## Guide to the Secure Configuration of Debian 12

> with profile CIS Debian Benchmark for Level 2 - Server
> This profile defines a baseline that aligns to the "Level 2 - Server" configuration from the Center for Internet Security® Debian 12 Benchmark™, v1.1.0, released 2024-09-26. This profile includes Center for Internet Security® Debian 12 Benchmark™ content.

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 12. 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 | CIS Debian Benchmark for Level 2 - Server
Profile ID | xccdf_org.ssgproject.content_profile_cis_level2_server

#### CPE Platforms

- cpe:/o:debian:debian_linux:12

## 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. zIPL bootloader configuration
   6. Configure Syslog
   7. Network Configuration and Firewalls
   8. File Permissions and Masks
2. Services
   1. Avahi Server
   2. Cron and At Daemons
   3. Deprecated services
   4. DHCP
   5. DNS Server
   6. FTP Server
   7. Web Server
   8. IMAP and POP3 Server
   9. LDAP
   10. Mail Server Software
   11. NFS and RPC
   12. Network Time Protocol
   13. Obsolete Services
   14. Print Support
   15. Proxy Server
   16. Samba(SMB) Microsoft Windows File Sharing Server
   17. SNMP Server
   18. SSH Server
   19. X Window System
3. System Accounting with auditd
   1. Configure auditd Rules for Comprehensive Auditing
   2. Configure auditd Data Retention
   3. System Accounting with auditd

## Checklist

Group Guide to the Secure Configuration of Debian 12 Group contains 117 groups and 507 rules
Group System Settings Group contains 57 groups and 309 rules
[ref] Contains rules that check correct system settings.
Group Installing and Maintaining Software Group contains 9 groups and 26 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 4 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 4 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 4 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
cis | 6.3.1
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
cis | 6.3.1
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=file:' ${AIDE_CONFIG}; then
        # replace_or_append gets confused by 'database=file' as a key, so should not be used.
        #replace_or_append "${AIDE_CONFIG}" '^database=file' "${DEFAULT_DB_PATH}" '@CCENUM@' '%s:%s'
        echo "database=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 AIDE to Verify the Audit Tools [ref]

The operating system file integrity tool must be configured to protect the integrity of the audit tools.

Rationale:

Protecting the integrity of the tools used for auditing purposes is a critical step toward ensuring the integrity of audit information. Audit information includes all information (e.g., audit records, audit settings, and audit reports) needed to successfully audit information system activity. Audit tools include but are not limited to vendor-provided and open-source audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators. It is not uncommon for attackers to replace the audit tools or inject code into the existing tools to provide the capability to hide or erase system activity from the audit logs. To address this risk, audit tools must be cryptographically signed to provide the capability to identify when the audit tools have been modified, manipulated, or replaced. An example is a checksum hash of the file or files.

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

References:

nist | AU-9(3), AU-9(3).1
os-srg | SRG-OS-000278-GPOS-00108
cis | 6.3.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$'; then

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

    if grep -i -E '^.*(/usr)?/sbin/auditctl.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/auditctl.*#/usr/sbin/auditctl p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/auditctl p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

    if grep -i -E '^.*(/usr)?/sbin/auditd.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/auditd.*#/usr/sbin/auditd p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/auditd p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

    if grep -i -E '^.*(/usr)?/sbin/ausearch.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/ausearch.*#/usr/sbin/ausearch p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/ausearch p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

    if grep -i -E '^.*(/usr)?/sbin/aureport.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/aureport.*#/usr/sbin/aureport p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/aureport p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

    if grep -i -E '^.*(/usr)?/sbin/autrace.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/autrace.*#/usr/sbin/autrace p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/autrace p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

    if grep -i -E '^.*(/usr)?/sbin/augenrules.*$' /etc/aide/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/augenrules.*#/usr/sbin/augenrules p+i+n+u+g+s+b+acl+selinux+xattrs+sha512#" /etc/aide/aide.conf
    else
    echo "/usr/sbin/augenrules p+i+n+u+g+s+b+acl+selinux+xattrs+sha512" >> /etc/aide/aide.conf
    fi

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

#### 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
cis | 6.3.2
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

Group Disk Partitioning Group contains 7 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 /dev/shm is configured [ref]

The `/dev/shm` is a traditional shared memory concept. One program will create a memory portion, which other processes (if permitted) can access. If `/dev/shm` is not configured, tmpfs will be mounted to /dev/shm by systemd. Warning: This rule does not have a remediation. It is expected that this will be managed by systemd and will be a tmpfs partition.

Rationale:

Any user can upload and execute files inside the `/dev/shm` similar to the `/tmp` partition. Configuring `/dev/shm` allows an administrator to set the noexec option on the mount, making /dev/shm useless for an attacker to install executable code. It would also prevent an attacker from establishing a hardlink to a system setuid program and wait for it to be updated. Once the program was updated, the hardlink would be broken and the attacker would have his own copy of the program. If the program happened to have a security vulnerability, the attacker could continue to exploit the known flaw.

Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_dev_shm

References:

cis | 1.1.2.2.1

#### 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
cis | 1.1.2.3.1

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

The `/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 `/tmp` partition is used as temporary storage by many programs. Placing `/tmp` in its own partition enables the setting of more restrictive mount options, which can help protect programs which use it.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_tmp

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
cis | 1.1.2.1.1

#### 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
cis | 1.1.2.4.1

#### 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
cis | 1.1.2.6.1

#### 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
cis | 1.1.2.7.1

#### 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
cis | 1.1.2.5.1

Group GNOME Desktop Environment Group contains 3 groups and 9 rules

[ref] GNOME is a graphical desktop environment bundled with many Linux distributions that allow users to easily interact with the operating system graphically rather than textually. The GNOME Graphical Display Manager (GDM) provides login, logout, and user switching contexts as well as display server management.
GNOME is developed by the GNOME Project and is considered the default Red Hat Graphical environment.
For more information on GNOME and the GNOME Project, see https://www.gnome.org.

Group Configure GNOME Login Screen Group contains 2 rules

[ref] In the default GNOME desktop, the login is displayed after system boot and can display user accounts, allow users to reboot the system, and allow users to login automatically and/or with a guest account. The login screen should be configured to prevent such behavior.
For more information about enforcing preferences in the GNOME3 environment using the DConf configuration system, see https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/desktop_migration_and_administration_guide/> and the man page `dconf(1)`.

#### Rule Disable the GNOME3 Login User List [ref]

In the default graphical environment, users logging directly into the system are greeted with a login screen that displays all known users. This functionality should be disabled by setting `disable-user-list` to `true`.
To disable, add or edit `disable-user-list` to `/etc/dconf/db/gdm.d/00-security-settings`. For example:

    [org/gnome/login-screen]
    disable-user-list=true

Once the setting has been added, add a lock to `/etc/dconf/db/gdm.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/login-screen/disable-user-list

After the settings have been set, run `dconf update`.

Rationale: | Leaving the user list enabled is a security risk since it allows anyone with physical access to the system to quickly enumerate known user accounts without logging in.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_user_list

References:

nist | CM-6(a), AC-23
os-srg | SRG-OS-000480-GPOS-00227
cis | 1.7.3

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/login-screen\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|gdm.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/gdm.d/00-security-settings"
    DBDIR="/etc/dconf/db/gdm.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*disable-user-list\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)disable-user-list(\s*=)/#\1disable-user-list\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "true")"
    if grep -q "^\\s*disable-user-list\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*disable-user-list\\s*=\\s*.*/disable-user-list=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/login-screen\\]|a\\disable-user-list=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/login-screen/disable-user-list$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|gdm.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/gdm.d/locks"

    mkdir -p "${LOCKSFOLDER}"

    # Comment out the configurations in databases different from the target one
    if [[ ! -z "${LOCKFILES}" ]]
    then
        sed -i -E "s|^/org/gnome/login-screen/disable-user-list$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/login-screen/disable-user-list$" /etc/dconf/db/gdm.d/
    then
        echo "/org/gnome/login-screen/disable-user-list" >> "/etc/dconf/db/gdm.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Disable XDMCP in GDM [ref]

XDMCP is an unencrypted protocol, and therefore, presents a security risk, see e.g. XDMCP Gnome docs. To disable XDMCP support in Gnome, set `Enable` to `false` under the `[xdmcp]` configuration section in `/etc/gdm3/daemon.conf`. For example:

    [xdmcp]
    Enable=false

Rationale: | XDMCP provides unencrypted remote access through the Gnome Display Manager (GDM) which does not provide for the confidentiality and integrity of user passwords or the remote session. If a privileged user were to login using XDMCP, the privileged user password could be compromised due to typed XEvents and keystrokes will traversing over the network in clear text.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_gnome_gdm_disable_xdmcp

References:

cis | 1.7.10

Remediation Shell script ⇲

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

    # Try find '[xdmcp]' and 'Enable' in '/etc/gdm3/daemon.conf', if it exists, set
    # to 'false', if it isn't here, add it, if '[xdmcp]' doesn't exist, add it there
    if grep -qzosP '[[:space:]]*\[xdmcp]([^\n\[]*\n+)+?[[:space:]]*Enable' '/etc/gdm3/daemon.conf'; then

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

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

Group GNOME Media Settings Group contains 3 rules
[ref] GNOME media settings that apply to the graphical interface.

#### Rule Disable GNOME3 Automounting [ref]

The system's default desktop environment, GNOME3, will mount devices and removable media (such as DVDs, CDs and USB flash drives) whenever they are inserted into the system. To disable automount within GNOME3, add or set `automount` to `false` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/media-handling]
    automount=false

Once the settings have been added, add a lock to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/media-handling/automount

After the settings have been set, run `dconf update`.

Rationale: | Disabling automatic mounting in GNOME3 can prevent the introduction of malware via removable media. It will, however, also prevent desktop users from legitimate use of removable media.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_automount

References:

cis-csc | 12, 16
cobit5 | APO13.01, DSS01.04, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03
cui | 3.1.7
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.2, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.4, SR 1.5, SR 1.9, SR 2.1, SR 2.6
iso27001-2013 | A.11.2.6, A.13.1.1, A.13.2.1, A.6.2.1, A.6.2.2, A.7.1.1, A.9.2.1
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.AC-6
os-srg | SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227
cis | 1.7.6, 1.7.7
pcidss4 | 3.4.2, 3.4

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/media-handling\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*automount\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)automount(\s*=)/#\1automount\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

    [ ! -z "${DCONFFILE}" ] && echo "" >> "${DCONFFILE}"
    if ! grep -q "\\[org/gnome/desktop/media-handling\\]" "${DCONFFILE}"
    then
        printf '%s\n' "[org/gnome/desktop/media-handling]" >> ${DCONFFILE}
    fi

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "false")"
    if grep -q "^\\s*automount\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*automount\\s*=\\s*.*/automount=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/media-handling\\]|a\\automount=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/media-handling/automount$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|local.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/local.d/locks"

    mkdir -p "${LOCKSFOLDER}"

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

    if ! grep -qr "^/org/gnome/desktop/media-handling/automount$" /etc/dconf/db/local.d/
    then
        echo "/org/gnome/desktop/media-handling/automount" >> "/etc/dconf/db/local.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Disable GNOME3 Automount Opening [ref]

The system's default desktop environment, GNOME3, will mount devices and removable media (such as DVDs, CDs and USB flash drives) whenever they are inserted into the system. To disable automount-open within GNOME3, add or set `automount-open` to `false` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/media-handling]
    automount-open=false

Once the settings have been added, add a lock to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/media-handling/automount-open

After the settings have been set, run `dconf update`.

Rationale: | Automatically mounting file systems permits easy introduction of unknown devices, thereby facilitating malicious activity. Disabling automatic mounting in GNOME3 can prevent the introduction of malware via removable media. It will, however, also prevent desktop users from legitimate use of removable media.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_automount_open

References:

cis-csc | 12, 16
cobit5 | APO13.01, DSS01.04, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03
cui | 3.1.7
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.2, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.4, SR 1.5, SR 1.9, SR 2.1, SR 2.6
iso27001-2013 | A.11.2.6, A.13.1.1, A.13.2.1, A.6.2.1, A.6.2.2, A.7.1.1, A.9.2.1
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.AC-6
os-srg | SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227
cis | 1.7.6, 1.7.7
pcidss4 | 3.4.2, 3.4

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/media-handling\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*automount-open\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)automount-open(\s*=)/#\1automount-open\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

    [ ! -z "${DCONFFILE}" ] && echo "" >> "${DCONFFILE}"
    if ! grep -q "\\[org/gnome/desktop/media-handling\\]" "${DCONFFILE}"
    then
        printf '%s\n' "[org/gnome/desktop/media-handling]" >> ${DCONFFILE}
    fi

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "false")"
    if grep -q "^\\s*automount-open\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*automount-open\\s*=\\s*.*/automount-open=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/media-handling\\]|a\\automount-open=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/media-handling/automount-open$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|local.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/local.d/locks"

    mkdir -p "${LOCKSFOLDER}"

    # Comment out the configurations in databases different from the target one
    if [[ ! -z "${LOCKFILES}" ]]
    then
        sed -i -E "s|^/org/gnome/desktop/media-handling/automount-open$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/desktop/media-handling/automount-open$" /etc/dconf/db/local.d/
    then
        echo "/org/gnome/desktop/media-handling/automount-open" >> "/etc/dconf/db/local.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Disable GNOME3 Automount running [ref]

The system's default desktop environment, GNOME3, will mount devices and removable media (such as DVDs, CDs and USB flash drives) whenever they are inserted into the system. To disable autorun-never within GNOME3, add or set `autorun-never` to `true` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/media-handling]
    autorun-never=true

Once the settings have been added, add a lock to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/media-handling/autorun-never

After the settings have been set, run `dconf update`.

Rationale: | Automatically mounting file systems permits easy introduction of unknown devices, thereby facilitating malicious activity. Disabling automatic mount running in GNOME3 can prevent the introduction of malware via removable media. It will, however, also prevent desktop users from legitimate use of removable media.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_autorun

References:

cis-csc | 12, 16
cobit5 | APO13.01, DSS01.04, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03
cui | 3.1.7
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.2, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.4, SR 1.5, SR 1.9, SR 2.1, SR 2.6
iso27001-2013 | A.11.2.6, A.13.1.1, A.13.2.1, A.6.2.1, A.6.2.2, A.7.1.1, A.9.2.1
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.AC-6
os-srg | SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227
cis | 1.7.8, 1.7.9

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/media-handling\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*autorun-never\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)autorun-never(\s*=)/#\1autorun-never\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

    [ ! -z "${DCONFFILE}" ] && echo "" >> "${DCONFFILE}"
    if ! grep -q "\\[org/gnome/desktop/media-handling\\]" "${DCONFFILE}"
    then
        printf '%s\n' "[org/gnome/desktop/media-handling]" >> ${DCONFFILE}
    fi

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "true")"
    if grep -q "^\\s*autorun-never\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*autorun-never\\s*=\\s*.*/autorun-never=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/media-handling\\]|a\\autorun-never=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/media-handling/autorun-never$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|local.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/local.d/locks"

    mkdir -p "${LOCKSFOLDER}"

    # Comment out the configurations in databases different from the target one
    if [[ ! -z "${LOCKFILES}" ]]
    then
        sed -i -E "s|^/org/gnome/desktop/media-handling/autorun-never$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/desktop/media-handling/autorun-never$" /etc/dconf/db/local.d/
    then
        echo "/org/gnome/desktop/media-handling/autorun-never" >> "/etc/dconf/db/local.d/locks/00-security-settings-lock"
    fi
    dconf update

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

Group Configure GNOME Screen Locking Group contains 3 rules

[ref] In the default GNOME3 desktop, the screen can be locked by selecting the user name in the far right corner of the main panel and selecting Lock.
The following sections detail commands to enforce idle activation of the screensaver, screen locking, a blank-screen screensaver, and an idle activation time.
Because users should be trained to lock the screen when they step away from the computer, the automatic locking feature is only meant as a backup.
The root account can be screen-locked; however, the root account should never be used to log into an X Windows environment and should only be used to for direct login via console in emergency circumstances.
For more information about enforcing preferences in the GNOME3 environment using the DConf configuration system, see http://wiki.gnome.org/dconf and the man page `dconf(1)`.

#### Rule Set GNOME3 Screensaver Inactivity Timeout [ref]

The idle time-out value for inactivity in the GNOME3 desktop is configured via the `idle-delay` setting must be set under an appropriate configuration file(s) in the `/etc/dconf/db/local.d` directory and locked in `/etc/dconf/db/local.d/locks` directory to prevent user modification.
For example, to configure the system for a 15 minute delay, add the following to `/etc/dconf/db/local.d/00-security-settings`:

    [org/gnome/desktop/session]
    idle-delay=uint32 900

Rationale:

A session time-out lock is a temporary action taken when a user stops work and moves away from the immediate physical vicinity of the information system but does not logout because of the temporary nature of the absence. Rather than relying on the user to manually lock their operating system session prior to vacating the vicinity, GNOME3 can be configured to identify when a user's session has idled and take action to initiate a session lock.

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

References:

cis-csc | 1, 12, 15, 16
cjis | 5.5.5
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.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 | AC-11(a), CM-6(a)
nist-csf | PR.AC-7
pcidss | Req-8.1.8
os-srg | SRG-OS-000029-GPOS-00010, SRG-OS-000031-GPOS-00012
cis | 1.7.4, 1.7.5
pcidss4 | 8.2.8, 8.2

Remediation Shell script ⇲

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

    inactivity_timeout_value='900'

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/session\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*idle-delay\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)idle-delay(\s*=)/#\1idle-delay\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "uint32 ${inactivity_timeout_value}")"
    if grep -q "^\\s*idle-delay\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*idle-delay\\s*=\\s*.*/idle-delay=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/session\\]|a\\idle-delay=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update

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

#### Rule Set GNOME3 Screensaver Lock Delay After Activation Period [ref]

To activate the locking delay of the screensaver in the GNOME3 desktop when the screensaver is activated, add or set `lock-delay` to `uint32 5` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/screensaver]
    lock-delay=uint32 5

After the settings have been set, run `dconf update`.

Rationale: | A session lock is a temporary action taken when a user stops work and moves away from the immediate physical vicinity of the information system but does not want to logout because of the temporary nature of the absence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_screensaver_lock_delay

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.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 | AC-11(a), CM-6(a)
nist-csf | PR.AC-7
pcidss | Req-8.1.8
os-srg | SRG-OS-000029-GPOS-00010, SRG-OS-000031-GPOS-00012
cis | 1.7.4, 1.7.5
pcidss4 | 8.2.8, 8.2

Remediation Shell script ⇲

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

    var_screensaver_lock_delay='5'

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/screensaver\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*lock-delay\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)lock-delay(\s*=)/#\1lock-delay\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "uint32 ${var_screensaver_lock_delay}")"
    if grep -q "^\\s*lock-delay\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*lock-delay\\s*=\\s*.*/lock-delay=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/screensaver\\]|a\\lock-delay=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update

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

#### Rule Enable GNOME3 Screensaver Lock After Idle Period [ref]

To activate locking of the screensaver in the GNOME3 desktop when it is activated, add or set `lock-enabled` to `true` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/screensaver]
    lock-enabled=true

Once the settings have been added, add a lock to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/screensaver/lock-enabled

After the settings have been set, run `dconf update`.

Rationale: | A session lock is a temporary action taken when a user stops work and moves away from the immediate physical vicinity of the information system but does not want to logout because of the temporary nature of the absence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_screensaver_lock_enabled

References:

cis-csc | 1, 12, 15, 16
cjis | 5.5.5
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.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)
nist-csf | PR.AC-7
pcidss | Req-8.1.8
os-srg | SRG-OS-000028-GPOS-00009, SRG-OS-000030-GPOS-00011
cis | 1.7.4, 1.7.5
pcidss4 | 8.2.8, 8.2

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/desktop/screensaver\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|local.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/local.d/00-security-settings"
    DBDIR="/etc/dconf/db/local.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*lock-enabled\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)lock-enabled(\s*=)/#\1lock-enabled\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "true")"
    if grep -q "^\\s*lock-enabled\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*lock-enabled\\s*=\\s*.*/lock-enabled=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/screensaver\\]|a\\lock-enabled=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/screensaver/lock-enabled$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|local.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/local.d/locks"

    mkdir -p "${LOCKSFOLDER}"

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

    if ! grep -qr "^/org/gnome/desktop/screensaver/lock-enabled$" /etc/dconf/db/local.d/
    then
        echo "/org/gnome/desktop/screensaver/lock-enabled" >> "/etc/dconf/db/local.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Remove the GDM Package Group [ref]

By removing the `gdm` package, the system no longer has GNOME installed. If X Windows is not installed then the system cannot boot into graphical user mode. This prevents the system from being accidentally or maliciously booted into a `graphical.target` mode. To do so, run the following command:

    $ sudo yum remove gdm

Rationale: | Unnecessary service packages must not be installed to decrease the attack surface of the system. A graphical environment is unnecessary for certain types of systems including a virtualization hypervisor.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_gdm_removed

References:

nist | CM-7(a), CM-7(b), CM-6(a)
os-srg | SRG-OS-000480-GPOS-00227
cis | 1.7.1

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}' 'gdm3' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove gdm
    # from the system, and may remove any packages
    # that depend on gdm. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "gdm"

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

Remediation Puppet snippet ⇲

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

    include remove_gdm

    class remove_gdm {
      package { 'gdm':
        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_gdm_removed

    - name: 'Remove the GDM Package Group: Ensure gdm is removed'
      ansible.builtin.package:
        name: gdm
        state: absent
      when: '"gdm3" 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_gdm_removed

Group Sudo Group contains 6 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
cis | 5.2.1
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 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
cis | 5.2.2
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 Sudo Logfile Exists - sudo logfile [ref]

A custom log sudo file can be configured with the 'logfile' tag. This rule configures a sudo custom logfile at the default location suggested by CIS, which uses /var/log/sudo.log.
Rationale: | A sudo log file simplifies auditing of sudo commands.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_custom_logfile

References:

pcidss | Req-10.2.5
cis | 5.2.3
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

    var_sudo_logfile='/var/log/sudo.log'

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

                escaped_variable=${var_sudo_logfile//$'/'/$'\/'}
                sed -Ei "s/(^[\s]*Defaults.*\blogfile=)[-]?.+(\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:
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_custom_logfile
    - name: XCCDF Value var_sudo_logfile # promote to variable
      set_fact:
        var_sudo_logfile: !!str /var/log/sudo.log
      tags:
        - always

    - name: Ensure logfile is enabled with the appropriate value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults\s(.*)\blogfile=[-]?.+\b(.*)$
        line: Defaults \1logfile={{ var_sudo_logfile }}\2
        validate: /usr/sbin/visudo -cf %s
        backrefs: true
      register: edit_sudoers_logfile_option
      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
      - low_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_custom_logfile

    - name: Enable logfile option with appropriate value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        line: Defaults logfile={{ var_sudo_logfile }}
        validate: /usr/sbin/visudo -cf %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - edit_sudoers_logfile_option is defined and not edit_sudoers_logfile_option.changed
      tags:
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_custom_logfile

#### Rule Ensure Users Re-Authenticate for Privilege Escalation - sudo !authenticate [ref]

The sudo `!authenticate` option, when specified, allows a user to execute commands using sudo without having to authenticate. This should be disabled by making sure that the `!authenticate` option does not exist in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Without re-authentication, users may access resources or perform tasks for which they do not have authorization. When operating systems provide the capability to escalate a functional capability, it is critical that the user re-authenticate.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_remove_no_authenticate

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.5.1, 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.3, SR 1.4, 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.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-11, CM-6(a)
nist-csf | PR.AC-1, PR.AC-7
os-srg | SRG-OS-000373-GPOS-00156, SRG-OS-000373-GPOS-00157, SRG-OS-000373-GPOS-00158
cis | 5.2.5
ism | 1546

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

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

    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-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_no_authenticate

    - name: Find /etc/sudoers.d/ files
      ansible.builtin.find:
        paths:
        - /etc/sudoers.d/
      register: sudoers
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_no_authenticate

    - name: Remove lines containing !authenticate from sudoers files
      ansible.builtin.replace:
        regexp: (^(?!#).*[\s]+\!authenticate.*$)
        replace: '# \g<1>'
        path: '{{ item.path }}'
        validate: /usr/sbin/visudo -cf %s
      with_items:
      - path: /etc/sudoers
      - '{{ sudoers.files }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_no_authenticate

#### Rule Ensure Users Re-Authenticate for Privilege Escalation - sudo [ref]

The sudo `NOPASSWD` and `!authenticate` option, when specified, allows a user to execute commands using sudo without having to authenticate. This should be disabled by making sure that `NOPASSWD` and/or `!authenticate` do not exist in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`."
Rationale: | Without re-authentication, users may access resources or perform tasks for which they do not have authorization. When operating systems provide the capability to escalate a functional capability, it is critical that the user re-authenticate.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_require_authentication

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.5.1, 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.3, SR 1.4, 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.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-11, CM-6(a)
nist-csf | PR.AC-1, PR.AC-7
os-srg | SRG-OS-000373-GPOS-00156
cis | 5.2.4
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

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

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

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

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

    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-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_authentication

    - name: Find /etc/sudoers.d/ files
      ansible.builtin.find:
        paths:
        - /etc/sudoers.d/
      register: sudoers
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_authentication

    - name: Remove lines containing NOPASSWD from sudoers files
      ansible.builtin.replace:
        regexp: (^(?!#).*[\s]+NOPASSWD[\s]*\:.*$)
        replace: '# \g<1>'
        path: '{{ item.path }}'
        validate: /usr/sbin/visudo -cf %s
      with_items:
      - path: /etc/sudoers
      - '{{ sudoers.files }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_authentication

    - name: Find /etc/sudoers.d/ files
      ansible.builtin.find:
        paths:
        - /etc/sudoers.d/
      register: sudoers
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_authentication

    - name: Remove lines containing !authenticate from sudoers files
      ansible.builtin.replace:
        regexp: (^(?!#).*[\s]+\!authenticate.*$)
        replace: '# \g<1>'
        path: '{{ item.path }}'
        validate: /usr/sbin/visudo -cf %s
      with_items:
      - path: /etc/sudoers
      - '{{ sudoers.files }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_authentication

#### Rule Require Re-Authentication When Using the sudo Command [ref]

The sudo `timestamp_timeout` tag sets the amount of time sudo password prompt waits. The default `timestamp_timeout` value is 5 minutes. The timestamp_timeout should be configured by making sure that the `timestamp_timeout` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`. If the value is set to an integer less than 0, the user's time stamp will not expire and the user will not have to re-authenticate for privileged actions until the user's session is terminated.

Rationale: | Without re-authentication, users may access resources or perform tasks for which they do not have authorization. When operating systems provide the capability to escalate a functional capability, it is critical that the user re-authenticate.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_require_reauthentication

References:

nist | IA-11
os-srg | SRG-OS-000373-GPOS-00156, SRG-OS-000373-GPOS-00157, SRG-OS-000373-GPOS-00158
cis | 5.2.6
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

    var_sudo_timestamp_timeout='15'

    if grep -Px '^[\s]*Defaults.*timestamp_timeout[\s]*=.*' /etc/sudoers.d/*; then
        find /etc/sudoers.d/ -type f -exec sed -Ei "/^[[:blank:]]*Defaults.*timestamp_timeout[[:blank:]]*=.*/d" {} \;
    fi

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults.*timestamp_timeout[\s]*=[\s]*[-]?\w+.*$' /etc/sudoers; then
            # sudoers file doesn't define Option timestamp_timeout
            echo "Defaults timestamp_timeout=${var_sudo_timestamp_timeout}" >> /etc/sudoers
        else
            # sudoers file defines Option timestamp_timeout, remediate wrong values if present
            if grep -qP "^[\s]*Defaults\s.*\btimestamp_timeout[\s]*=[\s]*(?!${var_sudo_timestamp_timeout}\b)[-]?\w+\b.*$" /etc/sudoers; then
                sed -Ei "s/(^[[:blank:]]*Defaults.*timestamp_timeout[[:blank:]]*=)[[:blank:]]*[-]?\w+(.*$)/\1${var_sudo_timestamp_timeout}\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:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication
    - name: XCCDF Value var_sudo_timestamp_timeout # promote to variable
      set_fact:
        var_sudo_timestamp_timeout: !!str 15
      tags:
        - always

    - name: Require Re-Authentication When Using the sudo Command - Find /etc/sudoers.d/*
        files containing 'Defaults timestamp_timeout'
      ansible.builtin.find:
        path: /etc/sudoers.d
        patterns: '*'
        contains: ^[\s]*Defaults\s.*\btimestamp_timeout[\s]*=.*
      register: sudoers_d_defaults_timestamp_timeout
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication

    - name: Require Re-Authentication When Using the sudo Command - Remove 'Defaults timestamp_timeout'
        from /etc/sudoers.d/* files
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^[\s]*Defaults\s.*\btimestamp_timeout[\s]*=.*
        state: absent
      with_items: '{{ sudoers_d_defaults_timestamp_timeout.files }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication

    - name: Require Re-Authentication When Using the sudo Command - Ensure timestamp_timeout
        has the appropriate value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults\s(.*)\btimestamp_timeout[\s]*=[\s]*[-]?\w+\b(.*)$
        line: Defaults \1timestamp_timeout={{ var_sudo_timestamp_timeout }}\2
        validate: /usr/sbin/visudo -cf %s
        backrefs: true
      register: edit_sudoers_timestamp_timeout_option
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication

    - name: Require Re-Authentication When Using the sudo Command - Enable timestamp_timeout
        option with correct value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        line: Defaults timestamp_timeout={{ var_sudo_timestamp_timeout }}
        validate: /usr/sbin/visudo -cf %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - |
        edit_sudoers_timestamp_timeout_option is defined and not edit_sudoers_timestamp_timeout_option.changed
      tags:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication

    - name: Require Re-Authentication When Using the sudo Command - Remove timestamp_timeout
        wrong values in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults\s.*\btimestamp_timeout[\s]*=[\s]*(?!{{ var_sudo_timestamp_timeout
          }}\b)[-]?\w+\b.*$
        state: absent
        validate: /usr/sbin/visudo -cf %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - NIST-800-53-IA-11
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_require_reauthentication

Group Account and Access Control Group contains 15 groups and 88 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 12.

Group Warning Banners for System Accesses Group contains 1 group and 14 rules

[ref] Each system should expose as little information about itself as possible.
System banners, which are typically displayed just before a login prompt, give out information about the service or the host's operating system. This might include the distribution name and the system kernel version, and the particular version of a network service. This information can assist intruders in gaining access to the system as it can reveal whether the system is running vulnerable software. Most network services can be configured to limit what information is displayed.
Many organizations implement security policies that require a system banner provide notice of the system's ownership, provide warning to unauthorized users, and remind authorized users of their consent to monitoring.

Group Implement a GUI Warning Banner Group contains 2 rules
[ref] In the default graphical environment, users logging directly into the system are greeted with a login screen provided by the GNOME Display Manager (GDM). The warning banner should be displayed in this graphical environment for these users. The following sections describe how to configure the GDM login banner.

#### Rule Enable GNOME3 Login Warning Banner [ref]

In the default graphical environment, displaying a login warning banner in the GNOME Display Manager's login screen can be enabled on the login screen by setting `banner-message-enable` to `true`.
To enable, add or edit `banner-message-enable` to `/etc/dconf/db/gdm.d/00-security-settings`. For example:

    [org/gnome/login-screen]
    banner-message-enable=true

Once the setting has been added, add a lock to `/etc/dconf/db/gdm.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/login-screen/banner-message-enable

After the settings have been set, run `dconf update`. The banner text must also be set.

Rationale:

Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance.
For U.S. Government systems, system use notifications are required only for access via login interfaces with human users and are not required when such human interfaces do not exist.

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

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.9
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 | AC-8(a), AC-8(b), AC-8(c)
nist-csf | PR.AC-7
os-srg | SRG-OS-000023-GPOS-00006, SRG-OS-000228-GPOS-00088
cis | 1.7.2

Remediation Shell script ⇲

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

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/login-screen\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|gdm.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/gdm.d/00-security-settings"
    DBDIR="/etc/dconf/db/gdm.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*banner-message-enable\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)banner-message-enable(\s*=)/#\1banner-message-enable\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "true")"
    if grep -q "^\\s*banner-message-enable\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*banner-message-enable\\s*=\\s*.*/banner-message-enable=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/login-screen\\]|a\\banner-message-enable=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/login-screen/banner-message-enable$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|gdm.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/gdm.d/locks"

    mkdir -p "${LOCKSFOLDER}"

    # Comment out the configurations in databases different from the target one
    if [[ ! -z "${LOCKFILES}" ]]
    then
        sed -i -E "s|^/org/gnome/login-screen/banner-message-enable$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/login-screen/banner-message-enable$" /etc/dconf/db/gdm.d/
    then
        echo "/org/gnome/login-screen/banner-message-enable" >> "/etc/dconf/db/gdm.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Set the GNOME3 Login Warning Banner Text [ref]

In the default graphical environment, configuring the login warning banner text in the GNOME Display Manager's login screen can be configured on the login screen by setting `banner-message-text` to `'APPROVED_BANNER'` where APPROVED_BANNER is the approved banner for your environment.
To enable, add or edit `banner-message-text` to `/etc/dconf/db/gdm.d/00-security-settings`. For example:

    [org/gnome/login-screen]
    banner-message-text='APPROVED_BANNER'

Once the setting has been added, add a lock to `/etc/dconf/db/gdm.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/login-screen/banner-message-text

After the settings have been set, run `dconf update`. When entering a warning banner that spans several lines, remember to begin and end the string with `'` and use `\n` for new lines.

Rationale: | An appropriate warning message reinforces policy awareness during the logon process and facilitates possible legal action against attackers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_login_banner_text

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.9
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 | AC-8(a), AC-8(c)
nist-csf | PR.AC-7
os-srg | SRG-OS-000023-GPOS-00006, SRG-OS-000228-GPOS-00088
cis | 1.7.2

Remediation Shell script ⇲

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

    login_banner_text='^Authorized[\s\n]+users[\s\n]+only\.[\s\n]+All[\s\n]+activity[\s\n]+may[\s\n]+be[\s\n]+monitored[\s\n]+and[\s\n]+reported\.$'

    # Multiple regexes transform the banner regex into a usable banner
    # 0 - Remove anchors around the banner text
    login_banner_text=$(echo "$login_banner_text" | sed 's/^\^\(.*\)\$$/\1/g')
    # 1 - Keep only the first banners if there are multiple
    #    (dod_banners contains the long and short banner)
    login_banner_text=$(echo "$login_banner_text" | sed 's/^(\(.*\.\)|.*)$/\1/g')
    # 2 - Add spaces ' '. (Transforms regex for "space or newline" into a " ")
    login_banner_text=$(echo "$login_banner_text" | sed 's/\[\\s\\n\]+/ /g')
    # 3 - Adds newline "tokens". (Transforms "(?:\[\\n\]+|(?:\\n)+)" into "(n)*")
    login_banner_text=$(echo "$login_banner_text" | sed 's/(?:\[\\n\]+|(?:\\\\n)+)/(n)*/g')
    # 4 - Remove any leftover backslash. (From any parenthesis in the banner, for example).
    login_banner_text=$(echo "$login_banner_text" | sed 's/\\//g')
    # 5 - Removes the newline "token." (Transforms them into newline escape sequences "\n").
    #    ( Needs to be done after 4, otherwise the escapce sequence will become just "n".
    login_banner_text=$(echo "$login_banner_text" | sed 's/(n)\*/\\n/g')

    # Check for setting in any of the DConf db directories
    # If files contain ibus or distro, ignore them.
    # The assignment assumes that individual filenames don't contain :
    readarray -t SETTINGSFILES < <(grep -r "\\[org/gnome/login-screen\\]" "/etc/dconf/db/" \
                                    | grep -v 'distro\|ibus\|gdm.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/gdm.d/00-security-settings"
    DBDIR="/etc/dconf/db/gdm.d"

    mkdir -p "${DBDIR}"

    # Comment out the configurations in databases different from the target one
    if [ "${#SETTINGSFILES[@]}" -ne 0 ]
    then
        if grep -q "^\\s*banner-message-text\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)banner-message-text(\s*=)/#\1banner-message-text\2/g" "${SETTINGSFILES[@]}"
        fi
    fi

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "'${login_banner_text}'")"
    if grep -q "^\\s*banner-message-text\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*banner-message-text\\s*=\\s*.*/banner-message-text=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/login-screen\\]|a\\banner-message-text=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/login-screen/banner-message-text$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|gdm.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/gdm.d/locks"

    mkdir -p "${LOCKSFOLDER}"

    # Comment out the configurations in databases different from the target one
    if [[ ! -z "${LOCKFILES}" ]]
    then
        sed -i -E "s|^/org/gnome/login-screen/banner-message-text$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/login-screen/banner-message-text$" /etc/dconf/db/gdm.d/
    then
        echo "/org/gnome/login-screen/banner-message-text" >> "/etc/dconf/db/gdm.d/locks/00-security-settings-lock"
    fi
    dconf update

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

#### Rule Ensure Local Login Warning Banner Is Configured Properly [ref]

To configure the system local login warning banner edit the `/etc/issue` file. The contents of this file is displayed to users prior to login to local terminals. Replace the default text with a message compliant with the local site policy. The message should not contain information about operating system version, release, kernel version or patch level. The recommended banner text can be tailored in the XCCDF Value `xccdf_org.ssgproject.content_value_cis_banner_text`:

    Authorized users only. All activity may be monitored and reported.

Rationale:

Warning messages inform users who are attempting to login to the system of their legal status regarding the system and must include the name of the organization that owns the system and any monitoring policies that are in place. Displaying OS and patch level information in login banners also has the side effect of providing detailed system information to attackers attempting to target specific exploits of a system. Authorized users can easily get this information by running the `uname -a` command once they have logged in.

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

References:

cis | 1.6.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

    cis_banner_text='Authorized users only. All activity may be monitored and reported.'

    echo "$cis_banner_text" > "/etc/issue"

    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:
      - banner_etc_issue_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value cis_banner_text # promote to variable
      set_fact:
        cis_banner_text: !!str Authorized users only. All activity may be monitored and reported.
      tags:
        - always

    - name: Ensure Local Login Warning Banner Is Configured Properly - Copy using inline
        content
      ansible.builtin.copy:
        content: '{{ cis_banner_text }}'
        dest: /etc/issue
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - banner_etc_issue_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure Remote Login Warning Banner Is Configured Properly [ref]

To configure the system remote login warning banner edit the `/etc/issue.net` file. The contents of this file is displayed to users prior to login from remote connections. Replace the default text with a message compliant with the local site policy. The message should not contain information about operating system version, release, kernel version or patch level. The recommended banner text can be tailored in the XCCDF Value `xccdf_org.ssgproject.content_value_cis_banner_text`:

    Authorized users only. All activity may be monitored and reported.

Rationale:

Warning messages inform users who are attempting to login to the system of their legal status regarding the system and must include the name of the organization that owns the system and any monitoring policies that are in place. Displaying OS and patch level information in login banners also has the side effect of providing detailed system information to attackers attempting to target specific exploits of a system. Authorized users can easily get this information by running the `uname -a` command once they have logged in.

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

References:

cis | 1.6.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$'; then

    cis_banner_text='Authorized users only. All activity may be monitored and reported.'

    echo "$cis_banner_text" > "/etc/issue.net"

    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:
      - banner_etc_issue_net_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value cis_banner_text # promote to variable
      set_fact:
        cis_banner_text: !!str Authorized users only. All activity may be monitored and reported.
      tags:
        - always

    - name: Ensure Remote Login Warning Banner Is Configured Properly - Copy using inline
        content
      ansible.builtin.copy:
        content: '{{ cis_banner_text }}'
        dest: /etc/issue.net
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - banner_etc_issue_net_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure Message Of The Day Is Configured Properly [ref]

To configure the system message of the day banner edit the `/etc/motd` file. Replace the default text with a message compliant with the local site policy. The message should not contain information about operating system version, release, kernel version or patch level. The recommended banner text can be tailored in the XCCDF Value `xccdf_org.ssgproject.content_value_cis_banner_text`:

    Authorized users only. All activity may be monitored and reported.

Rationale:

Warning messages inform users who are attempting to login to the system of their legal status regarding the system and must include the name of the organization that owns the system and any monitoring policies that are in place. Displaying OS and patch level information in login banners also has the side effect of providing detailed system information to attackers attempting to target specific exploits of a system. Authorized users can easily get this information by running the `uname -a` command once they have logged in.

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

References:

cis | 1.6.1

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

    cis_banner_text='Authorized users only. All activity may be monitored and reported.'

    echo "$cis_banner_text" > "/etc/motd"

    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:
      - banner_etc_motd_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value cis_banner_text # promote to variable
      set_fact:
        cis_banner_text: !!str Authorized users only. All activity may be monitored and reported.
      tags:
        - always

    - name: Ensure Message Of The Day Is Configured Properly - Copy using inline content
      ansible.builtin.copy:
        content: '{{ cis_banner_text }}'
        dest: /etc/motd
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - banner_etc_motd_cis
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify Group Ownership of System Login Banner [ref]

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

    $ sudo chgrp root /etc/issue

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper group ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_issue

References:

cis | 1.6.5

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/issue" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/issue
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_etc_issue_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_issue_newgroup: '0'
      tags:
      - configure_strategy
      - file_groupowner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/issue
      ansible.builtin.stat:
        path: /etc/issue
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/issue
      ansible.builtin.file:
        path: /etc/issue
        follow: false
        group: '{{ file_groupowner_etc_issue_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Ownership of System Login Banner for Remote Connections [ref]

To properly set the group owner of `/etc/issue.net`, run the command:

    $ sudo chgrp root /etc/issue.net

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper group ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_issue_net

References:

cis | 1.6.6
pcidss4 | 1.2.8, 1.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/issue.net" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/issue.net
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_etc_issue_net_newgroup variable if represented by
        gid
      ansible.builtin.set_fact:
        file_groupowner_etc_issue_net_newgroup: '0'
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_groupowner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/issue.net
      ansible.builtin.stat:
        path: /etc/issue.net
      register: file_exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_groupowner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/issue.net
      ansible.builtin.file:
        path: /etc/issue.net
        follow: false
        group: '{{ file_groupowner_etc_issue_net_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_groupowner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Ownership of Message of the Day Banner [ref]

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

    $ sudo chgrp root /etc/motd

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper group ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_motd

References:

cis | 1.6.4

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/motd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/motd
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_etc_motd_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_motd_newgroup: '0'
      tags:
      - configure_strategy
      - file_groupowner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/motd
      ansible.builtin.stat:
        path: /etc/motd
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/motd
      ansible.builtin.file:
        path: /etc/motd
        follow: false
        group: '{{ file_groupowner_etc_motd_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify ownership of System Login Banner [ref]

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

    $ sudo chown root /etc/issue

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_issue

References:

cis | 1.6.5

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/issue" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/issue
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_etc_issue_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_issue_newown: '0'
      tags:
      - configure_strategy
      - file_owner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/issue
      ansible.builtin.stat:
        path: /etc/issue
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/issue
      ansible.builtin.file:
        path: /etc/issue
        follow: false
        owner: '{{ file_owner_etc_issue_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify ownership of System Login Banner for Remote Connections [ref]

To properly set the owner of `/etc/issue.net`, run the command:

    $ sudo chown root /etc/issue.net

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_issue_net

References:

cis | 1.6.6
pcidss4 | 1.2.8, 1.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/issue.net" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/issue.net
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_etc_issue_net_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_issue_net_newown: '0'
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_owner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/issue.net
      ansible.builtin.stat:
        path: /etc/issue.net
      register: file_exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_owner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/issue.net
      ansible.builtin.file:
        path: /etc/issue.net
        follow: false
        owner: '{{ file_owner_etc_issue_net_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_owner_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify ownership of Message of the Day Banner [ref]

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

    $ sudo chown root /etc/motd

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper ownership will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_motd

References:

cis | 1.6.4

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/motd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/motd
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_etc_motd_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_motd_newown: '0'
      tags:
      - configure_strategy
      - file_owner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/motd
      ansible.builtin.stat:
        path: /etc/motd
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/motd
      ansible.builtin.file:
        path: /etc/motd
        follow: false
        owner: '{{ file_owner_etc_motd_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify permissions on System Login Banner [ref]

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

    $ sudo chmod 0644 /etc/issue

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper permissions will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_issue

References:

cis | 1.6.5

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwt /etc/issue

Remediation Ansible snippet ⇲

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

    - name: Test for existence /etc/issue
      ansible.builtin.stat:
        path: /etc/issue
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/issue
      ansible.builtin.file:
        path: /etc/issue
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_issue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify permissions on System Login Banner for Remote Connections [ref]

To properly set the permissions of `/etc/issue.net`, run the command:

    $ sudo chmod 0644 /etc/issue.net

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper permissions will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_issue_net

References:

cis | 1.6.6
pcidss4 | 1.2.8, 1.2

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwt /etc/issue.net

Remediation Ansible snippet ⇲

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

    - name: Test for existence /etc/issue.net
      ansible.builtin.stat:
        path: /etc/issue.net
      register: file_exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_permissions_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/issue.net
      ansible.builtin.file:
        path: /etc/issue.net
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.8
      - configure_strategy
      - file_permissions_etc_issue_net
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify permissions on Message of the Day Banner [ref]

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

    $ sudo chmod 0644 /etc/motd

Rationale: | Display of a standardized and approved use notification before granting access to the operating system ensures privacy and security notification verbiage used is consistent with applicable federal laws, Executive Orders, directives, policies, regulations, standards, and guidance. Proper permissions will ensure that only root user can modify the banner.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_motd

References:

cis | 1.6.4

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwt /etc/motd

Remediation Ansible snippet ⇲

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

    - name: Test for existence /etc/motd
      ansible.builtin.stat:
        path: /etc/motd
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/motd
      ansible.builtin.file:
        path: /etc/motd
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_motd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Protect Accounts by Configuring PAM Group contains 4 groups and 28 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 9 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 Verify pam_pwhistory module is activated [ref]

The `pam_pwhistory.so` module is part of the Pluggable Authentication Modules (PAM) framework designed to increase password security. It works by storing a history of previously used passwords for each user, ensuring users cannot alternate between the same passwords too frequently.
This module is incompatible with Kerberos. Furthermore, its usage with `NIS` or `LDAP` is generally impractical, as other machines can not access local password histories.

Rationale: | Enforcing strong passwords increases the difficulty and resources required for password compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_pwhistory_enabled

References:

cis | 5.3.2.4

#### Rule Limit Password Reuse [ref]

Do not allow root to reuse recent passwords. This can be accomplished by using the `enforce_for_root` option for the `pam_pwhistory` PAM modules. In the file `/etc/pam.d/common-password`, make sure the parameters `enforce_for_root` is present.
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_pwhistory_enforce_root

References:

cis | 5.3.3.3.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}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    if [ -f /usr/bin/authselect ]; then
        if authselect list-features sssd | grep -q with-pwhistory; 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-pwhistory

            authselect apply-changes -b
        else

            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 "cac_pwhistory")
            PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

            authselect apply-changes -b

            if ! grep -qP "^\s*password\s+requisite\s+pam_pwhistory.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_pwhistory.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_pwhistory.so.*)/\1requisite \2/" "$PAM_FILE_PATH"
                else
                    echo "password    requisite    pam_pwhistory.so" >> "$PAM_FILE_PATH"
                fi
            fi
        fi
    else

    conf_name=cac_pwhistory
    conf_path="/usr/share/pam-configs"

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

    DEBIAN_FRONTEND=noninteractive pam-auth-update

    fi
    conf_file=/usr/share/pam-configs/cac_pwhistory
    if ! grep -qE 'pam_pwhistory\.so\s+[^#\n]*\benforce_for_root\b' "$conf_file"; then
    	sed -i -E '/^Password:/,/^[^[:space:]]/ {
        /pam_pwhistory\.so/ {
            s/$/ enforce_for_root/g
        }
        }' "$conf_file"

        sed -i -E '/^Password-Initial:/,/^[^[:space:]]/ {
        /pam_pwhistory\.so/ {
            s/$/ enforce_for_root/g
        }
        }' "$conf_file"
    fi

    DEBIAN_FRONTEND=noninteractive pam-auth-update --enable cac_pwhistory

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

#### 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_pwhistory` PAM modules.
In the file `/etc/pam.d/common-password`, make sure the parameters `remember` and `use_authtok` are present, and that the value for the `remember` parameter is 24 or greater. For example:

    password requisite pam_pwhistory.so ...existing_options... remember=24 use_authtok

The profile requirement is 24 passwords.

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_pwhistory_remember

References:

os-srg | SRG-OS-000077-GPOS-00045
cis | 5.3.3.3.1

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}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    declare -a VALUES=()
    declare -a VALUE_NAMES=()
    declare -a ARGS=()
    declare -a NEW_ARGS=()
    declare -a DEL_ARGS=()

    var_password_pam_remember='24'

    VALUES+=("$var_password_pam_remember")
    VALUE_NAMES+=("remember")
    ARGS+=("")
    NEW_ARGS+=("")

    VALUES+=("")
    VALUE_NAMES+=("")
    ARGS+=("use_authtok")
    NEW_ARGS+=("use_authtok")

    for idx in "${!VALUES[@]}"
    do
        if [ -e "/etc/pam.d/common-password" ] ; then
            valueRegex="${VALUES[$idx]}" defaultValue="${VALUES[$idx]}"
            # non-empty values need to be preceded by an equals sign
            [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
            # add an equals sign to non-empty values
            [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

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

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

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

    for idx in "${!ARGS[@]}"
    do
        if ! grep -q -P "^\s*password\s+requisite\s+pam_pwhistory.so.*\s+${ARGS[$idx]}\s*$" /etc/pam.d/common-password ; then
            sed --follow-symlinks -i -E -e "s/^\\s*password\\s+requisite\\s+pam_pwhistory.so.*\$/& ${NEW_ARGS[$idx]}/" /etc/pam.d/common-password
            if [ -n "${DEL_ARGS[$idx]}" ]; then
                sed --follow-symlinks -i -E -e "s/\s+${DEL_ARGS[$idx]}\S+\s+/ /g" /etc/pam.d/common-password
            fi
        fi
    done

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

#### Rule Enforce Password History with use_authtok [ref]

The `use_authtok` option ensures the pam_pwhistory module uses the new password provided by a previously stacked PAM module during password changes, rather than prompting the user again.
Rationale: | The `use_authtok` option allows multiple PAM modules to validate the new password before it is accepted, ensuring it meets all security requirements without requiring the user to re-enter it multiple times.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_pwhistory_use_authtok

References:

cis | 5.3.3.3.3

#### Rule Require use_authtok for pam_unix.so [ref]

When password changing enforce the module to set the new password to the one provided by a previously stacked password module
Rationale: | Require use_authtok in pam_unix.so configuration
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_unix_authtok

References:

cis | 5.3.3.4.4

#### 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 4 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
cis | 5.3.3.1.1
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='4'

    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 Ensure pam_faillock module is enabled [ref]

The `pam_faillock.so` module maintains a list of failed authentication attempts per user during a specified interval and locks the account in case there were more than the configured number of consecutive failed authentications (this is defined by the `deny` parameter in the faillock configuration). It stores the failure records into per-user files in the tally directory.
Rationale: | Locking out user IDs after n unsuccessful consecutive login attempts mitigates brute force password attacks against your systems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_enabled

References:

cis | 5.3.2.2

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

This rule configures the system to lock out root 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: `root_unlock_time=<interval-in-seconds>` where `interval-in-seconds` is `900` or greater. If `root_unlock_time` is set to `0`, it may enable attacker to apply denial of service to legitimate users.

Rationale: | By limiting the number of failed logon attempts the risk of unauthorized root access via 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_root_unlock_time

References:

cis | 5.3.3.1.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_root_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*root_unlock_time\s*="
        line="root_unlock_time = $var_accounts_passwords_pam_faillock_root_unlock_time"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        else
            sed -i --follow-symlinks 's|^\s*\(root_unlock_time\s*=\s*\)\(\S\+\)|\1'"$var_accounts_passwords_pam_faillock_root_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.*\broot_unlock_time\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\broot_unlock_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).*root_unlock_time' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ root_unlock_time='"$var_accounts_passwords_pam_faillock_root_unlock_time"'/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ root_unlock_time='"$var_accounts_passwords_pam_faillock_root_unlock_time"'/' "$pam_file"
            else
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"root_unlock_time"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_root_unlock_time"'\3/' "$pam_file"
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"root_unlock_time"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_root_unlock_time"'\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
cis | 5.3.3.1.2
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 13 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 13 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
cis | 5.3.3.2.3
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'

    # 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 - Prevent the Use of Dictionary Words [ref]

The pam_pwquality module's `dictcheck` check if passwords contains dictionary words. When `dictcheck` is set to `1` passwords will be checked for dictionary words.

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.
Passwords with dictionary words may be more vulnerable to password-guessing attacks.

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

References:

nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
os-srg | SRG-OS-000480-GPOS-00225, SRG-OS-000072-GPOS-00040
cis | 5.3.3.2.6

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_dictcheck='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' <<< "^dictcheck")

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

    # 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 "^dictcheck\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^dictcheck\\>.*/$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_dictcheck
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_dictcheck # promote to variable
      set_fact:
        var_password_pam_dictcheck: !!str 1
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Prevent the Use of Dictionary
        Words - Ensure PAM variable dictcheck is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*dictcheck
        line: dictcheck = {{ var_password_pam_dictcheck }}
      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_dictcheck
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

The pam_pwquality module's `difok` parameter sets the number of characters in a password that must not be present in and old password during a password change. Modify the `difok` setting in `/etc/security/pwquality.conf` to equal 2 to require differing 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 different characters during password changes ensures that newly changed passwords should not resemble previously compromised ones. Note that passwords which are changed on compromised systems will still be compromised, however.

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

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)(b), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000072-GPOS-00040
cis | 5.3.3.2.1

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_difok='2'

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

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

    # 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 "^difok\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^difok\\>.*/$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)(b)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_difok
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_difok # promote to variable
      set_fact:
        var_password_pam_difok: !!str 2
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Different Characters -
        Ensure PAM variable difok is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*difok
        line: difok = {{ var_password_pam_difok }}
      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)(b)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_difok
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Enforce for root User [ref]

The pam_pwquality module's `enforce_for_root` parameter controls requirements for enforcing password complexity for the root user. Enable the `enforce_for_root` setting in `/etc/security/pwquality.conf` to require the `root` user to use complex 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_enforce_root

References:

nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
os-srg | SRG-OS-000072-GPOS-00040, SRG-OS-000071-GPOS-00039, SRG-OS-000070-GPOS-00038, SRG-OS-000266-GPOS-00101, SRG-OS-000078-GPOS-00046, SRG-OS-000480-GPOS-00225, SRG-OS-000069-GPOS-00037
cis | 5.3.3.2.8

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

    if [ -e "/etc/security/pwquality.conf" ] ; then

        LC_ALL=C sed -i "/^\s*enforce_for_root/Id" "/etc/security/pwquality.conf"
    else
        touch "/etc/security/pwquality.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/security/pwquality.conf"

    cp "/etc/security/pwquality.conf" "/etc/security/pwquality.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "enforce_for_root" >> "/etc/security/pwquality.conf"
    # Clean up after ourselves.
    rm "/etc/security/pwquality.conf.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:
      - 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_enforce_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Enforce for root User
      ansible.builtin.lineinfile:
        path: /etc/security/pwquality.conf
        create: true
        regexp: ''
        line: enforce_for_root
        state: present
      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_enforce_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Enforcing [ref]

Verify that the operating system uses "pwquality" to enforce the password complexity rules. Verify the pwquality module is being enforced by operating system by running the following command:

    $ grep -i enforcing /etc/security/pwquality.conf
    enforcing = 1

If the value of "enforcing" is not "1" or the line is commented out, this is a finding.

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. Using enforcing=1 ensures "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_accounts_password_pam_enforcing

References:

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

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

    if [ -e "/etc/security/pwquality.conf" ] ; then

        LC_ALL=C sed -i "/^\s*enforcing = 1/Id" "/etc/security/pwquality.conf"
    else
        touch "/etc/security/pwquality.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/security/pwquality.conf"

    cp "/etc/security/pwquality.conf" "/etc/security/pwquality.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "enforcing = 1" >> "/etc/security/pwquality.conf"
    # Clean up after ourselves.
    rm "/etc/security/pwquality.conf.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:
      - accounts_password_pam_enforcing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Enforcing
      ansible.builtin.lineinfile:
        path: /etc/security/pwquality.conf
        create: true
        regexp: ''
        line: enforcing = 1
        state: present
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - accounts_password_pam_enforcing
      - 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
cis | 5.3.3.2.3
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'

    # 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 Set Password Maximum Consecutive Repeating Characters [ref]

The pam_pwquality module's `maxrepeat` parameter controls requirements for consecutive repeating characters. When set to a positive number, it will reject passwords which contain more than that number of consecutive characters. Modify the `maxrepeat` setting in `/etc/security/pwquality.conf` to equal 3 to prevent a run of (3 + 1) or more identical characters.

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.
Passwords with excessive repeating characters may be more vulnerable to password-guessing attacks.

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

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), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000072-GPOS-00040
cis | 5.3.3.2.4

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_maxrepeat='3'

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

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

    # 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 "^maxrepeat\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^maxrepeat\\>.*/$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(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_maxrepeat
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_maxrepeat # promote to variable
      set_fact:
        var_password_pam_maxrepeat: !!str 3
      tags:
        - always

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

#### Rule Limit the maximum number of sequential characters in passwords [ref]

The `pwquality maxsequence` setting defines the maximum allowable length for consecutive character sequences in a new password. Such sequences can be, e.g., 123 or abc. If the value is set to 0, this check will be turned off.
Note: Passwords that consist mainly of such sequences are unlikely to meet the simplicity criteria unless the sequence constitutes only a small portion of the overall password.

Rationale:

Use of a strong 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 important factor that determines the duration required to crack it. A more intricate password results in a larger number of potential combinations that must be tested before successfully compromising the password.

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

References:

cis | 5.3.3.2.5

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_maxsequence='3'

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

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

    # 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 "^maxsequence\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^maxsequence\\>.*/$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:
      - accounts_password_pam_maxsequence
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_maxsequence # promote to variable
      set_fact:
        var_password_pam_maxsequence: !!str 3
      tags:
        - always

    - name: Limit the maximum number of sequential characters in passwords - Ensure PAM
        variable maxsequence is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*maxsequence
        line: maxsequence = {{ var_password_pam_maxsequence }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - accounts_password_pam_maxsequence
      - 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
cis | 5.3.3.2.3
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'

    # 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=14` 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
cis | 5.3.3.2.2
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='14'

    # 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 14
      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
cis | 5.3.3.2.3
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'

    # 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 Verify pam_pwquality module is activated [ref]

The `pam_pwquality.so` module ensures password quality by evaluating user-created passwords against a system dictionary and a set of rules designed to detect weak choices. Originally derived from the pam_cracklib module, this module is backward-compatible with options of pam_cracklib.
The module's process includes prompting the user for a password, checking its strength, and if it meets the criteria requesting the password again for confirmation. If both entries match, the password is passed to subsequent modules to be set as the new authentication token.

Rationale: | Strong passwords significantly increase the time and effort required for unauthorized access, increasing overall system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_pwquality_enabled

References:

cis | 5.3.2.3

#### 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
cis | 5.3.3.2.3
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'

    # 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 2 rules
[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
cis | 5.4.1.4
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 Set PAM''s Password Hashing Algorithm [ref]

The PAM system service can be configured to only store encrypted representations of passwords. In "/etc/pam.d/common-password", the `password` section of the file controls which PAM modules to execute during a password change. Set the `pam_unix.so` module in the `password` section to include the option `yescrypt` and no other hashing algorithms as shown below:

    password    [success=1 default=ignore]   pam_unix.so yescrypt
              other arguments...

This will help ensure that new passwords for local users will be stored using the yescrypt algorithm.
Warning: The hashing algorithms to be used with pam_unix.so are defined with independent module options. There are at least 7 possible algorithms and likely more algorithms will be introduced along the time. Due the the number of options and its possible combinations, the use of multiple hashing algorithm options may bring unexpected behaviors to the system. For this reason the check will pass only when one hashing algorithm option is defined and is aligned to the "var_password_hashing_algorithm_pam" variable. The remediation will ensure the correct option and remove any other extra hashing algorithm option.

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.
This setting ensures user and group account administration utilities are configured to store only encrypted representations of passwords. Additionally, the `crypt_style` configuration option in `/etc/libuser.conf` ensures the use of a strong hashing algorithm that makes password cracking attacks more difficult.

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

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, SRG-OS-000120-GPOS-00061
anssi | R68
cis | 5.3.3.4.3
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}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_hashing_algorithm_pam='yescrypt'

    conf_name=cac_unix
    conf_path="/usr/share/pam-configs"

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

    # Ensure all the hashing algorithm option is removed.
    declare -a HASHING_ALGORITHMS_OPTIONS=("sha512" "yescrypt" "gost_yescrypt" "blowfish" "sha256" "md5" "bigcrypt")

    for hash_option in "${HASHING_ALGORITHMS_OPTIONS[@]}"; do
      sed -i -E '/^Password:/,/^[^[:space:]]/ {
        /pam_unix\.so/ {
          s/\s*\b'"$hash_option"'\b//g
        }
        }' "$PAM_FILE_PATH"
        sed -i -E '/^Password-Initial:/,/^[^[:space:]]/ {
        /pam_unix\.so/ {
          s/\s*\b'"$hash_option"'\b//g
        }
        }' "$PAM_FILE_PATH"
        DEBIAN_FRONTEND=noninteractive pam-auth-update
    done

    if ! grep -qzP "Password:\s*\n\s+.*\s+pam_unix.so\s+.*\b$var_password_hashing_algorithm_pam\b" "$PAM_FILE_PATH"; then
      sed -i -E '/^Password:/,/^[^[:space:]]/ {
        /pam_unix\.so/ {
            s/$/ '"$var_password_hashing_algorithm_pam"'/g
        }
    }' "$PAM_FILE_PATH"
    fi

    if ! grep -qzP "Password-Initial:\s*\n\s+.*\s+pam_unix.so\s+.*\b$var_password_hashing_algorithm_pam\b" "$PAM_FILE_PATH"; then
      sed -i -E '/^Password-Initial:/,/^[^[:space:]]/ {
        /pam_unix\.so/ {
            s/$/ '"$var_password_hashing_algorithm_pam"'/g
        }
    }' "$PAM_FILE_PATH"
    fi

    DEBIAN_FRONTEND=noninteractive pam-auth-update

    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.2
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_systemauth
    - name: XCCDF Value var_password_hashing_algorithm_pam # promote to variable
      set_fact:
        var_password_hashing_algorithm_pam: !!str yescrypt
      tags:
        - always

    - name: Set PAM's Password Hashing Algorithm - Check if /etc/pam.d/system-auth file
        is present
      ansible.builtin.stat:
        path: /etc/pam.d/system-auth
      register: result_pam_file_present
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_systemauth

    - name: Set PAM's Password Hashing Algorithm - Check the proper remediation for the
        system
      block:

      - name: Set PAM's Password Hashing Algorithm - Define the PAM file to be edited
          as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/system-auth

      - name: Set PAM's Password Hashing Algorithm - Check if system relies on authselect
          tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Set PAM's Password Hashing Algorithm - Ensure authselect custom profile
          is used if authselect is present
        block:

        - name: Set PAM's Password Hashing Algorithm - Check integrity of authselect current
            profile
          ansible.builtin.command:
            cmd: authselect check
          register: result_authselect_check_cmd
          changed_when: false
          check_mode: false
          failed_when: false

        - name: Set PAM's Password Hashing Algorithm - Informative message based on the
            authselect integrity check result
          ansible.builtin.assert:
            that:
            - ansible_check_mode or result_authselect_check_cmd.rc == 0
            fail_msg:
            - authselect integrity check failed. Remediation aborted!
            - This remediation could not be applied because an authselect profile was
              not selected or the selected profile is not intact.
            - It is not recommended to manually edit the PAM files when authselect tool
              is available.
            - In cases where the default authselect profile does not cover a specific
              demand, a custom authselect profile is recommended.
            success_msg:
            - authselect integrity check passed

        - name: Set PAM's Password Hashing Algorithm - Get authselect current profile
          ansible.builtin.shell:
            cmd: authselect current -r | awk '{ print $1 }'
          register: result_authselect_profile
          changed_when: false
          when:
          - result_authselect_check_cmd is success

        - name: Set PAM's Password Hashing Algorithm - Define the current authselect profile
            as a local fact
          ansible.builtin.set_fact:
            authselect_current_profile: '{{ result_authselect_profile.stdout }}'
            authselect_custom_profile: '{{ result_authselect_profile.stdout }}'
          when:
          - result_authselect_profile is not skipped
          - result_authselect_profile.stdout is match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Define the new authselect custom
            profile as a local fact
          ansible.builtin.set_fact:
            authselect_current_profile: '{{ result_authselect_profile.stdout }}'
            authselect_custom_profile: custom/hardening
          when:
          - result_authselect_profile is not skipped
          - result_authselect_profile.stdout is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Get authselect current features
            to also enable them in the custom profile
          ansible.builtin.shell:
            cmd: authselect current | tail -n+3 | awk '{ print $2 }'
          register: result_authselect_features
          changed_when: false
          check_mode: false
          when:
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Check if any custom profile with
            the same name was already created
          ansible.builtin.stat:
            path: /etc/authselect/{{ authselect_custom_profile }}
          register: result_authselect_custom_profile_present
          changed_when: false
          when:
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Create an authselect custom profile
            based on the current profile
          ansible.builtin.command:
            cmd: authselect create-profile hardening -b {{ authselect_current_profile
              }}
          when:
          - result_authselect_profile is not skipped
          - result_authselect_check_cmd is success
          - authselect_current_profile is not match("^(custom/|local)")
          - not result_authselect_custom_profile_present.stat.exists

        - name: Set PAM's Password Hashing Algorithm - Create an authselect custom profile
            based on sssd profile
          ansible.builtin.command:
            cmd: authselect create-profile hardening -b sssd
          when:
          - result_authselect_profile is not skipped
          - result_authselect_check_cmd is success
          - authselect_current_profile is match("local")
          - not result_authselect_custom_profile_present.stat.exists

        - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b --backup=before-hardening-custom-profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")
          - authselect_custom_profile is not match(authselect_current_profile)

        - name: Set PAM's Password Hashing Algorithm - Ensure the authselect custom profile
            is selected
          ansible.builtin.command:
            cmd: authselect select {{ authselect_custom_profile }}
          register: result_pam_authselect_select_profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")
          - authselect_custom_profile is not match(authselect_current_profile)

        - name: Set PAM's Password Hashing Algorithm - Restore the authselect features
            in the custom profile
          ansible.builtin.command:
            cmd: authselect enable-feature {{ item }}
          loop: '{{ result_authselect_features.stdout_lines }}'
          register: result_pam_authselect_restore_features
          when:
          - result_authselect_profile is not skipped
          - result_authselect_features is not skipped
          - result_pam_authselect_select_profile is not skipped

        - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b --backup=after-hardening-custom-profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - result_pam_authselect_restore_features is not skipped

        - name: Set PAM's Password Hashing Algorithm - Change the PAM file to be edited
            according to the custom authselect profile
          ansible.builtin.set_fact:
            pam_file_path: /etc/authselect/{{ authselect_custom_profile }}/{{ pam_file_path
              | basename }}
          when:
          - authselect_custom_profile is defined
        when:
        - result_authselect_present.stat.exists

      - name: Set PAM's Password Hashing Algorithm - Define a fact for control already
          filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set PAM's Password Hashing Algorithm - Check if expected PAM module line
          is present in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          regexp: ^\s*password\s+{{ pam_module_control | regex_escape() }}\s+pam_unix.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Set PAM's Password Hashing Algorithm - Include or update the PAM module
          line in {{ pam_file_path }}
        block:

        - name: Set PAM's Password Hashing Algorithm - Check if required PAM module line
            is present in {{ pam_file_path }} with different control
          ansible.builtin.lineinfile:
            path: '{{ pam_file_path }}'
            regexp: ^\s*password\s+.*\s+pam_unix.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Set PAM's Password Hashing Algorithm - Ensure the correct control for
            the required PAM module line in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: ^(\s*password\s+).*(\bpam_unix.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Set PAM's Password Hashing Algorithm - Ensure the required PAM module
            line is included in {{ pam_file_path }}
          ansible.builtin.lineinfile:
            dest: '{{ pam_file_path }}'
            line: password    {{ pam_module_control }}    pam_unix.so
          register: result_pam_module_add
          when:
          - result_pam_line_other_control_present.found == 0 or result_pam_line_other_control_present.found
            > 1

        - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present is defined
          - result_authselect_present.stat.exists
          - |-
            (result_pam_module_add is defined and result_pam_module_add.changed)
             or (result_pam_module_edit is defined and result_pam_module_edit.changed)
        when:
        - result_pam_line_present.found is defined
        - result_pam_line_present.found == 0

      - name: Set PAM's Password Hashing Algorithm - Define a fact for control already
          filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set PAM's Password Hashing Algorithm - Check if the required PAM module
          option is present in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          regexp: ^\s*password\s+{{ pam_module_control | regex_escape() }}\s+pam_unix.so\s*.*\s{{
            var_password_hashing_algorithm_pam }}\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_set_password_hashing_algorithm_systemauth_option_present

      - name: Set PAM's Password Hashing Algorithm - Ensure the "{{ var_password_hashing_algorithm_pam
          }}" PAM option for "pam_unix.so" is included in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          backrefs: true
          regexp: ^(\s*password\s+{{ pam_module_control | regex_escape() }}\s+pam_unix.so.*)
          line: \1 {{ var_password_hashing_algorithm_pam }}
          state: present
        register: result_pam_set_password_hashing_algorithm_systemauth_add
        when:
        - result_pam_module_set_password_hashing_algorithm_systemauth_option_present.found
          is defined
        - result_pam_module_set_password_hashing_algorithm_systemauth_option_present.found
          == 0

      - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - |-
          (result_pam_set_password_hashing_algorithm_systemauth_add is defined and result_pam_set_password_hashing_algorithm_systemauth_add.changed)
           or (result_pam_set_password_hashing_algorithm_systemauth_edit is defined and result_pam_set_password_hashing_algorithm_systemauth_edit.changed)
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - CJIS-5.6.2.2
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_systemauth

    - name: Set PAM's Password Hashing Algorithm - Check if /etc/pam.d/system-auth File
        is Present
      ansible.builtin.stat:
        path: /etc/pam.d/system-auth
      register: result_pam_file_present
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_systemauth

    - name: Set PAM's Password Hashing Algorithm - Check The Proper Remediation For The
        System
      block:

      - name: Set PAM's Password Hashing Algorithm - Define the PAM file to be edited
          as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/system-auth

      - name: Set PAM's Password Hashing Algorithm - Check if system relies on authselect
          tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Set PAM's Password Hashing Algorithm - Ensure authselect custom profile
          is used if authselect is present
        block:

        - name: Set PAM's Password Hashing Algorithm - Check integrity of authselect current
            profile
          ansible.builtin.command:
            cmd: authselect check
          register: result_authselect_check_cmd
          changed_when: false
          check_mode: false
          failed_when: false

        - name: Set PAM's Password Hashing Algorithm - Informative message based on the
            authselect integrity check result
          ansible.builtin.assert:
            that:
            - ansible_check_mode or result_authselect_check_cmd.rc == 0
            fail_msg:
            - authselect integrity check failed. Remediation aborted!
            - This remediation could not be applied because an authselect profile was
              not selected or the selected profile is not intact.
            - It is not recommended to manually edit the PAM files when authselect tool
              is available.
            - In cases where the default authselect profile does not cover a specific
              demand, a custom authselect profile is recommended.
            success_msg:
            - authselect integrity check passed

        - name: Set PAM's Password Hashing Algorithm - Get authselect current profile
          ansible.builtin.shell:
            cmd: authselect current -r | awk '{ print $1 }'
          register: result_authselect_profile
          changed_when: false
          when:
          - result_authselect_check_cmd is success

        - name: Set PAM's Password Hashing Algorithm - Define the current authselect profile
            as a local fact
          ansible.builtin.set_fact:
            authselect_current_profile: '{{ result_authselect_profile.stdout }}'
            authselect_custom_profile: '{{ result_authselect_profile.stdout }}'
          when:
          - result_authselect_profile is not skipped
          - result_authselect_profile.stdout is match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Define the new authselect custom
            profile as a local fact
          ansible.builtin.set_fact:
            authselect_current_profile: '{{ result_authselect_profile.stdout }}'
            authselect_custom_profile: custom/hardening
          when:
          - result_authselect_profile is not skipped
          - result_authselect_profile.stdout is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Get authselect current features
            to also enable them in the custom profile
          ansible.builtin.shell:
            cmd: authselect current | tail -n+3 | awk '{ print $2 }'
          register: result_authselect_features
          changed_when: false
          check_mode: false
          when:
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Check if any custom profile with
            the same name was already created
          ansible.builtin.stat:
            path: /etc/authselect/{{ authselect_custom_profile }}
          register: result_authselect_custom_profile_present
          changed_when: false
          when:
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")

        - name: Set PAM's Password Hashing Algorithm - Create an authselect custom profile
            based on the current profile
          ansible.builtin.command:
            cmd: authselect create-profile hardening -b {{ authselect_current_profile
              }}
          when:
          - result_authselect_profile is not skipped
          - result_authselect_check_cmd is success
          - authselect_current_profile is not match("^(custom/|local)")
          - not result_authselect_custom_profile_present.stat.exists

        - name: Set PAM's Password Hashing Algorithm - Create an authselect custom profile
            based on sssd profile
          ansible.builtin.command:
            cmd: authselect create-profile hardening -b sssd
          when:
          - result_authselect_profile is not skipped
          - result_authselect_check_cmd is success
          - authselect_current_profile is match("local")
          - not result_authselect_custom_profile_present.stat.exists

        - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b --backup=before-hardening-custom-profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")
          - authselect_custom_profile is not match(authselect_current_profile)

        - name: Set PAM's Password Hashing Algorithm - Ensure the authselect custom profile
            is selected
          ansible.builtin.command:
            cmd: authselect select {{ authselect_custom_profile }}
          register: result_pam_authselect_select_profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - authselect_current_profile is not match("custom/")
          - authselect_custom_profile is not match(authselect_current_profile)

        - name: Set PAM's Password Hashing Algorithm - Restore the authselect features
            in the custom profile
          ansible.builtin.command:
            cmd: authselect enable-feature {{ item }}
          loop: '{{ result_authselect_features.stdout_lines }}'
          register: result_pam_authselect_restore_features
          when:
          - result_authselect_profile is not skipped
          - result_authselect_features is not skipped
          - result_pam_authselect_select_profile is not skipped

        - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b --backup=after-hardening-custom-profile
          when:
          - result_authselect_check_cmd is success
          - result_authselect_profile is not skipped
          - result_pam_authselect_restore_features is not skipped

        - name: Set PAM's Password Hashing Algorithm - Change the PAM file to be edited
            according to the custom authselect profile
          ansible.builtin.set_fact:
            pam_file_path: /etc/authselect/{{ authselect_custom_profile }}/{{ pam_file_path
              | basename }}
          when:
          - authselect_custom_profile is defined
        when:
        - result_authselect_present.stat.exists

      - name: Set PAM's Password Hashing Algorithm - Check if "{{ pam_file_path }}" File
          is Present
        ansible.builtin.stat:
          path: '{{ pam_file_path }}'
        register: pam_file_path_present

      - name: Set PAM's Password Hashing Algorithm - Ensure That Only the Correct Hashing
          Algorithm Option For pam_unix.so Is Used in {{ pam_file_path }}
        ansible.builtin.replace:
          dest: '{{ pam_file_path }}'
          regexp: (^\s*password.*pam_unix\.so.*)\b{{ item }}\b\s*(.*)
          replace: \1\2
        when:
        - item != var_password_hashing_algorithm_pam
        - pam_file_path_present.stat.exists
        loop:
        - sha512
        - yescrypt
        - gost_yescrypt
        - blowfish
        - sha256
        - md5
        - bigcrypt
        register: result_pam_hashing_options_removal

      - name: Set PAM's Password Hashing Algorithm - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - result_pam_hashing_options_removal is changed
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - CJIS-5.6.2.2
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_systemauth

#### Rule Install pam-modules Package [ref]

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

    $ apt-get install libpam-modules

Rationale: | libpam-modules contains PAM modules that are needed by other rules when configuring PAM options.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_pam_modules_installed

References:

cis | 5.3.1.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}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; then

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

    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-modules

    class install_libpam-modules {
      package { 'libpam-modules':
        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_modules_installed

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

Remediation OSBuild Blueprint snippet ⇲

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

#### 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
cis | 5.3.1.3

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 = "*"

#### Rule Install pam-runtime Package [ref]

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

    $ apt-get install libpam-runtime

Rationale: | libpam-runtime contains configuration that is needed by other rules when configuring PAM options.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_pam_runtime_installed

References:

cis | 5.3.1.1

Remediation Shell script ⇲

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

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

Remediation Puppet snippet ⇲

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

    include install_libpam-runtime

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

Remediation Ansible snippet ⇲

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

    - name: Ensure libpam-runtime is installed
      ansible.builtin.package:
        name: libpam-runtime
        state: present
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pam_runtime_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Verify pam_unix module is activated [ref]

`pam_unix` is the standard Unix authentication module. It uses standard calls from the system's libraries to retrieve and set account information as well as authentication. Usually this is obtained from the `/etc/passwd` and if shadow is enabled, the `/etc/shadow` file as well.
The account component performs the task of establishing the status of the user's account and password based on the following shadow elements: `expire, last_change, max_change, min_change, warn_change`. In the case of the latter, it may offer advice to the user on changing their password or, through the `PAM_AUTHTOKEN_REQD` return, delay giving service to the user until they have established a new password. The entries listed above are documented in the shadow(5) manual page. Should the user's record not contain one or more of these entries, the corresponding shadow check is not performed.
The authentication component performs the task of checking the users credentials (password). The default action of this module is to not permit the user access to a service if their official password is blank.

Rationale: | The system should only provide access after performing authentication of a user.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_unix_enabled

References:

cis | 5.3.2.1

Group Protect Accounts by Restricting Password-Based Login Group contains 4 groups and 29 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 Account Expiration Parameters Group contains 3 rules

[ref] Accounts can be configured to be automatically disabled after a certain time period, meaning that they will require administrator interaction to become usable again. Expiration of accounts after inactivity can be set for all accounts by default and also on a per-account basis, such as for accounts that are known to be temporary. To configure automatic expiration of an account following the expiration of its password (that is, after the password has expired and not been changed), run the following command, substituting `NUM_DAYS` and `USER` appropriately:

    $ sudo chage -I NUM_DAYS USER

Accounts, such as temporary accounts, can also be configured to expire on an explicitly-set date with the `-E` option. The file `/etc/default/useradd` controls default settings for all newly-created accounts created with the system's normal command line utilities.
Warning: This will only apply to newly created accounts

#### Rule Set Account Expiration Following Inactivity [ref]

To specify the number of days after a password expires (which signifies inactivity) until an account is permanently disabled, add or correct the following line in `/etc/default/useradd`:

    INACTIVE=45

If a password is currently on the verge of expiration, then `45` day(s) remain(s) until the account is automatically disabled. However, if the password will not expire for another 60 days, then 60 days plus `45` day(s) could elapse until the account would be automatically disabled. See the `useradd` man page for more information.

Rationale:

Inactive identifiers pose a risk to systems and applications because attackers may exploit an inactive identifier and potentially obtain undetected access to the system. Disabling inactive accounts ensures that accounts which may not have been responsibly removed are not available to attackers who may have compromised their credentials. Owners of inactive accounts will not notice if unauthorized access to their user account has been obtained.

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

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5, 7, 8
cjis | 5.6.2.1.1
cobit5 | DSS01.03, DSS03.05, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.5.6
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
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.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
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 | IA-4(e), AC-2(3), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7
pcidss | Req-8.1.4
os-srg | SRG-OS-000118-GPOS-00060
cis | 5.4.1.5
pcidss4 | 8.2.6, 8.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}' 'login' 2>/dev/null | grep -q '^installed$'; }; then

    var_account_disable_post_pw_expiration='45'

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

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

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

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

#### Rule Ensure All Accounts on the System Have Unique Names [ref]

Ensure accounts on the system have unique names. To ensure all accounts have unique names, run the following command:

    $ sudo getent passwd | awk -F: '{ print $1}' | uniq -d

If a username is returned, change or delete the username.

Rationale: | Unique usernames allow for accountability on the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_unique_name

References:

cjis | 5.5.2
pcidss | Req-8.1.1
cis | 7.2.7
pcidss4 | 8.2.1, 8.2

#### Rule Ensure shadow Group is Empty [ref]

The shadow group allows system programs which require access the ability to read the /etc/shadow file. No users should be assigned to the shadow group. Warning: This rule remediation will ensure the group membership is empty in /etc/group. To avoid any disruption the remediation won't change the primary group of users in /etc/passwd if any user has the shadow GID as primary group.

Rationale:

Any users assigned to the shadow group would be granted read access to the /etc/shadow file. If attackers can gain read access to the /etc/shadow file, they can easily run a password cracking program against the hashed passwords to break them. Other security information that is stored in the /etc/shadow file (such as expiration) could also be useful to subvert additional user accounts.

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

References:

pcidss | Req-8.2.1
cis | 7.2.4
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$'; then

    sed -ri 's/(^shadow:[^:]*:[^:]*:)([^:]+$)/\1/' /etc/group

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - ensure_shadow_group_empty
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure interactive local users are the owners of their respective initialization
        files
      ansible.builtin.lineinfile:
        dest: /etc/group
        backrefs: true
        regexp: (^shadow:[^:]*:[^:]*:)([^:]+$)
        line: \1
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-8.2.1
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.2
      - ensure_shadow_group_empty
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Set Password Expiration Parameters Group contains 6 rules

[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 Password Maximum Age [ref]

To specify password maximum age for new accounts, edit the file `/etc/login.defs` and add or correct the following line:

    PASS_MAX_DAYS 365

The profile requirement is `365`.

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.
Setting the password maximum age ensures users are required to periodically change their passwords. Requiring shorter password lifetimes increases the risk of users writing down the password in a convenient location subject to physical compromise.

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

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.6.2.1
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.5.6
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)(d), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
pcidss | Req-8.2.4
os-srg | SRG-OS-000076-GPOS-00044
cis | 5.4.1.1
ism | 0418, 1055, 1402
pcidss4 | 8.3.9, 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_accounts_maximum_age_login_defs='365'

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

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

    # 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 "^PASS_MAX_DAYS\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^PASS_MAX_DAYS\\>.*/$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:
      - CJIS-5.6.2.1
      - NIST-800-171-3.5.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.4
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.9
      - accounts_maximum_age_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_maximum_age_login_defs # promote to variable
      set_fact:
        var_accounts_maximum_age_login_defs: !!str 365
      tags:
        - always

    - name: Set Password Maximum Age
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/login.defs
        regexp: ^#?PASS_MAX_DAYS
        line: PASS_MAX_DAYS {{ var_accounts_maximum_age_login_defs }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"login" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1
      - NIST-800-171-3.5.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.4
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.9
      - accounts_maximum_age_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Set Password Minimum Age [ref]

To specify password minimum age for new accounts, edit the file `/etc/login.defs` and add or correct the following line:

    PASS_MIN_DAYS 1

A value of 1 day is considered sufficient for many environments. The profile requirement is `1`.

Rationale:

Enforcing a minimum password lifetime helps to prevent repeated password changes to defeat the password reuse or history enforcement requirement. If users are allowed to immediately and continually change their password, then the password could be repeatedly changed in a short period of time to defeat the organization's policy regarding password reuse.
Setting the minimum password age protects against users cycling back to a favorite password after satisfying the password reuse requirement.

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

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)(d), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000075-GPOS-00043
cis | 5.4.1.2
ism | 0418, 1055, 1402

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_minimum_age_login_defs='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' <<< "^PASS_MIN_DAYS")

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

    # 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 "^PASS_MIN_DAYS\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^PASS_MIN_DAYS\\>.*/$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 Set Existing Passwords Maximum Age [ref]

Configure non-compliant accounts to enforce a 365-day maximum password lifetime restriction by running the following command:

    $ sudo chage -M 365
              USER

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_existing

References:

nist | IA-5(f), IA-5(1)(d), CM-6(a)
os-srg | SRG-OS-000076-GPOS-00044
cis | 5.4.1.1
pcidss4 | 8.3.9, 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$'; then

    var_accounts_maximum_age_login_defs='365'

    while IFS= read -r i; do

        chage -M $var_accounts_maximum_age_login_defs $i

    done <   <(awk -v var="$var_accounts_maximum_age_login_defs" -F: '(/^[^:]+:[^!*]/ && ($5 > var || $5 == "")) {print $1}' /etc/shadow)

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

#### Rule Set Existing Passwords Minimum Age [ref]

Configure non-compliant accounts to enforce a 24 hours/1 day minimum password lifetime by running the following command:

    $ sudo chage -m 1 USER

Rationale: | Enforcing a minimum password lifetime helps to prevent repeated password changes to defeat the password reuse or history enforcement requirement. If users are allowed to immediately and continually change their password, the password could be repeatedly changed in a short period of time to defeat the organization's policy regarding password reuse.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_set_min_life_existing

References:

nist | IA-5(f), IA-5(1)(d), CM-6(a)
os-srg | SRG-OS-000075-GPOS-00043
cis | 5.4.1.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

    var_accounts_minimum_age_login_defs='1'

    while IFS= read -r i; do

        chage -m $var_accounts_minimum_age_login_defs $i

    done <   <(awk -v var="$var_accounts_minimum_age_login_defs" -F: '(/^[^:]+:[^!*]/ && ($4 < var || $4 == "")) {print $1}' /etc/shadow)

    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)(d)
      - NIST-800-53-IA-5(f)
      - accounts_password_set_min_life_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_minimum_age_login_defs # promote to variable
      set_fact:
        var_accounts_minimum_age_login_defs: !!str 1
      tags:
        - always

    - name: Collect users with not correct minimum time period between password changes
      ansible.builtin.command: |
        awk -F':' '(/^[^:]+:[^!*]/ && ($4 < {{ var_accounts_minimum_age_login_defs }} || $4 == "")) {print $1}' /etc/shadow
      register: user_names
      changed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - accounts_password_set_min_life_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Change the minimum time period between password changes
      ansible.builtin.command: |
        chage -m {{ var_accounts_minimum_age_login_defs }} {{ item }}
      with_items: '{{ user_names.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - user_names.stdout_lines | length > 0
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - accounts_password_set_min_life_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Set Password Warning Age [ref]

To specify how many days prior to password expiration that a warning will be issued to users, edit the file `/etc/login.defs` and add or correct the following line:

    PASS_WARN_AGE 7

The profile requirement is `7`.

Rationale: | Setting the password warning age enables users to make the change at a practical time.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_warn_age_login_defs

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5, 7, 8
cobit5 | DSS01.03, DSS03.05, 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.3, 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, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.3, 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 | IA-5(f), IA-5(1)(d), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7
pcidss | Req-8.2.4
cis | 5.4.1.3
ism | 0418, 1055, 1402
pcidss4 | 8.3.9, 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_accounts_password_warn_age_login_defs='7'

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

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

    # 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 "^PASS_WARN_AGE\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^PASS_WARN_AGE\\>.*/$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 Set existing passwords a period of inactivity before they been locked [ref]

Configure user accounts that have been inactive for over a given period of time to be automatically disabled by running the following command:

    $ sudo chage --inactive 30 USER

Rationale: | Inactive accounts pose a threat to system security since the users are not logging in to notice failed login attempts or other anomalies.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_set_post_pw_existing

References:

cobit5 | DSS01.03, DSS03.05, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.5.6
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
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.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
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 | IA-4(e), AC-2(3), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7
pcidss | Req-8.1.4
os-srg | SRG-OS-000118-GPOS-00060
cis | 5.4.1.5
pcidss4 | 8.2.6, 8.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

    var_account_disable_post_pw_expiration='45'

    while IFS= read -r i; do
        chage --inactive $var_account_disable_post_pw_expiration $i
    done <   <(awk -v var="$var_account_disable_post_pw_expiration" -F: '(($7 > var || $7 == "") && $2 ~ /^\$/) {print $1}' /etc/shadow)

    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.5.6
      - NIST-800-53-AC-2(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-4(e)
      - PCI-DSS-Req-8.1.4
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.6
      - accounts_set_post_pw_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_account_disable_post_pw_expiration # promote to variable
      set_fact:
        var_account_disable_post_pw_expiration: !!str 45
      tags:
        - always

    - name: Collect users with not correct INACTIVE parameter set
      ansible.builtin.command:
        cmd: awk -F':' '(($7 > {{ var_account_disable_post_pw_expiration }} || $7 == "")
          && $2 ~ /^\$/) {print $1}' /etc/shadow
      register: user_names
      changed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.5.6
      - NIST-800-53-AC-2(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-4(e)
      - PCI-DSS-Req-8.1.4
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.6
      - accounts_set_post_pw_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Change the period of inactivity
      ansible.builtin.command:
        cmd: chage --inactive {{ var_account_disable_post_pw_expiration }} {{ item }}
      with_items: '{{ user_names.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - user_names is not skipped and user_names.stdout_lines | length > 0
      tags:
      - NIST-800-171-3.5.6
      - NIST-800-53-AC-2(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-4(e)
      - PCI-DSS-Req-8.1.4
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.6
      - accounts_set_post_pw_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Verify Proper Storage and Existence of Password Hashes Group contains 8 rules

[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 Verify All Account Password Hashes are Shadowed [ref]

If any password hashes are stored in `/etc/passwd` (in the second field, instead of an `x` or `*`), the cause of this misconfiguration should be investigated. The account should have its password reset and the hash should be properly stored, or the account should be deleted entirely.
Rationale: | The hashes for all user account passwords should be stored in the file `/etc/shadow` and never in `/etc/passwd`, which is readable by all users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_all_shadowed

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.5.2
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.5.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(h), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
pcidss | Req-8.2.1
cis | 7.2.1
ism | 1402
pcidss4 | 8.3.2, 8.3

#### Rule Ensure all users last password change date is in the past [ref]

All users should have a password change date in the past. Warning: Automatic remediation is not available, in order to avoid any system disruption.
Rationale: | If a user recorded password change date is in the future then they could bypass any set password expiration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_last_change_is_in_past

References:

cis | 5.4.1.6
pcidss4 | 8.3.5, 8.3

#### Rule Avoid using remember in pam_unix module [ref]

The `remember` option stores the last n passwords for each user in `/etc/security/opasswd`, enforcing password history and preventing users from reusing the same passwords. However, this feature relies on the MD5 password hash algorithm, which is less secure. Instead, the `pam_pwhistory` module should be used. This module also stores the last n passwords in `/etc/security/opasswd` and it uses the password hash algorithm configured in the pam_unix module, such as yescrypt or SHA512, offering enhanced security.

Rationale: | Removing the `remember` argument ensures the use of a stronger password hashing algorithm. A more robust hash algorithm increases the difficulty for attackers to crack stored passwords in `/etc/security/opasswd`, thereby improving system security and protecting user credentials.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_unix_no_remember

References:

cis | 5.3.3.4.2

#### Rule All GIDs referenced in /etc/passwd must be defined in /etc/group [ref]

Add a group to the system for each GID referenced without a corresponding group.
Rationale: | If a user is assigned the Group Identifier (GID) of a group not existing on the system, and a group with the Group Identifier (GID) is subsequently created, the user may have unintended rights to any files associated with the group.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_gid_passwd_group_same

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.5.2
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
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
pcidss | Req-8.5.a
os-srg | SRG-OS-000104-GPOS-00051
cis | 7.2.3
pcidss4 | 8.2.2, 8.2

#### Rule Ensure There Are No Accounts With Blank or Null Passwords [ref]

Check the "/etc/shadow" file for blank passwords with the following command:

    $ sudo awk -F: '!$2 {print $1}' /etc/shadow

If the command returns any results, this is a finding. Configure all accounts on the system to have a password or lock the account with the following commands: Perform a password reset:

    $ sudo passwd [username]

Lock an account:

    $ sudo passwd -l [username]

Warning: Note that this rule is not applicable for systems running within a container. Having user with empty password within a container is not considered a risk, because it should not be possible to directly login into a container anyway.

Rationale: | If an account has an empty password, anyone could log in and run commands with the privileges of that account. Accounts with empty passwords should never be used in operational environments.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_no_empty_passwords_etc_shadow

References:

nist | CM-6(b), CM-6.1(iv)
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.2
pcidss4 | 2.2.2, 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

    readarray -t users_with_empty_pass < <(sudo awk -F: '!$2 {print $1}' /etc/shadow)

    for user_with_empty_pass in "${users_with_empty_pass[@]}"
    do
        passwd -l $user_with_empty_pass
    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(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.2
      - high_severity
      - low_complexity
      - low_disruption
      - no_empty_passwords_etc_shadow
      - no_reboot_needed
      - restrict_strategy

    - name: Collect users with no password
      ansible.builtin.command: |
        awk -F: '!$2 {print $1}' /etc/shadow
      register: users_nopasswd
      changed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.2
      - high_severity
      - low_complexity
      - low_disruption
      - no_empty_passwords_etc_shadow
      - no_reboot_needed
      - restrict_strategy

    - name: Lock users with no password
      ansible.builtin.command: |
        passwd -l {{ item }}
      with_items: '{{ users_nopasswd.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - users_nopasswd is not skipped and users_nopasswd.stdout_lines | length > 0
      tags:
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.2
      - high_severity
      - low_complexity
      - low_disruption
      - no_empty_passwords_etc_shadow
      - no_reboot_needed
      - restrict_strategy

#### Rule Prevent Login to Accounts With Empty Password [ref]

If an account is configured for password authentication but does not have an assigned password, it may be possible to log into the account without authentication. Remove any instances of the `nullok` in `/etc/pam.d/common-{password,auth,account,session,session-noninteractive}` to prevent logins with empty passwords.
Rationale: | If an account has an empty password, anyone could log in and run commands with the privileges of that account. Accounts with empty passwords should never be used in operational environments.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_no_empty_passwords_unix

References:

cis | 5.3.3.4.1

Remediation Shell script ⇲

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

    # 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

    conf_name=cac_unix
    conf_path="/usr/share/pam-configs"

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

    DEBIAN_FRONTEND=noninteractive pam-auth-update

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

#### Rule Verify No .forward Files Exist [ref]

The `.forward` file specifies an email address to forward the user's mail to.
Rationale: | Use of the `.forward` file poses a security risk in that sensitive data may be inadvertently transferred outside the organization. The .forward file also poses a risk as it can be used to execute commands that may perform unintended actions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_forward_files

References:

cis | 7.2.10

#### Rule Verify No netrc Files Exist [ref]

The `.netrc` files contain login information used to auto-login into FTP servers and reside in the user's home directory. These files may contain unencrypted passwords to remote FTP servers making them susceptible to access by unauthorized users and should not be used. Any `.netrc` files should be removed.
Rationale: | Unencrypted passwords for remote FTP servers may be stored in `.netrc` files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_netrc_files

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
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
nerc-cip | CIP-003-8 R1.3, CIP-003-8 R3, CIP-003-8 R3.1, CIP-003-8 R3.2, CIP-003-8 R3.3, 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-5(h), IA-5(1)(c), CM-6(a), IA-5(7)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.PT-3
cis | 7.2.10

Group Restrict Root Logins Group contains 8 rules

[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 Verify Only Root Has UID 0 [ref]

If any account other than root has a UID of 0, this misconfiguration should be investigated and the accounts other than root should be removed or have their UID changed. If the account is associated with system commands or applications the UID should be changed to one greater than "0" but less than "1000." Otherwise assign a UID greater than "1000" that has not already been assigned.
Rationale: | An account has root authority if it has a UID of 0. Multiple accounts with a UID of 0 afford more opportunity for potential intruders to guess a password for a privileged account. Proper configuration of sudo is recommended to afford multiple system administrators access to root privileges in an accountable manner.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_no_uid_except_zero

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.10
cui | 3.1.1, 3.1.5
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
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 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 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, AC-6(5), IA-4(b)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5
pcidss | Req-8.5
os-srg | SRG-OS-000480-GPOS-00227
cis | 5.4.2.1
ism | 1546
pcidss4 | 8.2.1, 8.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

    awk -F: '$3 == 0 && $1 != "root" { print $1 }' /etc/passwd | xargs --no-run-if-empty --max-lines=1 passwd -l

    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.5
      - NIST-800-53-AC-6(5)
      - NIST-800-53-IA-2
      - NIST-800-53-IA-4(b)
      - PCI-DSS-Req-8.5
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.1
      - accounts_no_uid_except_zero
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Get all /etc/passwd file entries
      ansible.builtin.getent:
        database: passwd
        split: ':'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-AC-6(5)
      - NIST-800-53-IA-2
      - NIST-800-53-IA-4(b)
      - PCI-DSS-Req-8.5
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.1
      - accounts_no_uid_except_zero
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Lock the password of the user accounts other than root with uid 0
      ansible.builtin.command: passwd -l {{ item.key }}
      loop: '{{ getent_passwd | dict2items | rejectattr(''key'', ''search'', ''root'')
        | list }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value.1  == '0'
      tags:
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-AC-6(5)
      - NIST-800-53-IA-2
      - NIST-800-53-IA-4(b)
      - PCI-DSS-Req-8.5
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.1
      - accounts_no_uid_except_zero
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify Root Has A Primary GID 0 [ref]

The `root` user should have a primary group of 0.
Rationale: | To help ensure that root-owned files are not inadvertently exposed to other users.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_root_gid_zero

References:

pcidss | Req-8.1.1
cis | 5.4.2.2
pcidss4 | 8.2.1, 8.2

#### Rule Ensure the Group Used by pam_wheel.so Module Exists on System and is Empty [ref]

Ensure that the group `sugroup` referenced by `var_pam_wheel_group_for_su` variable and used as value for the `pam_wheel.so` `group` option exists and has no members. This empty group used by `pam_wheel.so` in `/etc/pam.d/su` ensures that no user can run commands with altered privileges through the `su` command.
Warning: Note that this rule just ensures the group exists and has no members. This rule does not configure `pam_wheel.so` module. The `pam_wheel.so` module configuration is accomplished by `use_pam_wheel_group_for_su` rule.

Rationale: | The `su` program allows to run commands with a substitute user and group ID. It is commonly used to run commands as the root user. Limiting access to such command is considered a good security practice.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_pam_wheel_group_empty

References:

cis | 5.2.7
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

    var_pam_wheel_group_for_su='sugroup'

    # Workaround for https://github.com/OpenSCAP/openscap/issues/2242: Use full
    # path to groupadd command to avoid the issue with the command not being found.
    if ! grep -q "^${var_pam_wheel_group_for_su}:[^:]*:[^:]*:[^:]*" /etc/group; then
        /usr/sbin/groupadd ${var_pam_wheel_group_for_su}
    fi

    # group must be empty
    gpasswd -M '' ${var_pam_wheel_group_for_su}

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

#### Rule Ensure root account access is controlled [ref]

There are a number of methods to access the root account directly. Without a password set any user would be able to gain access and thus control over the entire system. Warning: This rule doesn't come with a remediation, as the exact requirement allows root to either have a password or be locked.
Rationale: | Access to root should be secured at all times.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_root_access_controlled

References:

cis | 5.4.2.4

#### Rule Verify Only Group Root Has GID 0 [ref]

If any group other than root has a GID of 0, this misconfiguration should be investigated and the groups other than root should be removed or have their GID changed. Warning: This rule doesn't come with a remediation. The removal of groups from a system or reassigning the GID is considered too disruptive.
Rationale: | Ensuring that only the `root` group has a GID of 0 helps prevent root group owned files from becoming accidentally accessible to non-privileged users.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_groups_no_zero_gid_except_root

References:

cis | 5.4.2.3

#### Rule Verify Non-Interactive Accounts Are Locked [ref]

Accounts meant for non-interactive purposes should be locked to prevent unauthorized access. Accounts with non-standard shells (those not defined in `/etc/shells`) should be locked using `usermod -L`. Warning: Automatic remediation of this control is not recommended. Locking system accounts could be highly disruptive.
Rationale: | Locking non-interactive accounts improves security by preventing potential misuse. While many systems configure these accounts with invalid strings, setting the shell field to `nologin` is also suggested
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_invalid_shell_accounts_unlocked

References:

cis | 5.4.2.8

#### Rule Ensure that System Accounts Do Not Run a Shell Upon Login [ref]

Some accounts are not associated with a human user of the system, and exist to perform some administrative functions. Should an attacker be able to log into these accounts, they should not be granted access to a shell.
The login shell for each local account is stored in the last field of each line in `/etc/passwd`. System accounts are those user accounts with a user ID less than `1000`. The user ID is stored in the third field. If any system account other than `root` has a login shell, disable it with the command:

    $ sudo usermod -s /sbin/nologin account

Warning: Do not perform the steps in this section on the root account. Doing so might cause the system to become inaccessible.

Rationale: | Ensuring shells are not given to system accounts upon login makes it more difficult for attackers to make use of system accounts.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_shelllogin_for_systemaccounts

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5, 7, 8
cobit5 | DSS01.03, DSS03.05, DSS05.04, DSS05.05, DSS05.07, DSS06.03
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, 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.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 | AC-6, CM-6(a), CM-6(b), CM-6.1(iv)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6
os-srg | SRG-OS-000480-GPOS-00227
cis | 5.4.2.7
ism | 1491
pcidss4 | 8.2.2, 8.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
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

    readarray -t systemaccounts < <(awk -F: '($3 < 1000 && $3 != root \
      && $7 != "\/sbin\/shutdown" && $7 != "\/sbin\/halt" && $7 != "\/bin\/sync") \
      { print $1 }' /etc/passwd)

    for systemaccount in "${systemaccounts[@]}"; do
        usermod -s /sbin/nologin "$systemaccount"
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.2
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - no_shelllogin_for_systemaccounts
      - restrict_strategy

    - name: Ensure that System Accounts Do Not Run a Shell Upon Login - Get All Local
        Users From /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.2
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - no_shelllogin_for_systemaccounts
      - restrict_strategy

    - name: Ensure that System Accounts Do Not Run a Shell Upon Login - Create local_users
        Variable From getent_passwd Facts
      ansible.builtin.set_fact:
        local_users: '{{ ansible_facts.getent_passwd | dict2items }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.2
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - no_shelllogin_for_systemaccounts
      - restrict_strategy

    - name: Ensure that System Accounts Do Not Run a Shell Upon Login -  Disable Login
        Shell for System Accounts
      ansible.builtin.user:
        name: '{{ item.key }}'
        shell: /sbin/nologin
      loop: '{{ local_users }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.key not in ['root']
      - item.value[1]|int < 1000
      - item.value[5] not in ['/sbin/shutdown', '/sbin/halt', '/bin/sync']
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.2
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - no_shelllogin_for_systemaccounts
      - restrict_strategy

#### Rule Enforce Usage of pam_wheel with Group Parameter for su Authentication [ref]

To ensure that only users who are members of the group set in the `group` option of `pam_wheel.so` module can run commands with altered privileges through the `su` command, make sure that the following line exists in the file `/etc/pam.d/su`:

    auth required pam_wheel.so use_uid group=sugroup

Warning: Note that `ensure_pam_wheel_group_empty` rule complements this requirement by ensuring the referenced group exists and has no members.

Rationale: | The `su` program allows to run commands with a substitute user and group ID. It is commonly used to run commands as the root user. Limiting access to such command is considered a good security practice.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_use_pam_wheel_group_for_su

References:

cis | 5.2.7
pcidss4 | 2.2.6, 2.2

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$'; then

    var_pam_wheel_group_for_su='sugroup'

    PAM_CONF=/etc/pam.d/su

    pamstr=$(grep -P '^auth\s+required\s+pam_wheel\.so\s+(?=[^#]*\buse_uid\b)(?=[^#]*\bgroup=)' ${PAM_CONF})
    if [ -z "$pamstr" ]; then
        sed -Ei '/^auth\b.*\brequired\b.*\bpam_wheel\.so/d' ${PAM_CONF} # remove any remaining uncommented pam_wheel.so line
        sed -Ei "/^auth\s+sufficient\s+pam_rootok\.so.*$/a auth             required        pam_wheel.so use_uid group=${var_pam_wheel_group_for_su}" ${PAM_CONF}
    else
        group_val=$(echo -n "$pamstr" | grep -Eo '\bgroup=[_a-z][-0-9_a-z]*' | cut -d '=' -f 2)
        if [ -z "${group_val}" ] || [ ${group_val} != ${var_pam_wheel_group_for_su} ]; then
            sed -Ei "s/(^auth\s+required\s+pam_wheel.so\s+[^#]*group=)[_a-z][-0-9_a-z]*/\1${var_pam_wheel_group_for_su}/" ${PAM_CONF}
        fi
    fi

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

#### Rule Ensure All Accounts on the System Have Unique User IDs [ref]

Change user IDs (UIDs), or delete accounts, so each has a unique name. Warning: Automatic remediation of this control is not available due to unique requirements of each system.
Rationale: | To assure accountability and prevent unauthenticated access, interactive users must be identified and authenticated to prevent potential misuse and compromise of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_unique_id

References:

pcidss | Req-8.1.1
os-srg | SRG-OS-000104-GPOS-00051, SRG-OS-000121-GPOS-00062
cis | 7.2.5
pcidss4 | 8.2.1, 8.2

#### Rule Ensure All Groups on the System Have Unique Group ID [ref]

Change the group name or delete groups, so each has a unique id. Warning: Automatic remediation of this control is not available due to the unique requirements of each system.
Rationale: | To assure accountability and prevent unauthenticated access, groups must be identified uniquely to prevent potential misuse and compromise of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_group_unique_id

References:

os-srg | SRG-OS-000104-GPOS-00051
cis | 7.2.6
pcidss4 | 8.2.1, 8.2

#### Rule Ensure All Groups on the System Have Unique Group Names [ref]

Change the group name or delete groups, so each has a unique name. Warning: Automatic remediation of this control is not available due to the unique requirements of each system.
Rationale: | To assure accountability and prevent unauthenticated access, groups must be identified uniquely to prevent potential misuse and compromise of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_group_unique_name

References:

cis | 7.2.8
pcidss4 | 8.2.1, 8.2

#### Rule Ensure nologin Shell is Not Listed in /etc/shells [ref]

The `/sbin/nologin` shell is used to restrict accounts from having login access and should not be listed as a valid login shell in `/etc/shells`. To verify that nologin is not listed in /etc/shells, run:

    $ grep nologin /etc/shells

The command should return no output.

Rationale: | The `/etc/shells` is consulted by various programs to evaluate whether the user is somehow restricted. For example, the chsh utility will consult the file to determine if the user is allowed to change their shell.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_nologin_in_shells

References:

cis | 5.4.3.1

Remediation Shell script ⇲

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

    if grep -q -E "^[^#]*/nologin\b.*$" /etc/shells; then
      sed -i --follow-symlinks 's/^[^#]*\/nologin\b.*$/#&/g' /etc/shells
    fi

Group Secure Session Configuration Files for Login Accounts Group contains 2 groups and 17 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 No Dangerous Directories Exist in Root's Path Group contains 4 rules

[ref] The active path of the root account can be obtained by starting a new root shell and running:

    # echo $PATH

This will produce a colon-separated list of directories in the path.
Certain path elements could be considered dangerous, as they could lead to root executing unknown or untrusted programs, which could contain malicious code. Since root may sometimes work inside untrusted directories, the `.` character, which represents the current directory, should never be in the root path, nor should any directory which can be written to by an unprivileged or semi-privileged (system) user.
It is a good practice for administrators to always execute privileged commands by typing the full path to the command.

#### Rule Ensure that Root's Path Does Not Include World or Group-Writable Directories [ref]

For each element in root's path, run:

    # ls -ld DIR

and ensure that write permissions are disabled for group and other.

Rationale: | Such entries increase the risk that root could execute code provided by unprivileged users, and potentially malicious code.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_root_path_dirs_no_write

References:

cis-csc | 11, 3, 9
cobit5 | 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.2.2, A.14.2.3, A.14.2.4
nist | CM-6(a), CM-6(a)
nist-csf | PR.IP-1
cis | 5.4.2.5

#### Rule Ensure that All Root's Path Directories Are Owned by Root [ref]

For each element in root's path, run:

    # ls -ld DIR

and ensure that the directory is owned by the root user.

Rationale: | Directories in root's path that are not owned by root could allow unprivileged users to manipulate the execution environment of root, potentially leading to privilege escalation or execution of malicious code.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_dirs_unowned_by_root

References:

cis | 5.4.2.5

#### Rule Ensure that All Entries in The Path of Root Are Directories [ref]

For each element in root's path, run:

    # ls -ld DIR

and ensure that the entry is a directory.

Rationale: | Locations in root's path that are not directories could cause unexpected behavior, such as executing scripts from unintended locations. Ensuring that all locations in root's path are directories helps maintain a secure environment for root.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_root_path_all_dirs

References:

cis | 5.4.2.5

#### Rule Ensure that Root's Path Does Not Include Relative Paths or Null Directories [ref]

Ensure that none of the directories in root's path is equal to a single `.` character, or that it contains any instances that lead to relative path traversal, such as `..` or beginning a path without the slash (`/`) character. Also ensure that there are no "empty" elements in the path, such as in these examples:

    PATH=:/bin
    PATH=/bin:
    PATH=/bin::/sbin

These empty elements have the same effect as a single `.` character.

Rationale: | Including these entries increases the risk that root could execute code from an untrusted location.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_root_path_no_dot

References:

cis-csc | 11, 3, 9
cobit5 | 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.2.2, A.14.2.3, A.14.2.4
nist | CM-6(a), CM-6(a)
nist-csf | PR.IP-1
cis | 5.4.2.5

Group Ensure that Users Have Sensible Umask Values Group contains 4 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 027

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
cis | 5.4.3.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}' 'bash' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_user_umask='027'

    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 027
      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 027

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
cis | 5.4.3.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_accounts_user_umask='027'

    # 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 027
      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 027

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
cis | 5.4.3.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$'; then

    var_accounts_user_umask='027'

    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 027
      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 Ensure the Root Bash Umask is Set Correctly [ref]

To ensure the root user's umask of the Bash shell is set properly, add or correct the `umask` setting in `/root/.bashrc` or `/root/.profile` to read as follows:

    umask 0027

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_root

References:

cis | 5.4.2.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}' 'bash' 2>/dev/null | grep -q '^installed$'; }; then

    for file in /root/.bashrc /root/.profile; do
        if [ -f "$file" ]; then
            sed -i -E -e "s/^([^#]*\bumask)[[:space:]]+[[:digit:]]+/\1 0027/g" "$file"
        fi
    done

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

#### 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=900

or

    declare -xr TMOUT=900

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
cis | 5.4.3.2
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='900'

    # 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 900
      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
cis | 7.2.10

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
cis | 7.2.10

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 Interactive Users Home Directories Must Exist [ref]

Create home directories to all local interactive users that currently do not have a home directory assigned. Use the following commands to create the user home directory assigned in `/etc/passwd`:

    $ sudo mkdir /home/USER

Rationale: | If a local interactive user has a home directory defined that does not exist, the user may be given access to the / directory as the current working directory upon logon. This could create a Denial of Service because the user would not be able to access their logon configuration files, and it may give them visibility to system files they normally would not be able to access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_user_interactive_home_directory_exists

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.9

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) print $1}' /etc/passwd); do
        mkhomedir_helper $user 0077;
    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_interactive_home_directory_exists
      - 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_user_interactive_home_directory_exists
      - 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_user_interactive_home_directory_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure interactive users have a home directory exists
      ansible.builtin.user:
        name: '{{ item.key }}'
        create_home: true
      loop: '{{ local_users }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      tags:
      - accounts_user_interactive_home_directory_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule All Interactive User Home Directories Must Be Group-Owned By The Primary Group [ref]

Change the group owner of interactive users home directory to the group found in `/etc/passwd`. To change the group owner of interactive users home directory, use the following command:

    $ sudo chgrp USER_GROUP /home/USER

This rule ensures every home directory related to an interactive user is group-owned by an interactive user. It also ensures that interactive users are group-owners of one and only one home directory.
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 home directories.

Rationale: | If the Group Identifier (GID) of a local interactive users home directory is not the same as the primary GID of the user, this would allow unauthorized access to the users files, and users that share the same group may not be able to access files that they legitimately should.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownership_home_directories

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.9

Remediation Shell script ⇲

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

    awk -F':' '{ if ($3 >= 1000 && $3 != 65534) system("chgrp -f " $4" "$6) }' /etc/passwd

Remediation Ansible snippet ⇲

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

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      tags:
      - file_groupownership_home_directories
      - 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 }}'
      tags:
      - file_groupownership_home_directories
      - 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
        group ownership
      ansible.builtin.stat:
        path: '{{ item.value[4] }}'
      register: path_exists
      loop: '{{ local_users }}'
      when:
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      tags:
      - file_groupownership_home_directories
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

#### Rule All Interactive User Home Directories Must Be Owned By The Primary User [ref]

Change the owner of interactive users home directories to that correct owner. To change the owner of a interactive users home directory, use the following command:

    $ sudo chown USER /home/USER

This rule ensures every home directory related to an interactive user is owned by an interactive user. It also ensures that interactive users are owners of one and only one home directory.
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 home directories.

Rationale: | If a local interactive user does not own their home directory, unauthorized users could access or modify the user's files, and the users may not be able to access their own files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_home_directories

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.9

Remediation Shell script ⇲

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

    awk -F':' '{ if ($3 >= 1000 && $3 != 65534) system("chown -f " $3" "$6) }' /etc/passwd

Remediation Ansible snippet ⇲

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

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      tags:
      - file_ownership_home_directories
      - 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 }}'
      tags:
      - file_ownership_home_directories
      - 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:
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      tags:
      - file_ownership_home_directories
      - 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] }}'
      loop: '{{ local_users|zip(path_exists.results)|list }}'
      when: item.1.stat is defined and item.1.stat.exists
      tags:
      - file_ownership_home_directories
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure User Bash History File Has Correct Permissions [ref]

Set the mode of the bash history file to `0600` with the following command:

    $ sudo chmod 0600 /home/USER/.bash_history

Rationale: | Incorrect permissions may enable malicious users to recover other users' command history.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permission_user_bash_history

References:

cis | 7.2.10

Remediation Ansible snippet ⇲

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

    - name: Ensure User Bash History File Has Correct Permissions - Gather User Info
      ansible.builtin.getent:
        database: passwd
      tags:
      - file_permission_user_bash_history
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure User Bash History File Has Correct Permissions - Check Bash History
        Files Existence
      ansible.builtin.stat:
        path: '{{ item.value[4] }}/.bash_history'
      register: bash_history_files
      with_dict: '{{ ansible_facts.getent_passwd }}'
      when:
      - item.value[4] != "/sbin/nologin"
      - item.key not in ["nobody", "nfsnobody"]
      - item.value[1] | int >= 1000
      tags:
      - file_permission_user_bash_history
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure User Bash History File Has Correct Permissions - Fix Bash History Files
        Permissions
      ansible.builtin.file:
        path: '{{ item.stat.path }}'
        mode: u-sx,go=
      with_items: '{{ bash_history_files.results }}'
      when:
      - item.stat is defined
      - item.stat.exists
      tags:
      - file_permission_user_bash_history
      - 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
cis | 7.2.10

Remediation Shell script ⇲

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

    var_user_initialization_files_regex='^\.[\w\- ]+$'

    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 ^\.[\w\- ]+$
      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

#### Rule All Interactive User Home Directories Must Have mode 0750 Or Less Permissive [ref]

Change the mode of interactive users home directories to `0750`. To change the mode of interactive users home directory, use the following command:

    $ sudo chmod 0750 /home/USER

Rationale: | Excessive permissions on local interactive user home directories may allow unauthorized access to user files by other users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_home_directories

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.9

Remediation Shell script ⇲

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

    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" -maxdepth 0 -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    done

Remediation Ansible snippet ⇲

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

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      tags:
      - file_permissions_home_directories
      - 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 }}'
      tags:
      - file_permissions_home_directories
      - 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:
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      - item.value[4] != "/"
      tags:
      - file_permissions_home_directories
      - 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: false
      loop: '{{ local_users|zip(path_exists.results)|list }}'
      when: item.1.stat is defined and item.1.stat.exists
      tags:
      - file_permissions_home_directories
      - 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 Utils 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-utils_installed

References:

cis | 1.3.1.1

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-utils"

    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-utils

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

Remediation Ansible snippet ⇲

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

    - 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"]
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_apparmor-utils_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### 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
cis | 1.3.1.1

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 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
cis | 1.3.1.4

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 All AppArmor Profiles are in enforce or complain mode [ref]

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

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

run the following command to set all profiles to `complain` mode:

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

To list unconfined processes run the following command:

    $ sudo aa-unconfined

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_in_enforce_complain_mode

References:

cis | 1.3.1.3

#### 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
cis | 1.3.1.2

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 4 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 12 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 3 rules
[ref] Non-UEFI GRUB2 bootloader configuration

#### 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
cis | 1.4.2
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/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
cis | 1.4.2
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 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
cis | 1.4.1

Group UEFI GRUB2 bootloader configuration Group contains 1 rule
[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 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
cis | 1.4.1

Group zIPL bootloader configuration Group contains 2 rules
[ref] During the boot process, the bootloader is responsible for starting the execution of the kernel and passing options to it. The default Debian 12 boot loader for s390x systems is called zIPL.

#### Rule Enable Auditing to Start Prior to the Audit Daemon in zIPL [ref]

To ensure all processes can be audited, even those which start prior to the audit daemon, check that all boot entries in `/boot/loader/entries/*.conf` have `audit=1` included in its options. To ensure that new kernels and boot entries continue to enable audit, add `audit=1` to `/etc/kernel/cmdline`.
Rationale: | Each process on the system carries an "auditable" flag which indicates whether its activities can be audited. Although `auditd` takes care of enabling this for all processes which launch after it does, adding the kernel argument ensures it is set for every process during boot.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_zipl_audit_argument

References:

ospp | FAU_GEN.1
cis | 6.2.1.3

#### Rule Extend Audit Backlog Limit for the Audit Daemon in zIPL [ref]

To improve the kernel capacity to queue all log events, even those which start prior to the audit daemon, check that all boot entries in `/boot/loader/entries/*.conf` have `audit_backlog_limit=8192` included in its options. To ensure that new kernels and boot entries continue to extend the audit log events queue, add `audit_backlog_limit=8192` to `/etc/kernel/cmdline`.
Rationale: | audit_backlog_limit sets the queue length for audit events awaiting transfer to the audit daemon. Until the audit daemon is up and running, all log messages are stored in this queue. If the queue is overrun during boot process, the action defined by audit failure flag is taken.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_zipl_audit_backlog_limit_argument

References:

ospp | FAU_STG.1, FAU_STG.3
cis | 6.2.1.4

Group Configure Syslog Group contains 2 groups and 15 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 12, 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 systemd-journald Group contains 10 rules
[ref] systemd-journald is a system service that collects and stores logging data. It creates and maintains structured, indexed journals based on logging information that is received from a variety of sources. For more information on `systemd-journald` and additional `systemd-journald` configuration options, see https://systemd.io/.

#### Rule Install systemd-journal-remote Package [ref]

Journald (via systemd-journal-remote ) supports the ability to send log events it gathers to a remote log host or to receive messages from remote hosts, thus enabling centralised log management.
Rationale: | Storing log data on a remote host protects log integrity from local attacks. If an attacker gains root access on the local system, they could tamper with or remove log data that is stored on the local system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_systemd-journal-remote_installed

References:

os-srg | SRG-OS-000479-GPOS-00224
cis | 6.1.2.1.1

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 "systemd-journal-remote"

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

Remediation Puppet snippet ⇲

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

    include install_systemd-journal-remote

    class install_systemd-journal-remote {
      package { 'systemd-journal-remote':
        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_systemd-journal-remote_installed

    - name: Ensure systemd-journal-remote is installed
      ansible.builtin.package:
        name: systemd-journal-remote
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_systemd-journal-remote_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "systemd-journal-remote"
    version = "*"

#### Rule Enable systemd-journal-upload Service [ref]

The `systemd-journal-upload` service is part of the `systemd-journal-remote` package and enables centralized logging by uploading local systemd journal entries to a remote log server via HTTPS. This service acts as a client that pushes journal data to a remote host running the `systemd-journal-remote` receiver service. The `systemd-journal-upload` service can be enabled with the following command:

    $ sudo systemctl enable systemd-journal-upload.service

Warning: The `systemd-journal-upload` service will fail to start if the remote server URL is not configured. Edit `/etc/systemd/journal-upload.conf` to configure the remote server URL.

Rationale:

Centralized logging through `systemd-journal-upload` is essential for security monitoring, incident response, and compliance requirements. Storing log data on a remote host protects log integrity from local attacks. If an attacker gains root access on the local system, they could tamper with or remove log data stored locally to hide their activities. Remote logging ensures that audit trails remain intact even if the local system is compromised. Additionally, centralized logs facilitate correlation of events across multiple systems, enabling better detection of distributed attacks and security incidents.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_systemd-journal-upload_enabled

References:

os-srg | SRG-OS-000479-GPOS-00224
cis | 6.1.2.1.3

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$' && { ( [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ] && dpkg-query --show --showformat='${db:Status-Status}' 'systemd-journal-remote' 2>/dev/null | grep -q '^installed$' ); }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'systemd-journal-upload.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'systemd-journal-upload.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'systemd-journal-upload.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_systemd-journal-upload

    class enable_systemd-journal-upload {
      service {'systemd-journal-upload':
        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:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-journal-upload_enabled

    - name: Enable systemd-journal-upload Service - Enable service systemd-journal-upload
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable systemd-journal-upload Service - Enable Service systemd-journal-upload
        ansible.builtin.systemd:
          name: systemd-journal-upload
          enabled: true
          state: started
          masked: false
        when:
        - '"systemd-journal-remote" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-journal-upload_enabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "systemd-journal-remote" in ansible_facts.packages )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["systemd-journal-upload"]

#### Rule Enable systemd-journald Service [ref]

The `systemd-journald` service is an essential component of systemd. The `systemd-journald` service can be enabled with the following command:

    $ sudo systemctl enable systemd-journald.service

Rationale: | In the event of a system failure, Debian 12 must preserve any information necessary to determine cause of failure and any information necessary to return to operations with least disruption to system processes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_systemd-journald_enabled

References:

nist | SC-24
os-srg | SRG-OS-000269-GPOS-00103
cis | 6.1.1.1

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 'systemd-journald.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'systemd-journald.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'systemd-journald.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_systemd-journald

    class enable_systemd-journald {
      service {'systemd-journald':
        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-SC-24
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-journald_enabled

    - name: Enable systemd-journald Service - Enable service systemd-journald
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable systemd-journald Service - Enable Service systemd-journald
        ansible.builtin.systemd:
          name: systemd-journald
          enabled: true
          state: started
          masked: false
        when:
        - '"systemd" in ansible_facts.packages'
      tags:
      - NIST-800-53-SC-24
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-journald_enabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["systemd-journald"]

#### Rule Ensure journald is configured to compress large log files [ref]

The journald system can compress large log files to avoid fill the system disk.
Rationale: | Log files that are not properly compressed run the risk of growing so large that they fill up the log partition. Valuable logging information could be lost if the log partition becomes full.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_journald_compress

References:

cis | 6.1.2.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$'; then

    if [ -e "/etc/systemd/journald.conf" ] ; then

        LC_ALL=C sed -i "/^\s*Compress\s*=\s*/d" "/etc/systemd/journald.conf"
    else
        touch "/etc/systemd/journald.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/systemd/journald.conf"

    cp "/etc/systemd/journald.conf" "/etc/systemd/journald.conf.bak"
    # Insert before the line matching the regex '^#\s*Compress'.
    line_number="$(LC_ALL=C grep -n "^#\s*Compress" "/etc/systemd/journald.conf.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^#\s*Compress', insert at
        # the end of the file.
        printf '%s\n' "Compress=yes" >> "/etc/systemd/journald.conf"
    else
        head -n "$(( line_number - 1 ))" "/etc/systemd/journald.conf.bak" > "/etc/systemd/journald.conf"
        printf '%s\n' "Compress=yes" >> "/etc/systemd/journald.conf"
        tail -n "+$(( line_number ))" "/etc/systemd/journald.conf.bak" >> "/etc/systemd/journald.conf"
    fi
    # Clean up after ourselves.
    rm "/etc/systemd/journald.conf.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:
      - journald_compress
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Setting unquoted shell-style assignment of 'Compress' to 'yes' in '/etc/systemd/journald.conf'
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Compress=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Compress=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Compress=
          line: Compress=yes
          state: present
          insertbefore: ^# Compress
          validate: /usr/bin/bash -n %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - journald_compress
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure journald ForwardToSyslog is disabled [ref]

Data from journald should be kept in the confines of the service and not forwarded to other services.
Rationale: | If journald is the method for capturing logs, all logs of the system should be handled by journald and not forwarded to other logging mechanisms.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_journald_disable_forward_to_syslog

References:

cis | 6.1.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}' 'systemd' 2>/dev/null | grep -q '^installed$'; }; then

    if [ -e "/etc/systemd/journald.conf" ] ; then

        LC_ALL=C sed -i "/^\s*ForwardToSyslog\s*=\s*/d" "/etc/systemd/journald.conf"
    else
        touch "/etc/systemd/journald.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/systemd/journald.conf"

    cp "/etc/systemd/journald.conf" "/etc/systemd/journald.conf.bak"
    # Insert before the line matching the regex '^#\s*ForwardToSyslog'.
    line_number="$(LC_ALL=C grep -n "^#\s*ForwardToSyslog" "/etc/systemd/journald.conf.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^#\s*ForwardToSyslog', insert at
        # the end of the file.
        printf '%s\n' "ForwardToSyslog=no" >> "/etc/systemd/journald.conf"
    else
        head -n "$(( line_number - 1 ))" "/etc/systemd/journald.conf.bak" > "/etc/systemd/journald.conf"
        printf '%s\n' "ForwardToSyslog=no" >> "/etc/systemd/journald.conf"
        tail -n "+$(( line_number ))" "/etc/systemd/journald.conf.bak" >> "/etc/systemd/journald.conf"
    fi
    # Clean up after ourselves.
    rm "/etc/systemd/journald.conf.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:
      - journald_disable_forward_to_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Setting unquoted shell-style assignment of 'ForwardToSyslog' to 'no' in '/etc/systemd/journald.conf'
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          line: ForwardToSyslog=no
          state: present
          insertbefore: ^# ForwardToSyslog
          validate: /usr/bin/bash -n %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - journald_disable_forward_to_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure journald is configured to send logs to rsyslog [ref]

Data from journald may be stored in volatile memory or persisted locally. Utilities exist to accept remote export of journald logs.
Rationale: | Storing log data on a remote host protects log integrity from local attacks. If an attacker gains root access on the local system, they could tamper with or remove log data that is stored on the local system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_journald_forward_to_syslog

References:

cis | 6.1.3.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$'; then

    if [ -e "/etc/systemd/journald.conf" ] ; then

        LC_ALL=C sed -i "/^\s*ForwardToSyslog\s*=\s*/d" "/etc/systemd/journald.conf"
    else
        touch "/etc/systemd/journald.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/systemd/journald.conf"

    cp "/etc/systemd/journald.conf" "/etc/systemd/journald.conf.bak"
    # Insert before the line matching the regex '^#\s*ForwardToSyslog'.
    line_number="$(LC_ALL=C grep -n "^#\s*ForwardToSyslog" "/etc/systemd/journald.conf.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^#\s*ForwardToSyslog', insert at
        # the end of the file.
        printf '%s\n' "ForwardToSyslog=yes" >> "/etc/systemd/journald.conf"
    else
        head -n "$(( line_number - 1 ))" "/etc/systemd/journald.conf.bak" > "/etc/systemd/journald.conf"
        printf '%s\n' "ForwardToSyslog=yes" >> "/etc/systemd/journald.conf"
        tail -n "+$(( line_number ))" "/etc/systemd/journald.conf.bak" >> "/etc/systemd/journald.conf"
    fi
    # Clean up after ourselves.
    rm "/etc/systemd/journald.conf.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:
      - journald_forward_to_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Setting unquoted shell-style assignment of 'ForwardToSyslog' to 'yes' in '/etc/systemd/journald.conf'
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*ForwardToSyslog=
          line: ForwardToSyslog=yes
          state: present
          insertbefore: ^# ForwardToSyslog
          validate: /usr/bin/bash -n %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - journald_forward_to_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure journald is configured to write log files to persistent disk [ref]

The journald system may store log files in volatile memory or locally on disk. If the logs are only stored in volatile memory they will be lost upon reboot.
Rationale: | Log files contain valuable data and need to be persistent to aid in possible investigations.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_journald_storage

References:

cis | 6.1.2.4

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/systemd/journald.conf" ] ; then

        LC_ALL=C sed -i "/^\s*Storage\s*=\s*/d" "/etc/systemd/journald.conf"
    else
        touch "/etc/systemd/journald.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/systemd/journald.conf"

    cp "/etc/systemd/journald.conf" "/etc/systemd/journald.conf.bak"
    # Insert before the line matching the regex '^#\s*Storage'.
    line_number="$(LC_ALL=C grep -n "^#\s*Storage" "/etc/systemd/journald.conf.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^#\s*Storage', insert at
        # the end of the file.
        printf '%s\n' "Storage=persistent" >> "/etc/systemd/journald.conf"
    else
        head -n "$(( line_number - 1 ))" "/etc/systemd/journald.conf.bak" > "/etc/systemd/journald.conf"
        printf '%s\n' "Storage=persistent" >> "/etc/systemd/journald.conf"
        tail -n "+$(( line_number ))" "/etc/systemd/journald.conf.bak" >> "/etc/systemd/journald.conf"
    fi
    # Clean up after ourselves.
    rm "/etc/systemd/journald.conf.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:
      - journald_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Setting unquoted shell-style assignment of 'Storage' to 'persistent' in '/etc/systemd/journald.conf'
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Storage=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Storage=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/systemd/journald.conf
        ansible.builtin.lineinfile:
          path: /etc/systemd/journald.conf
          create: true
          regexp: (?i)^\s*Storage=
          line: Storage=persistent
          state: present
          insertbefore: ^# Storage
          validate: /usr/bin/bash -n %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - journald_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Disable systemd-journal-remote Socket [ref]

Journald supports the ability to receive messages from remote hosts, thus acting as a log server. Clients should not receive data from other hosts. NOTE: The same package, systemd-journal-remote , is used for both sending logs to remote hosts and receiving incoming logs. With regards to receiving logs, there are two Systemd unit files; systemd-journal-remote.socket and systemd-journal-remote.service.

Rationale: | If a client is configured to also receive data, thus turning it into a server, the client system is acting outside it's operational boundary.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_socket_systemd-journal-remote_disabled

References:

cis | 6.1.2.1.4

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

    SOCKET_NAME="systemd-journal-remote.socket"
    SYSTEMCTL_EXEC='/usr/bin/systemctl'

    if "$SYSTEMCTL_EXEC" -q list-unit-files --type socket | grep -q "$SOCKET_NAME"; then
        if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
          "$SYSTEMCTL_EXEC" stop "$SOCKET_NAME"
        fi
        "$SYSTEMCTL_EXEC" mask "$SOCKET_NAME"
    fi

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

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
      - medium_severity
      - no_reboot_needed
      - socket_systemd-journal-remote_disabled

    - name: Disable systemd-journal-remote Socket - Collect systemd Socket Units Present
        in the System
      ansible.builtin.command:
        cmd: systemctl -q list-unit-files --type socket
      register: result_systemd_unit_files
      changed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - socket_systemd-journal-remote_disabled

    - name: Disable systemd-journal-remote Socket - Ensure systemd-journal-remote.socket
        is Masked
      ansible.builtin.systemd:
        name: systemd-journal-remote.socket
        state: stopped
        enabled: false
        masked: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - result_systemd_unit_files.stdout_lines is search("systemd-journal-remote.socket")
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - socket_systemd-journal-remote_disabled

#### Rule Configure systemd-journal-upload TLS parameters: ServerKeyFile, ServerCertificateFile and TrustedCertificateFile [ref]

Debian 12 must offload rsyslog messages for networked systems in real time and offload standalone systems at least weekly
Rationale: | Information stored in one location is vulnerable to accidental or incidental deletion or alteration. Offloading is a common process in information systems with limited audit storage capacity
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_systemd_journal_upload_server_tls

References:

os-srg | SRG-OS-000479-GPOS-00224
cis | 6.1.2.1.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

    dropin_conf=/etc/systemd/journal-upload.conf

    for conf in /etc/systemd/journal-upload.conf /etc/systemd/journal-upload.conf.d/*; do
        [[ -e "${conf}" ]] || continue
        sed -i --follow-symlinks \
            -e 's/^ServerKeyFile\>/#&/g' \
            -e 's/^ServerCertificateFile\>/#&/g' \
            -e 's/^TrustedCertificateFile\>/#&/g' "${conf}"
    done

    var_journal_upload_server_key_file='/etc/pki/systemd/private/journal-upload.pem'

    var_journal_upload_server_certificate_file='/etc/pki/systemd/certs/journal-upload.pem'

    var_journal_upload_server_trusted_certificate_file='/etc/pki/systemd/ca/trusted.pem'

    found=false

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

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Upload\]([^\n\[]*\n+)+?[[:space:]]*ServerKeyFile" "$f"; then
            if ! grep -qPz "ServerKeyFile=$var_journal_upload_server_key_file" "$f"; then

                sed -i "s/ServerKeyFile[^(\n)]*/ServerKeyFile=$var_journal_upload_server_key_file/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Upload\]" "$f"; then

                sed -i "/[[:space:]]*\[Upload\]/a ServerKeyFile=$var_journal_upload_server_key_file" "$f"

                found=true
        fi
    done

    # if section not in any file, append section with key = value to FIRST file in files parameter
    if ! $found ; then
        file=$(echo "${dropin_conf}" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Upload]\nServerKeyFile=$var_journal_upload_server_key_file" >> "$file"

    fi
    found=false

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

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Upload\]([^\n\[]*\n+)+?[[:space:]]*ServerCertificateFile" "$f"; then
            if ! grep -qPz "ServerCertificateFile=$var_journal_upload_server_certificate_file" "$f"; then

                sed -i "s/ServerCertificateFile[^(\n)]*/ServerCertificateFile=$var_journal_upload_server_certificate_file/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Upload\]" "$f"; then

                sed -i "/[[:space:]]*\[Upload\]/a ServerCertificateFile=$var_journal_upload_server_certificate_file" "$f"

                found=true
        fi
    done

    # if section not in any file, append section with key = value to FIRST file in files parameter
    if ! $found ; then
        file=$(echo "${dropin_conf}" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Upload]\nServerCertificateFile=$var_journal_upload_server_certificate_file" >> "$file"

    fi
    found=false

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

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Upload\]([^\n\[]*\n+)+?[[:space:]]*TrustedCertificateFile" "$f"; then
            if ! grep -qPz "TrustedCertificateFile=$var_journal_upload_server_trusted_certificate_file" "$f"; then

                sed -i "s/TrustedCertificateFile[^(\n)]*/TrustedCertificateFile=$var_journal_upload_server_trusted_certificate_file/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Upload\]" "$f"; then

                sed -i "/[[:space:]]*\[Upload\]/a TrustedCertificateFile=$var_journal_upload_server_trusted_certificate_file" "$f"

                found=true
        fi
    done

    # if section not in any file, append section with key = value to FIRST file in files parameter
    if ! $found ; then
        file=$(echo "${dropin_conf}" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Upload]\nTrustedCertificateFile=$var_journal_upload_server_trusted_certificate_file" >> "$file"

    fi

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

#### Rule Configure systemd-journal-upload URL [ref]

Debian 12 must offload rsyslog messages for networked systems in real time and offload standalone systems at least weekly
Rationale: | Information stored in one location is vulnerable to accidental or incidental deletion or alteration. Offloading is a common process in information systems with limited audit storage capacity
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_systemd_journal_upload_url

References:

os-srg | SRG-OS-000479-GPOS-00224
cis | 6.1.2.1.2

Group Configure rsyslogd to Accept Remote Messages If Acting as a Log Server Group contains 1 rule
[ref] By default, `rsyslog` does not listen over the network for log messages. If needed, modules can be enabled to allow the rsyslog daemon to receive messages from other systems and for the system thus to act as a log server. If the system is not a log server, then lines concerning these modules should remain commented out.

#### Rule Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server [ref]

The `rsyslog` daemon should not accept remote messages unless the system acts as a log server. To ensure that it is not listening on the network, ensure any of the following lines are not found in `rsyslog` configuration files. If using legacy syntax:

    $ModLoad imtcp
    $InputTCPServerRun port
    $ModLoad imudp
    $UDPServerRun port
    $ModLoad imrelp
    $InputRELPServerRun port

If using RainerScript syntax:

    module(load="imtcp")
    module(load="imudp")
    input(type="imtcp" port="514")
    input(type="imudp" port="514")

Rationale: | Any process which receives messages from the network incurs some risk of receiving malicious messages. This risk can be eliminated for rsyslog by configuring it not to listen on the network.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_nolisten

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 3, 4, 5, 6, 8, 9
cobit5 | APO01.06, APO11.04, APO13.01, BAI03.05, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.07, DSS06.02, MEA02.01
isa-62443-2009 | 4.2.3.4, 4.3.3.3.9, 4.3.3.4, 4.3.3.5.8, 4.3.4.3.2, 4.3.4.3.3, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4, 4.4.3.3
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.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.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.5.1, A.12.6.2, A.12.7.1, 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.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.IP-1, PR.PT-1, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
cis | 6.1.3.7
ism | 0988, 1405

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

    legacy_regex='^\s*\$(((Input(TCP|RELP)|UDP)ServerRun)|ModLoad\s+(imtcp|imudp|imrelp))'
    rainer_regex='^\s*(module|input)\((load|type)="(imtcp|imudp)".*$'

    readarray -t legacy_targets < <(grep -l -E -r "${legacy_regex[@]}" /etc/rsyslog.conf /etc/rsyslog.d/)
    readarray -t rainer_targets < <(grep -l -E -r "${rainer_regex[@]}" /etc/rsyslog.conf /etc/rsyslog.d/)

    config_changed=false
    if [ ${#legacy_targets[@]} -gt 0 ]; then
        for target in "${legacy_targets[@]}"; do
            sed -E -i "/$legacy_regex/ s/^/# /" "$target"
        done
        config_changed=true
    fi

    if [ ${#rainer_targets[@]} -gt 0 ]; then
        for target in "${rainer_targets[@]}"; do
            sed -E -i "/$rainer_regex/ s/^/# /" "$target"
        done
        config_changed=true
    fi

    if $config_changed; then
        systemctl restart rsyslog.service
    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)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Define Rsyslog Config Lines Regex in Legacy Syntax
      ansible.builtin.set_fact:
        rsyslog_listen_legacy_regex: ^\s*\$(((Input(TCP|RELP)|UDP)ServerRun)|ModLoad\s+(imtcp|imudp|imrelp))
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Search for Legacy Config Lines in Rsyslog Main Config File
      ansible.builtin.find:
        paths: /etc
        pattern: rsyslog.conf
        contains: '{{ rsyslog_listen_legacy_regex }}'
      register: rsyslog_listen_legacy_main_file
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Search for Legacy Config Lines in Rsyslog Include Files
      ansible.builtin.find:
        paths: /etc/rsyslog.d/
        pattern: '*.conf'
        contains: '{{ rsyslog_listen_legacy_regex }}'
      register: rsyslog_listen_legacy_include_files
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Assemble List of Config Files With Listen Lines in Legacy Syntax
      ansible.builtin.set_fact:
        rsyslog_legacy_remote_listen_files: '{{ rsyslog_listen_legacy_main_file.files
          | map(attribute=''path'') | list + rsyslog_listen_legacy_include_files.files
          | map(attribute=''path'') | list }}'
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Comment Listen Config Lines Wherever Defined Using Legacy Syntax
      ansible.builtin.replace:
        path: '{{ item }}'
        regexp: '{{ rsyslog_listen_legacy_regex }}'
        replace: '# \1'
      loop: '{{ rsyslog_legacy_remote_listen_files }}'
      register: rsyslog_listen_legacy_comment
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_legacy_remote_listen_files | length > 0
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Define Rsyslog Config Lines Regex in RainerScript Syntax
      ansible.builtin.set_fact:
        rsyslog_listen_rainer_regex: ^\s*(module|input)\((load|type)="(imtcp|imudp)".*$
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Search for RainerScript Config Lines in Rsyslog Main Config File
      ansible.builtin.find:
        paths: /etc
        pattern: rsyslog.conf
        contains: '{{ rsyslog_listen_rainer_regex }}'
      register: rsyslog_rainer_remote_main_file
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Search for RainerScript Config Lines in Rsyslog Include Files
      ansible.builtin.find:
        paths: /etc/rsyslog.d/
        pattern: '*.conf'
        contains: '{{ rsyslog_listen_rainer_regex }}'
      register: rsyslog_rainer_remote_include_files
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Assemble List of Config Files With Listen Lines in RainerScript
      ansible.builtin.set_fact:
        rsyslog_rainer_remote_listen_files: '{{ rsyslog_rainer_remote_main_file.files
          | map(attribute=''path'') | list + rsyslog_rainer_remote_include_files.files
          | map(attribute=''path'') | list }}'
      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)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Comment Listen Config Lines Wherever Defined Using RainerScript
      ansible.builtin.replace:
        path: '{{ item }}'
        regexp: '{{ rsyslog_listen_rainer_regex }}'
        replace: '# \1'
      loop: '{{ rsyslog_rainer_remote_listen_files }}'
      register: rsyslog_listen_rainer_comment
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_rainer_remote_listen_files | length > 0
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

    - name: Ensure rsyslog Does Not Accept Remote Messages Unless Acting As Log Server
        - Restart Rsyslog if Any Line Were Commented Out
      ansible.builtin.service:
        name: rsyslog
        state: restarted
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_listen_legacy_comment is changed or rsyslog_listen_rainer_comment is changed
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_nolisten

#### 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
cis | 6.1.3.1
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 12. 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
cis | 6.1.3.2
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"]

#### Rule Ensure One Logging Service Is In Use [ref]

Ensure that a logging system is active and in use.

    systemctl is-active rsyslog systemd-journald

The command should return at least one `active`.
Warning: This rule does not come with a remediation. There are specific rules for enabling each logging service which should be enabled instead.

Rationale: | The system should have one active logging service to avoid conflicts and ensure consistency.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_logging_services_active

References:

cis | 6.1.1.4

#### Rule Ensure rsyslog Default File Permissions Configured [ref]

rsyslog will create logfiles that do not already exist on the system. This settings controls what permissions will be applied to these newly created files.
Rationale: | It is important to ensure that log files have the correct permissions to ensure that sensitive data is archived and protected.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_filecreatemode

References:

cis | 6.1.3.4

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

    sed -i '/^\s*$FileCreateMode/d' /etc/rsyslog.d/*

    if ! grep -qE '^\s*\$FileCreateMode\s+0640' /etc/rsyslog.conf; then
        if grep -qE '^\s*\$FileCreateMode' /etc/rsyslog.conf; then
            sed -i '/^\s*\$FileCreateMode/ s/^/#/' /etc/rsyslog.conf
        fi
        ## Assume there is no filter named as 00-, otherwise those filters might be included before this configuration and create file with different permissions
        echo '$FileCreateMode 0640' > /etc/rsyslog.d/00-rsyslog_filecreatemode.conf
    fi

    systemctl restart rsyslog.service

    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
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Search for $FileCreateMode
        Parameter in rsyslog Main Config File
      ansible.builtin.find:
        paths: /etc
        pattern: rsyslog.conf
        contains: ^\s*\$FileCreateMode\s*\d+
      register: rsyslog_main_file_with_filecreatemode
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Search for $FileCreateMode
        Parameter in rsyslog Include Files
      ansible.builtin.find:
        paths: /etc/rsyslog.d/
        pattern: '*.conf'
        contains: ^\s*\$FileCreateMode\s*\d+
      register: rsyslog_includes_with_filecreatemode
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Assemble List of rsyslog
        Configuration Files with $FileCreateMode Parameter
      ansible.builtin.set_fact:
        rsyslog_filecreatemode_files: '{{ rsyslog_main_file_with_filecreatemode.files
          | map(attribute=''path'') | list + rsyslog_includes_with_filecreatemode.files
          | map(attribute=''path'') | list }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Remove $FileCreateMode
        Parameter from Multiple Files to Avoid Conflicts
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        regexp: \$FileCreateMode.*
        state: absent
      register: result_rsyslog_filecreatemode_removed
      loop: '{{ rsyslog_filecreatemode_files }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_filecreatemode_files | length > 1
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Add $FileCreateMode Parameter
        and Expected Value
      ansible.builtin.lineinfile:
        path: /etc/rsyslog.d/00-rsyslog_filecreatemode.conf
        line: $FileCreateMode 0640
        mode: 416
        create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_filecreatemode_files | length == 0 or result_rsyslog_filecreatemode_removed
        is not skipped
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

    - name: Ensure rsyslog Default File Permissions Configured - Ensure Correct Value
        of Existing $FileCreateMode Parameter
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        regexp: ^\$FileCreateMode
        line: $FileCreateMode 0640
      loop: '{{ rsyslog_filecreatemode_files }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - rsyslog_filecreatemode_files | length == 1
      tags:
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_filecreatemode

Group Network Configuration and Firewalls Group contains 13 groups and 54 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 iptables and ip6tables Group contains 2 groups and 9 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.

Group Inspect and Activate Default Rules Group contains 3 rules

[ref] View the currently-enforced `iptables` rules by running the command:

    $ sudo iptables -nL --line-numbers

The command is analogous for `ip6tables`.
If the firewall does not appear to be active (i.e., no rules appear), activate it and ensure that it starts at boot by issuing the following commands (and analogously for `ip6tables`):

    $ sudo service iptables restart

The default iptables rules are:

    Chain INPUT (policy ACCEPT)
    num  target     prot opt source       destination
    1    ACCEPT     all  --  0.0.0.0/0    0.0.0.0/0    state RELATED,ESTABLISHED
    2    ACCEPT     icmp --  0.0.0.0/0    0.0.0.0/0
    3    ACCEPT     all  --  0.0.0.0/0    0.0.0.0/0
    4    ACCEPT     tcp  --  0.0.0.0/0    0.0.0.0/0    state NEW tcp dpt:22
    5    REJECT     all  --  0.0.0.0/0    0.0.0.0/0    reject-with icmp-host-prohibited

    Chain FORWARD (policy ACCEPT)
    num  target     prot opt source       destination
    1    REJECT     all  --  0.0.0.0/0    0.0.0.0/0    reject-with icmp-host-prohibited

    Chain OUTPUT (policy ACCEPT)
    num  target     prot opt source       destination

The `ip6tables` default rules are essentially the same.

#### Rule Set Default ip6tables Policy for Incoming Packets [ref]

To set the default policy to DROP (instead of ACCEPT) for the built-in INPUT chain which processes incoming packets, add or correct the following line in `/etc/sysconfig/ip6tables`:

    :INPUT DROP [0:0]

If changes were required, reload the ip6tables rules:

    $ sudo service ip6tables reload

Rationale: | In `ip6tables`, the default policy is applied only after all the applicable rules in the table are examined for a match. Setting the default policy to `DROP` implements proper design for a firewall, i.e. any packets which are not explicitly permitted should not be accepted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_ip6tables_default_rule

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 R4, CIP-003-8 R5, CIP-004-6 R3
nist | AC-4, CM-7(b), CA-3(5), SC-7(21), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
cis | 4.4.3.1
pcidss4 | 1.4.1, 1.4

Remediation Shell script ⇲

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

    sed -i 's/^:INPUT ACCEPT.*/:INPUT DROP [0:0]/g' /etc/sysconfig/ip6tables

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

#### Rule Set configuration for IPv6 loopback traffic [ref]

Configure the loopback interface to accept traffic. Configure all other interfaces to deny traffic to the loopback network. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Loopback traffic is generated between processes on machine and is typically critical to operation of the system. The loopback interface is the only place that loopback network traffic should be seen, all other interfaces should ignore traffic on this network as an anti-spoofing measure.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_ipv6_loopback_traffic

References:

pcidss | Req-1.3
cis | 4.4.3.2
pcidss4 | 1.4.1, 1.4

#### Rule Set configuration for loopback traffic [ref]

Configure the loopback interface to accept traffic. Configure all other interfaces to deny traffic to the loopback network. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Loopback traffic is generated between processes on machine and is typically critical to operation of the system. The loopback interface is the only place that loopback network traffic should be seen, all other interfaces should ignore traffic on this network as an anti-spoofing measure.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_loopback_traffic

References:

pcidss | Req-1.3
cis | 4.4.2.2
pcidss4 | 1.4.1, 1.4

Group Strengthen the Default Ruleset Group contains 3 rules

[ref] The default rules can be strengthened. The system scripts that activate the firewall rules expect them to be defined in the configuration files `iptables` and `ip6tables` in the directory `/etc/sysconfig`. Many of the lines in these files are similar to the command line arguments that would be provided to the programs `/sbin/iptables` or `/sbin/ip6tables` - but some are quite different.
The following recommendations describe how to strengthen the default ruleset configuration file. An alternative to editing this configuration file is to create a shell script that makes calls to the iptables program to load in rules, and then invokes service iptables save to write those loaded rules to `/etc/sysconfig/iptables.`
The following alterations can be made directly to `/etc/sysconfig/iptables` and `/etc/sysconfig/ip6tables`. Instructions apply to both unless otherwise noted. Language and address conventions for regular iptables are used throughout this section; configuration for ip6tables will be either analogous or explicitly covered.
Warning: The program `system-config-securitylevel` allows additional services to penetrate the default firewall rules and automatically adjusts `/etc/sysconfig/iptables`. This program is only useful if the default ruleset meets your security requirements. Otherwise, this program should not be used to make changes to the firewall configuration because it re-writes the saved configuration file.

#### Rule Ensure ip6tables Firewall Rules Exist for All Open Ports [ref]

Any ports that have been opened on non-loopback addresses need firewall rules to govern traffic. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Without a firewall rule configured for open ports default firewall policy will drop all packets to these ports.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ip6tables_rules_for_open_ports

References:

cis | 4.4.3.4

#### Rule Ensure iptables Firewall Rules Exist for All Open Ports [ref]

Any ports that have been opened on non-loopback addresses need firewall rules to govern traffic. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Without a firewall rule configured for open ports default firewall policy will drop all packets to these ports.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_iptables_rules_for_open_ports

References:

cis | 4.4.2.4

#### Rule Set Default iptables Policy for Incoming Packets [ref]

To set the default policy to DROP (instead of ACCEPT) for the built-in INPUT chain which processes incoming packets, add or correct the following line in `/etc/sysconfig/iptables`:

    :INPUT DROP [0:0]

Rationale: | In `iptables` the default policy is applied only after all the applicable rules in the table are examined for a match. Setting the default policy to `DROP` implements proper design for a firewall, i.e. any packets which are not explicitly permitted should not be accepted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_iptables_default_rule

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 | CA-3(5), CM-7(b), SC-7(23), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
cis | 4.4.2.1

Remediation Shell script ⇲

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

    sed -i 's/^:INPUT ACCEPT.*/:INPUT DROP [0:0]/g' /etc/sysconfig/iptables

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

#### Rule Install iptables-persistent Package [ref]

The `iptables-persistent` package can be installed with the following command:

    $ apt-get install iptables-persistent

Rationale: | A method of configuring and maintaining firewall rules is necessary to configure a Host Based Firewall.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_iptables-persistent_installed

References:

cis | 4.4.1.1

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}' 'iptables' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "iptables-persistent"

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

Remediation Puppet snippet ⇲

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

    include install_iptables-persistent

    class install_iptables-persistent {
      package { 'iptables-persistent':
        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_iptables-persistent_installed

    - name: Ensure iptables-persistent is installed
      ansible.builtin.package:
        name: iptables-persistent
        state: present
      when: '"iptables" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_iptables-persistent_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "iptables-persistent"
    version = "*"

#### Rule Install iptables Package [ref]

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

    $ apt-get install iptables

Rationale: | `iptables` controls the Linux kernel network packet filtering code. `iptables` allows system operators to set up firewalls and IP masquerading, etc.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_iptables_installed

References:

nist | CM-6(a)
pcidss | Req-1.4.1
os-srg | SRG-OS-000480-GPOS-00227
cis | 4.4.1.1

Remediation Shell script ⇲

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

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

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

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

Remediation Puppet snippet ⇲

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

    include install_iptables

    class install_iptables {
      package { 'iptables':
        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-1.4.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_iptables_installed

    - name: Ensure iptables is installed
      ansible.builtin.package:
        name: iptables
        state: present
      when: ( "linux-base" in ansible_facts.packages )
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-1.4.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_iptables_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Remove iptables-persistent Package [ref]

The `iptables-persistent` package can be removed with the following command:

    $ apt-get remove iptables-persistent

Rationale: | Running both `ufw` and the services included in the `iptables-persistent` package may lead to conflict.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_iptables-persistent_removed

References:

cis | 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}' 'ufw' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove iptables-persistent
    # from the system, and may remove any packages
    # that depend on iptables-persistent. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "iptables-persistent"

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

Remediation Puppet snippet ⇲

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

    include remove_iptables-persistent

    class remove_iptables-persistent {
      package { 'iptables-persistent':
        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
      - medium_severity
      - no_reboot_needed
      - package_iptables-persistent_removed

    - name: 'Remove iptables-persistent Package: Ensure iptables-persistent is removed'
      ansible.builtin.package:
        name: iptables-persistent
        state: absent
      when: '"ufw" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_iptables-persistent_removed

Group IPv6 Group contains 1 group and 7 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 7 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 Router Advertisements on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_ra` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_ra=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 = 0

Rationale: | An illicit router advertisement 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_ra

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
cis | 3.3.11

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 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.*$' $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" 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_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_ra
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_ra="$sysctl_net_ipv6_conf_all_accept_ra_value"
    fi

    #
    # If net.ipv6.conf.all.accept_ra present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_ra = 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")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_ra_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\\>" "${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\\>.*/$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_ra
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_ra_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_ra_value: !!str 0
      tags:
        - always

    - name: Configure Accepting 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:
      - 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_ra

    - name: Configure Accepting Router Advertisements on All IPv6 Interfaces - Find all
        files that contain net.ipv6.conf.all.accept_ra
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra\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_ra

    - name: Configure Accepting Router Advertisements on All IPv6 Interfaces - Find all
        files that set net.ipv6.conf.all.accept_ra 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\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_ra_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_ra

    - name: Configure Accepting Router Advertisements on All IPv6 Interfaces - Comment
        out any occurrences of net.ipv6.conf.all.accept_ra from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_ra
        replace: '#net.ipv6.conf.all.accept_ra'
      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_ra

    - name: Configure Accepting Router Advertisements on All IPv6 Interfaces - Ensure
        sysctl net.ipv6.conf.all.accept_ra is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_ra
        value: '{{ sysctl_net_ipv6_conf_all_accept_ra_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_ra

#### 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
cis | 3.3.5

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
cis | 3.3.8

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 Disable Kernel Parameter for IPv6 Forwarding [ref]

To set the runtime status of the `net.ipv6.conf.all.forwarding` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.forwarding=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.forwarding = 0

Rationale: | IP forwarding permits the kernel to forward packets from one network interface to another. The ability to forward packets between two networks is only appropriate for systems acting as routers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_forwarding

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
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), CM-6(b), CM-6.1(iv)
nist-csf | DE.CM-1, PR.DS-4, PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
cis | 3.3.1

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.forwarding 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.forwarding.*$' $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.forwarding" 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_forwarding_value='0'

    #
    # Set runtime for net.ipv6.conf.all.forwarding
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.forwarding="$sysctl_net_ipv6_conf_all_forwarding_value"
    fi

    #
    # If net.ipv6.conf.all.forwarding present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.forwarding = 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.forwarding")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_forwarding_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.forwarding\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.forwarding\\>.*/$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-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_forwarding
    - name: XCCDF Value sysctl_net_ipv6_conf_all_forwarding_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_forwarding_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for IPv6 Forwarding - 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-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_forwarding

    - name: Disable Kernel Parameter for IPv6 Forwarding - Find all files that contain
        net.ipv6.conf.all.forwarding
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.forwarding\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-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_forwarding

    - name: Disable Kernel Parameter for IPv6 Forwarding - Find all files that set net.ipv6.conf.all.forwarding
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.forwarding\s*=\s*{{ sysctl_net_ipv6_conf_all_forwarding_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-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_forwarding

    - name: Disable Kernel Parameter for IPv6 Forwarding - Comment out any occurrences
        of net.ipv6.conf.all.forwarding from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.forwarding
        replace: '#net.ipv6.conf.all.forwarding'
      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-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_forwarding

    - name: Disable Kernel Parameter for IPv6 Forwarding - Ensure sysctl net.ipv6.conf.all.forwarding
        is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.forwarding
        value: '{{ sysctl_net_ipv6_conf_all_forwarding_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-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_forwarding

#### Rule Disable Accepting Router Advertisements on all IPv6 Interfaces by Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_ra` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_ra=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 = 0

Rationale: | An illicit router advertisement 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_ra

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
cis | 3.3.11

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 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.*$' $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" 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_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_ra
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_ra="$sysctl_net_ipv6_conf_default_accept_ra_value"
    fi

    #
    # If net.ipv6.conf.default.accept_ra present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_ra = 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")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_ra_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\\>" "${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\\>.*/$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_ra
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_ra_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_ra_value: !!str 0
      tags:
        - always

    - name: Disable Accepting 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:
      - 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_ra

    - name: Disable Accepting Router Advertisements on all IPv6 Interfaces by Default
        - Find all files that contain net.ipv6.conf.default.accept_ra
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra\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_ra

    - name: Disable Accepting Router Advertisements on all IPv6 Interfaces by Default
        - Find all files that set net.ipv6.conf.default.accept_ra 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\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_ra_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_ra

    - name: Disable Accepting Router Advertisements on all IPv6 Interfaces by Default
        - Comment out any occurrences of net.ipv6.conf.default.accept_ra from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_ra
        replace: '#net.ipv6.conf.default.accept_ra'
      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_ra

    - name: Disable Accepting Router Advertisements on all IPv6 Interfaces by Default
        - Ensure sysctl net.ipv6.conf.default.accept_ra is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_ra
        value: '{{ sysctl_net_ipv6_conf_default_accept_ra_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_ra

#### 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
cis | 3.3.5

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
cis | 3.3.8
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

Group Kernel Parameters Which Affect Networking Group contains 2 groups and 16 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 13 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 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
cis | 3.3.5

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
cis | 3.3.8

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 Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.log_martians` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.log_martians=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.log_martians = 1

Rationale: | The presence of "martian" packets (which have impossible addresses) as well as spoofed packets, source-routed packets, and redirects could be a sign of nefarious network activity. Logging these packets enables this activity to be detected.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_log_martians

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, DSS01.04, DSS03.05, DSS05.02, DSS05.03, 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.11.2.6, 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.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), SC-5(3)(a)
nist-csf | DE.CM-1, PR.AC-3, PR.DS-4, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
cis | 3.3.9

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.log_martians 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.log_martians.*$' $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.log_martians" 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_log_martians_value='1'

    #
    # Set runtime for net.ipv4.conf.all.log_martians
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.log_martians="$sysctl_net_ipv4_conf_all_log_martians_value"
    fi

    #
    # If net.ipv4.conf.all.log_martians present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.log_martians = 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.log_martians")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_log_martians_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.log_martians\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.log_martians\\>.*/$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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv4_conf_all_log_martians_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_log_martians_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Log Martian 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-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces - Find
        all files that contain net.ipv4.conf.all.log_martians
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.log_martians\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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces - Find
        all files that set net.ipv4.conf.all.log_martians to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.log_martians\s*=\s*{{ sysctl_net_ipv4_conf_all_log_martians_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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces - Comment
        out any occurrences of net.ipv4.conf.all.log_martians from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.log_martians
        replace: '#net.ipv4.conf.all.log_martians'
      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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces - Ensure
        sysctl net.ipv4.conf.all.log_martians is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.log_martians
        value: '{{ sysctl_net_ipv4_conf_all_log_martians_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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_all_log_martians
      - unknown_severity

#### 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
cis | 3.3.7
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
cis | 3.3.6
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 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
cis | 3.3.5
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
cis | 3.3.8

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 Log Martian Packets on all IPv4 Interfaces by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.log_martians` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.log_martians=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.log_martians = 1

Rationale: | The presence of "martian" packets (which have impossible addresses) as well as spoofed packets, source-routed packets, and redirects could be a sign of nefarious network activity. Logging these packets enables this activity to be detected.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_log_martians

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, DSS01.04, DSS03.05, DSS05.02, DSS05.03, 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.11.2.6, 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.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), SC-5(3)(a)
nist-csf | DE.CM-1, PR.AC-3, PR.DS-4, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
cis | 3.3.9

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.log_martians 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.log_martians.*$' $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.log_martians" 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_log_martians_value='1'

    #
    # Set runtime for net.ipv4.conf.default.log_martians
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.log_martians="$sysctl_net_ipv4_conf_default_log_martians_value"
    fi

    #
    # If net.ipv4.conf.default.log_martians present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.log_martians = 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.log_martians")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_log_martians_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.log_martians\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.log_martians\\>.*/$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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv4_conf_default_log_martians_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_log_martians_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Log Martian Packets 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-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces by Default
        - Find all files that contain net.ipv4.conf.default.log_martians
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.log_martians\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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces by Default
        - Find all files that set net.ipv4.conf.default.log_martians to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.log_martians\s*=\s*{{ sysctl_net_ipv4_conf_default_log_martians_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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces by Default
        - Comment out any occurrences of net.ipv4.conf.default.log_martians from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.log_martians
        replace: '#net.ipv4.conf.default.log_martians'
      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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity

    - name: Enable Kernel Parameter to Log Martian Packets on all IPv4 Interfaces by Default
        - Ensure sysctl net.ipv4.conf.default.log_martians is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.log_martians
        value: '{{ sysctl_net_ipv4_conf_default_log_martians_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(3)(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_conf_default_log_martians
      - unknown_severity

#### 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
cis | 3.3.7

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
cis | 3.3.6

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 Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.icmp_echo_ignore_broadcasts` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.icmp_echo_ignore_broadcasts=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_echo_ignore_broadcasts = 1

Rationale: | Responding to broadcast (ICMP) echoes facilitates network mapping and provides a vector for amplification attacks. Ignoring ICMP echo requests (pings) sent to broadcast or multicast addresses makes the system slightly more difficult to enumerate on the network.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_icmp_echo_ignore_broadcasts

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
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
cis | 3.3.4
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_echo_ignore_broadcasts 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_echo_ignore_broadcasts.*$' $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_echo_ignore_broadcasts" 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_echo_ignore_broadcasts_value='1'

    #
    # Set runtime for net.ipv4.icmp_echo_ignore_broadcasts
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.icmp_echo_ignore_broadcasts="$sysctl_net_ipv4_icmp_echo_ignore_broadcasts_value"
    fi

    #
    # If net.ipv4.icmp_echo_ignore_broadcasts present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.icmp_echo_ignore_broadcasts = 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_echo_ignore_broadcasts")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_icmp_echo_ignore_broadcasts_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_echo_ignore_broadcasts\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.icmp_echo_ignore_broadcasts\\>.*/$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
      - 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_ipv4_icmp_echo_ignore_broadcasts
    - name: XCCDF Value sysctl_net_ipv4_icmp_echo_ignore_broadcasts_value # promote to variable
      set_fact:
        sysctl_net_ipv4_icmp_echo_ignore_broadcasts_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests 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-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
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_icmp_echo_ignore_broadcasts

    - name: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests on IPv4 Interfaces
        - Find all files that contain net.ipv4.icmp_echo_ignore_broadcasts
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.icmp_echo_ignore_broadcasts\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
      - 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_ipv4_icmp_echo_ignore_broadcasts

    - name: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests on IPv4 Interfaces
        - Find all files that set net.ipv4.icmp_echo_ignore_broadcasts to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.icmp_echo_ignore_broadcasts\s*=\s*{{ sysctl_net_ipv4_icmp_echo_ignore_broadcasts_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
      - 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_ipv4_icmp_echo_ignore_broadcasts

    - name: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests on IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.icmp_echo_ignore_broadcasts from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.icmp_echo_ignore_broadcasts
        replace: '#net.ipv4.icmp_echo_ignore_broadcasts'
      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
      - 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_ipv4_icmp_echo_ignore_broadcasts

    - name: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests on IPv4 Interfaces
        - Ensure sysctl net.ipv4.icmp_echo_ignore_broadcasts is set
      ansible.posix.sysctl:
        name: net.ipv4.icmp_echo_ignore_broadcasts
        value: '{{ sysctl_net_ipv4_icmp_echo_ignore_broadcasts_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
      - 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_ipv4_icmp_echo_ignore_broadcasts

#### 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
cis | 3.3.3
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 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
cis | 3.3.10
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
cis | 3.3.2
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
cis | 3.3.2
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
cis | 3.3.1
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 8 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 Install nftables Package [ref]

nftables provides a new in-kernel packet classification framework that is based on a network-specific Virtual Machine (VM) and a new nft userspace command line tool. nftables reuses the existing Netfilter subsystems such as the existing hook infrastructure, the connection tracking system, NAT, userspace queuing and logging subsystem. The `nftables` package can be installed with the following command:

    $ apt-get install nftables

Rationale: | `nftables` is a subsystem of the Linux kernel that can protect against threats originating from within a corporate network to include malicious mobile code and poorly configured software on a host.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_nftables_installed

References:

cis | 4.3.1
pcidss4 | 1.2.1, 1.2

Remediation Shell script ⇲

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

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

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

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

Remediation Puppet snippet ⇲

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

    include install_nftables

    class install_nftables {
      package { 'nftables':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_nftables_installed

    - name: Ensure nftables is installed
      ansible.builtin.package:
        name: nftables
        state: present
      when: ( "linux-base" in ansible_facts.packages )
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_nftables_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Verify nftables Service is Enabled [ref]

The nftables service allows for the loading of nftables rulesets during boot, or starting on the nftables service The `nftables` service can be enabled with the following command:

    $ sudo systemctl enable nftables.service

Rationale: | The nftables service restores the nftables rules from the rules files referenced in the `/etc/sysconfig/nftables.conf` file during boot or the starting of the nftables service
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_nftables_enabled

References:

cis | 4.3.9

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}' 'nftables' 2>/dev/null | grep -q '^installed$' && ! (systemctl is-active firewalld &>/dev/null) && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'nftables.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'nftables.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'nftables.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_nftables

    class enable_nftables {
      service {'nftables':
        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:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_nftables_enabled

    - name: Verify nftables Service is Enabled - Enable service nftables
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Verify nftables Service is Enabled - Enable Service nftables
        ansible.builtin.systemd:
          name: nftables
          enabled: true
          state: started
          masked: false
        when:
        - '"nftables" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_nftables_enabled
      - special_service_block
      when: ( "nftables" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["nftables"]

#### Rule Verify nftables Service is Disabled [ref]

nftables is a subsystem of the Linux kernel providing filtering and classification of network packets/datagrams/frames and is the successor to iptables. The `nftables` service can be disabled with the following command:

    systemctl disable nftables

Rationale: | Running both `firewalld` and `nftables` may lead to conflict. `nftables` is actually one of the backends for `firewalld` management tools.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_nftables_disabled

References:

cis | 4.4.1.2
pcidss4 | 1.2.1, 1.2

Remediation Puppet snippet ⇲

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

    include disable_nftables

    class disable_nftables {
      service {'nftables':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_nftables_disabled

    - name: Verify nftables Service is Disabled - Disable service nftables
      block:

      - name: Verify nftables Service is Disabled - Collect systemd Services Present in
          the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Verify nftables Service is Disabled - Ensure nftables.service is Masked
        ansible.builtin.systemd:
          name: nftables.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("nftables.service", multiline=True)

      - name: Unit Socket Exists - nftables.socket
        ansible.builtin.command: systemctl -q list-unit-files nftables.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Verify nftables Service is Disabled - Disable Socket nftables
        ansible.builtin.systemd:
          name: nftables.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("nftables.socket", multiline=True)
      tags:
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_nftables_disabled
      - special_service_block
      when: ( "firewalld" in ansible_facts.packages and "nftables" in ansible_facts.packages
        and "linux-base" in ansible_facts.packages )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["nftables"]

#### Rule Ensure nftables Default Deny Firewall Policy [ref]

Base chain policy is the default verdict that will be applied to packets reaching the end of the chain. There are two policies: accept (Default) and drop. If the policy is set to accept, the firewall will accept any packet that is not configured to be denied and the packet will continue traversing the network stack. Run the following commands and verify that base chains contain a policy of DROP.

    $ nft list ruleset | grep 'hook input'
    type filter hook input priority 0; policy drop;
    $ nft list ruleset | grep 'hook forward'
    type filter hook forward priority 0; policy drop;
    $ nft list ruleset | grep 'hook output'
    type filter hook output priority 0; policy drop;

Warning: Changing firewall settings while connected over network can result in being locked out of the system.

Rationale: | It is easier to allow acceptable usage than to block unacceptable usage.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_nftables_ensure_default_deny_policy

References:

cis | 4.3.8
pcidss4 | 1.3.1, 1.3

#### Rule Ensure nftables Rules are Permanent [ref]

nftables is a subsystem of the Linux kernel providing filtering and classification of network packets/datagrams/frames. The nftables service reads the /etc/nftables.conf file for a nftables file or files to include in the nftables ruleset. A nftables ruleset containing the input, forward, and output base chains allow network traffic to be filtered.
Rationale: | Changes made to nftables ruleset only affect the live system, you will also need to configure the nftables ruleset to apply on boot
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_nftables_rules_permanent

References:

cis | 4.3.10

#### Rule Ensure Base Chains Exist for Nftables [ref]

Tables in nftables hold chains. Each table only has one address family and only applies to packets of this family. Tables can have one of six families. Chains are containers for rules. They exist in two kinds, base chains and regular chains. A base chain is an entry point for packets from the networking stack, a regular chain may be used as jump target and is used for better rule organization.
Warning: Configuring rules over ssh, by creating a base chain with policy drop will cause loss of connectivity. Ensure that a rule allowing ssh has been added to the base chain prior to setting the base cahin's policy to drop

Rationale: | If a base chain doesn't exist with a hook for input, forward, and delete, packets that would flow through those chains will not be touched by nftables.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_nftables_base_chain

References:

cis | 4.3.5

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}' 'nftables' 2>/dev/null | grep -q '^installed$'; then

    #Name of the table
    var_nftables_table='filter'

    #Family of the table
    var_nftables_family='inet'

    #Name(s) of base chain
    var_nftables_base_chain_names='input,forward,output'

    #Type(s) of base chain
    var_nftables_base_chain_types='filter,filter,filter'

    # Hooks for base chain
    var_nftables_base_chain_hooks='input,forward,output'

    #Priority
    var_nftables_base_chain_priorities='0,0,0'

    #Policy
    var_nftables_base_chain_policies='accept,accept,accept'

    #Transfer some of strings to arrays
    IFS="," read -r -a  names <<< "$var_nftables_base_chain_names"
    IFS="," read -r -a  types <<< "$var_nftables_base_chain_types"
    IFS="," read -r -a  hooks <<< "$var_nftables_base_chain_hooks"
    IFS="," read -r -a  priorities <<< "$var_nftables_base_chain_priorities"
    IFS="," read -r -a  policies <<< "$var_nftables_base_chain_policies"

    my_cmd="nft list tables | grep '$var_nftables_family $var_nftables_table'"
    eval IS_TABLE_EXIST=\$\($my_cmd\)
    if [ -z "$IS_TABLE_EXIST" ]
    then
      # We create a table and add chains to it
      nft create table "$var_nftables_family" "$var_nftables_table"
      num_of_chains=${#names[@]}
      for ((i=0; i < num_of_chains; i++))
      do
       chain_to_add="add chain $var_nftables_family $var_nftables_table ${names[$i]} { type ${types[$i]} hook ${hooks[$i]} priority ${priorities[$i]} ; policy ${policies[$i]} ; }"
       my_cmd="nft '$chain_to_add'"
       eval $my_cmd
      done
    else
      # We add missing chains to the existing table
      num_of_chains=${#names[@]}
      for ((i=0; i < num_of_chains; i++))
      do
        IS_CHAIN_EXIST=$(nft list table "$var_nftables_family" "$var_nftables_table" | grep "hook ${hooks[$i]}")
        if [ -z "$IS_CHAIN_EXIST" ]
          then
            chain_to_add="add chain '$var_nftables_family' '$var_nftables_table' ${names[$i]} { type ${types[$i]} hook ${hooks[$i]} priority ${priorities[$i]} ; policy ${policies[$i]} ; }"
            my_cmd="nft '$chain_to_add'"
            eval $my_cmd
        fi
      done
    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
      - set_nftables_base_chain
    - name: XCCDF Value var_nftables_table # promote to variable
      set_fact:
        var_nftables_table: !!str filter
      tags:
        - always
    - name: XCCDF Value var_nftables_family # promote to variable
      set_fact:
        var_nftables_family: !!str inet
      tags:
        - always
    - name: XCCDF Value var_nftables_base_chain_names # promote to variable
      set_fact:
        var_nftables_base_chain_names: !!str input,forward,output
      tags:
        - always
    - name: XCCDF Value var_nftables_base_chain_types # promote to variable
      set_fact:
        var_nftables_base_chain_types: !!str filter,filter,filter
      tags:
        - always
    - name: XCCDF Value var_nftables_base_chain_hooks # promote to variable
      set_fact:
        var_nftables_base_chain_hooks: !!str input,forward,output
      tags:
        - always
    - name: XCCDF Value var_nftables_base_chain_priorities # promote to variable
      set_fact:
        var_nftables_base_chain_priorities: !!str 0,0,0
      tags:
        - always
    - name: XCCDF Value var_nftables_base_chain_policies # promote to variable
      set_fact:
        var_nftables_base_chain_policies: !!str accept,accept,accept
      tags:
        - always

    - name: Ensure Base Chains Exist for Nftables - Check Existence of Nftables Table
      ansible.builtin.shell: nft list tables | grep '{{ var_nftables_family }} {{ var_nftables_table
        }}'
      register: existing_nftables
      changed_when: false
      failed_when: false
      when: '"nftables" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_base_chain

    - name: Ensure Base Chains Exist for Nftables - Set NFTables Table
      ansible.builtin.command: nft create table {{ var_nftables_family }} {{ var_nftables_table
        }}
      when:
      - '"nftables" in ansible_facts.packages'
      - existing_nftables is not skipped and existing_nftables.rc > 0
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_base_chain

    - name: Ensure Base Chains Exist for Nftables - Add Base Chains
      ansible.builtin.command: nft 'add chain {{ var_nftables_family }} {{ var_nftables_table
        }} {{ item.0 }} { type {{ item.1 }} hook {{ item.2 }} priority {{ item.3 }} ;
        policy {{ item.4 }} ; }'
      with_together:
      - '{{ var_nftables_base_chain_names.split(",") }}'
      - '{{ var_nftables_base_chain_types.split(",") }}'
      - '{{ var_nftables_base_chain_hooks.split(",") }}'
      - '{{ var_nftables_base_chain_priorities.split(",") }}'
      - '{{ var_nftables_base_chain_policies.split(",") }}'
      when: '"nftables" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_base_chain

#### Rule Set nftables Configuration for Loopback Traffic [ref]

Configure the loopback interface to accept traffic. Configure all other interfaces to deny traffic to the loopback network.
Warning: Changing firewall settings while connected over network can result in being locked out of the system. Keep in mind the remediation makes changes only to the running system, in order to keep the changes need to take care to save the nft settings to the relvant configutation files.

Rationale: | Loopback traffic is generated between processes on machine and is typically critical to operation of the system. The loopback interface is the only place that loopback network traffic should be seen, all other interfaces should ignore traffic on this network as an anti-spoofing measure.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_nftables_loopback_traffic

References:

pcidss | Req-1.4.1
cis | 4.3.6

Remediation Shell script ⇲

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

    grubfile="/boot/grub/grub.cfg"

    # Implement the loopback rules:
    nft add rule inet filter input iif lo accept
    nft add rule inet filter input ip saddr 127.0.0.0/8 counter drop

    # Check IPv6 is disabled, if false implement IPv6 loopback rules
    disabled="false"
    [ -f "$grubfile" ] && ! grep "^\s*linux" "$grubfile" | grep -vq "ipv6.disable=1" && disabled="true"

    grep -Eq "^\s*net\.ipv6\.conf\.all\.disable_ipv6\s*=\s*1\b(\s+#.*)?$" \
    /etc/sysctl.conf /etc/sysctl.d/*.conf && \
    grep -Eq "^\s*net\.ipv6\.conf\.default\.disable_ipv6\s*=\s*1\b(\s+#.*)?$" \
    /etc/sysctl.conf /etc/sysctl.d/*.conf && sysctl net.ipv6.conf.all.disable_ipv6 | \
    grep -Eq "^\s*net\.ipv6\.conf\.all\.disable_ipv6\s*=\s*1\b(\s+#.*)?$" && \
    sysctl net.ipv6.conf.default.disable_ipv6 | \
    grep -Eq "^\s*net\.ipv6\.conf\.default\.disable_ipv6\s*=\s*1\b(\s+#.*)?$" && disabled="true"

    # Is IPv6 Disabled? (true/false)
    if [ "$disabled" = false ] ; then
        nft add rule inet filter input ip6 saddr ::1 counter drop
    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-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Implement Loopback Rules
      ansible.builtin.command: nft add rule inet filter input iif lo accept
      when: ( "nftables" in ansible_facts.packages )
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Create Rule to Drop Input IP Address from Loopback
      ansible.builtin.command: nft add rule inet filter input ip saddr 127.0.0.0/8 counter
        drop
      when: ( "nftables" in ansible_facts.packages )
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Check if IPv6 is Disabled in grub Configuration
      ansible.builtin.shell: |
        [ -z "$(grep "^\s*linux" /boot/grub2/grub.cfg | grep -v ipv6.disabled=1)" ]
      register: ipv6_status
      changed_when: false
      check_mode: false
      when: ( "nftables" in ansible_facts.packages )
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Check sysctl value of net.ipv6.conf.all.disable_ipv6
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.disable_ipv6
        state: present
        value: '1'
      check_mode: true
      register: sysctl_ipv6_all
      when: ( "nftables" in ansible_facts.packages )
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Check sysctl value of net.ipv6.conf.default.disable_ipv6
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.disable_ipv6
        state: present
        value: '1'
      check_mode: true
      register: sysctl_ipv6_default
      when: ( "nftables" in ansible_facts.packages )
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

    - name: Implement IPv6 loopback rules
      ansible.builtin.command: nft add rule inet filter input ip6 saddr ::1 counter drop
      when:
      - ( "nftables" in ansible_facts.packages )
      - ipv6_status is not skipped
      - sysctl_ipv6_default is not skipped
      - sysctl_ipv6_all is not skipped
      - ipv6_status.rc == 0 or sysctl_ipv6_all.found > 0 or sysctl_ipv6_default.found
        > 0
      tags:
      - PCI-DSS-Req-1.4.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_loopback_traffic

#### Rule Ensure a Table Exists for Nftables [ref]

Tables in nftables hold chains. Each table only has one address family and only applies to packets of this family. Tables can have one of six families.
Warning: Adding or editing rules in a running nftables can cause loss of connectivity to the system.
Warning: Both the SCE check and remediation for this rule only consider runtime settings. There is no specific file to check as it depends on each site's policy. Therefore, check and remediation use the nft command directly. The fix is not persistent across system reboots.
Warning: SCE check does not support variables, therefore the SCE check in this rule only checks the address family, regardless of the table name.

Rationale: | Nftables doesn't have any default tables. Without a table being built, nftables will not filter network traffic.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_nftables_table

References:

cis | 4.3.4

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}' 'nftables' 2>/dev/null | grep -q '^installed$'; then

    var_nftables_family='inet'

    var_nftables_table='filter'

    if ! nft list table $var_nftables_family $var_nftables_table; then
      nft create table "$var_nftables_family" "$var_nftables_table"
    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
      - set_nftables_table
    - name: XCCDF Value var_nftables_family # promote to variable
      set_fact:
        var_nftables_family: !!str inet
      tags:
        - always
    - name: XCCDF Value var_nftables_table # promote to variable
      set_fact:
        var_nftables_table: !!str filter
      tags:
        - always

    - name: Collect Existing Nftables
      ansible.builtin.command: nft list table {{ var_nftables_family }} {{ var_nftables_table
        }}
      register: result_nftables_table_family
      changed_when: false
      failed_when: result_nftables_table_family.rc not in [0, 1]
      when: '"nftables" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_table

    - name: Set Nftable Table
      ansible.builtin.command: nft create table {{ var_nftables_family }} {{ var_nftables_table
        }}
      when:
      - '"nftables" in ansible_facts.packages'
      - result_nftables_table_family is not skipped
      - result_nftables_table_family.rc != 0
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_nftables_table

Group Uncomplicated Firewall (ufw) Group contains 7 rules

[ref] The Linux kernel in Ubuntu provides a packet filtering system called netfilter, and the traditional interface for manipulating netfilter are the iptables suite of commands. iptables provide a complete firewall solution that is both highly configurable and highly flexible. Becoming proficient in iptables takes time, and getting started with netfilter firewalling using only iptables can be a daunting task. As a result, many frontends for iptables have been created over the years, each trying to achieve a different result and targeting a different audience. The Uncomplicated Firewall (ufw) is a frontend for iptables and is particularly well-suited for host-based firewalls. ufw provides a framework for managing netfilter, as well as a command-line interface for manipulating the firewall. ufw aims to provide an easy to use interface for people unfamiliar with firewall concepts, while at the same time simplifies complicated iptables commands to help an administrator who knows what he or she is doing. ufw is an upstream for other distributions and graphical frontends.

#### Rule Install ufw Package [ref]

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

    $ apt-get install ufw

Rationale: | `ufw` controls the Linux kernel network packet filtering code. `ufw` allows system operators to set up firewalls and IP masquerading, etc.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_ufw_installed

References:

os-srg | SRG-OS-000297-GPOS-00115
cis | 4.2.1

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 "ufw"

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

Remediation Puppet snippet ⇲

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

    include install_ufw

    class install_ufw {
      package { 'ufw':
        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_ufw_installed

    - name: Ensure ufw is installed
      ansible.builtin.package:
        name: ufw
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_ufw_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Remove ufw Package [ref]

The `ufw` package can be removed with the following command:

    $ apt-get remove ufw

Rationale: | Running `iptables.persistent` with `ufw` enabled may lead to conflict and unexpected results.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_ufw_removed

References:

cis | 4.3.2, 4.4.1.3

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 ufw
    # from the system, and may remove any packages
    # that depend on ufw. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "ufw"

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

Remediation Puppet snippet ⇲

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

    include remove_ufw

    class remove_ufw {
      package { 'ufw':
        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
      - medium_severity
      - no_reboot_needed
      - package_ufw_removed

    - name: 'Remove ufw Package: Ensure ufw is removed'
      ansible.builtin.package:
        name: ufw
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_ufw_removed

#### Rule Verify ufw Enabled [ref]

The `ufw` service can be enabled with the following command:

    $ sudo systemctl enable ufw.service

Rationale: | The ufw service must be enabled and running in order for ufw to protect the system
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_ufw_enabled

References:

os-srg | SRG-OS-000297-GPOS-00115
cis | 4.2.3

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}' 'ufw' 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 'ufw.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'ufw.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'ufw.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_ufw

    class enable_ufw {
      service {'ufw':
        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:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_ufw_enabled

    - name: Verify ufw Enabled - Enable service ufw
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Verify ufw Enabled - Enable Service ufw
        ansible.builtin.systemd:
          name: ufw
          enabled: true
          state: started
          masked: false
        when:
        - '"ufw" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_ufw_enabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( "ufw" in ansible_facts.packages and "linux-base" in ansible_facts.packages )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["ufw"]

#### Rule Verify ufw Active [ref]

Verify the ufw is enabled on the system with the following command:

    # sudo ufw status

If the above command returns the status as "inactive" or any type of error, this is a finding.

Rationale:

Remote access services, such as those providing remote access to network devices and information systems, which lack automated control capabilities, increase risk and make remote user access management difficult at best. Remote access is access to nonpublic information systems by an authorized user (or an information system) communicating through an external, nonorganization-controlled network. Remote access methods include, for example, dial-up, broadband, and wireless. Ubuntu 22.04 LTS functionality (e.g., RDP) must be capable of taking enforcement action if the audit reveals unauthorized activity. Automated control of remote access sessions allows organizations to ensure ongoing compliance with remote access policies by enforcing connection rules of remote access applications on a variety of information system components.

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

References:

cis | 4.2.3

#### Rule Ensure ufw Default Deny Firewall Policy [ref]

A default deny policy on connections ensures that any unconfigured network usage will be rejected. Note: Any port or protocol without a explicit allow before the default deny will be blocked. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | With a default accept policy the firewall will accept any packet that is not configured to be denied. It is easier to allow acceptable usage than to block unacceptable usage.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_ufw_default_rule

References:

cis | 4.2.7

#### Rule Set UFW Loopback Traffic [ref]

Configure the loopback interface to accept traffic. Configure all other interfaces to deny traffic to the loopback network. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Loopback traffic is generated between processes on machine and is typically critical to operation of the system. The loopback interface is the only place that loopback network traffic should be seen, all other interfaces should ignore traffic on this network as an anti-spoofing measure.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_ufw_loopback_traffic

References:

cis | 4.2.4

#### Rule Ensure ufw Firewall Rules Exist for All Open Ports [ref]

Any ports that have been opened on non-loopback addresses need firewall rules to govern traffic. Warning: Changing firewall settings while connected over network can result in being locked out of the system.
Rationale: | Without a firewall rule configured for open ports default firewall policy will drop all packets to these ports.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ufw_rules_for_open_ports

References:

cis | 4.2.6

Group Uncommon Network Protocols Group contains 4 rules

[ref] The system includes support for several network protocols which are not commonly used. Although security vulnerabilities in kernel networking code are not frequently discovered, the consequences can be dramatic. Ensuring uncommon network protocols are disabled reduces the system's risk to attacks targeted at its implementation of those protocols.
Warning: Although these protocols are not commonly used, avoid disruption in your network environment by ensuring they are not needed prior to disabling them.

#### Rule Disable DCCP Support [ref]

The Datagram Congestion Control Protocol (DCCP) is a relatively new transport layer protocol, designed to support streaming media and telephony. To configure the system to prevent the `dccp` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/dccp.conf`:

    install dccp /bin/false

This entry will cause a non-zero return value during a `dccp` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install dccp /bin/true

Rationale: | Disabling DCCP protects the system against exploitation of any flaws in its implementation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_dccp_disabled

References:

cis-csc | 11, 14, 3, 9
cjis | 5.10.1
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
pcidss | Req-1.4.2
os-srg | SRG-OS-000096-GPOS-00050, SRG-OS-000378-GPOS-00163
cis | 3.2.1
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

    if LC_ALL=C grep -q -m 1 "^install dccp" /etc/modprobe.d/dccp.conf ; then

    	sed -i 's#^install dccp.*#install dccp /bin/false#g' /etc/modprobe.d/dccp.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/dccp.conf
    	echo "install dccp /bin/false" >> /etc/modprobe.d/dccp.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist dccp$" /etc/modprobe.d/dccp.conf ; then
    	echo "blacklist dccp" >> /etc/modprobe.d/dccp.conf
    fi

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

#### Rule Disable RDS Support [ref]

The Reliable Datagram Sockets (RDS) protocol is a transport layer protocol designed to provide reliable high-bandwidth, low-latency communications between nodes in a cluster. To configure the system to prevent the `rds` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/rds.conf`:

    install rds /bin/false

This entry will cause a non-zero return value during a `rds` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install rds /bin/true

Rationale: | Disabling RDS protects the system against exploitation of any flaws in its implementation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_rds_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
cis | 3.2.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

    if LC_ALL=C grep -q -m 1 "^install rds" /etc/modprobe.d/rds.conf ; then

    	sed -i 's#^install rds.*#install rds /bin/false#g' /etc/modprobe.d/rds.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/rds.conf
    	echo "install rds /bin/false" >> /etc/modprobe.d/rds.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist rds$" /etc/modprobe.d/rds.conf ; then
    	echo "blacklist rds" >> /etc/modprobe.d/rds.conf
    fi

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

#### Rule Disable SCTP Support [ref]

The Stream Control Transmission Protocol (SCTP) is a transport layer protocol, designed to support the idea of message-oriented communication, with several streams of messages within one connection. To configure the system to prevent the `sctp` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/sctp.conf`:

    install sctp /bin/false

This entry will cause a non-zero return value during a `sctp` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install sctp /bin/true

Rationale: | Disabling SCTP protects the system against exploitation of any flaws in its implementation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_sctp_disabled

References:

cis-csc | 11, 14, 3, 9
cjis | 5.10.1
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
ospp | FMT_SMF_EXT.1
pcidss | Req-1.4.2
os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
cis | 3.2.4
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

    if LC_ALL=C grep -q -m 1 "^install sctp" /etc/modprobe.d/sctp.conf ; then

    	sed -i 's#^install sctp.*#install sctp /bin/false#g' /etc/modprobe.d/sctp.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/sctp.conf
    	echo "install sctp /bin/false" >> /etc/modprobe.d/sctp.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist sctp$" /etc/modprobe.d/sctp.conf ; then
    	echo "blacklist sctp" >> /etc/modprobe.d/sctp.conf
    fi

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

#### Rule Disable TIPC Support [ref]

The Transparent Inter-Process Communication (TIPC) protocol is designed to provide communications between nodes in a cluster. To configure the system to prevent the `tipc` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/tipc.conf`:

    install tipc /bin/false

This entry will cause a non-zero return value during a `tipc` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install tipc /bin/true

Warning: This configuration baseline was created to deploy the base operating system for general purpose workloads. When the operating system is configured for certain purposes, such as a node in High Performance Computing cluster, it is expected that the `tipc` kernel module will be loaded.

Rationale: | Disabling TIPC protects the system against exploitation of any flaws in its implementation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_tipc_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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000095-GPOS-00049
cis | 3.2.2

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

    if LC_ALL=C grep -q -m 1 "^install tipc" /etc/modprobe.d/tipc.conf ; then

    	sed -i 's#^install tipc.*#install tipc /bin/false#g' /etc/modprobe.d/tipc.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/tipc.conf
    	echo "install tipc /bin/false" >> /etc/modprobe.d/tipc.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist tipc$" /etc/modprobe.d/tipc.conf ; then
    	echo "blacklist tipc" >> /etc/modprobe.d/tipc.conf
    fi

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

Group Wireless Networking Group contains 1 group and 2 rules

[ref] Wireless networking, such as 802.11 (WiFi) and Bluetooth, can present a security risk to sensitive or classified systems and networks. Wireless networking hardware is much more likely to be included in laptop or portable systems than in desktops or servers.
Removal of hardware provides the greatest assurance that the wireless capability remains disabled. Acquisition policies often include provisions to prevent the purchase of equipment that will be used in sensitive spaces and includes wireless capabilities. If it is impractical to remove the wireless hardware, and policy permits the device to enter sensitive spaces as long as wireless is disabled, efforts should instead focus on disabling wireless capability via software.

Group Disable Wireless Through Software Configuration Group contains 2 rules
[ref] If it is impossible to remove the wireless hardware from the device in question, disable as much of it as possible through software. The following methods can disable software support for wireless networking, but note that these methods do not prevent malicious software or careless users from re-activating the devices.

#### Rule Disable Bluetooth Service [ref]

The `bluetooth` service can be disabled with the following command:

    $ sudo systemctl mask --now bluetooth.service

    $ sudo service bluetooth stop

Rationale: | Disabling the `bluetooth` service prevents the system from attempting connections to Bluetooth devices, which entails some security risk. Nevertheless, variation in this risk decision may be expected due to the utility of Bluetooth connectivity and its limited range.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_bluetooth_disabled

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
cui | 3.1.16
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 | AC-18(a), AC-18(3), CM-7(a), CM-7(b), CM-6(a), MP-7
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
cis | 3.1.3

Remediation Puppet snippet ⇲

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

    include disable_bluetooth

    class disable_bluetooth {
      service {'bluetooth':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_bluetooth_disabled

    - name: Disable Bluetooth Service - Disable service bluetooth
      block:

      - name: Disable Bluetooth Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Bluetooth Service - Ensure bluetooth.service is Masked
        ansible.builtin.systemd:
          name: bluetooth.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("bluetooth.service", multiline=True)

      - name: Unit Socket Exists - bluetooth.socket
        ansible.builtin.command: systemctl -q list-unit-files bluetooth.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Bluetooth Service - Disable Socket bluetooth
        ansible.builtin.systemd:
          name: bluetooth.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("bluetooth.socket", multiline=True)
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_bluetooth_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["bluetooth"]

#### Rule Deactivate Wireless Network Interfaces [ref]

Deactivating wireless network interfaces should prevent normal usage of the wireless capability.
Configure the system to disable all wireless network interfaces with the following command:

    $ sudo nmcli radio all off

Rationale:

The use of wireless networking can introduce many different attack vectors into the organization's network. Common attack vectors such as malicious association and ad hoc networks will allow an attacker to spoof a wireless access point (AP), allowing validated systems to connect to the malicious AP and enabling the attacker to monitor and record network traffic. These malicious APs can also serve to create a man-in-the-middle attack or be used to create a denial of service to valid network resources.

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

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
cui | 3.1.16
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 | AC-18(a), AC-18(3), CM-7(a), CM-7(b), CM-6(a), MP-7
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-1.3.3
os-srg | SRG-OS-000299-GPOS-00117, SRG-OS-000300-GPOS-00118, SRG-OS-000424-GPOS-00188, SRG-OS-000481-GPOS-00481
cis | 3.1.2
ism | 1315, 1319
pcidss4 | 1.3.3, 1.3

Remediation Shell script ⇲

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

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

    if command -v nmcli >/dev/null 2>&1 && systemctl is-active NetworkManager >/dev/null 2>&1; then
        nmcli radio all off
    fi

    if command -v wicked >/dev/null 2>&1 && systemctl is-active wickedd >/dev/null 2>&1; then
      if [ -n "$(find /sys/class/net/*/ -type d -name wireless)" ]; then
        interfaces=$(find /sys/class/net/*/wireless -type d -name wireless | xargs -0 dirname | xargs basename)
        for iface in $interfaces; do
          wicked ifdown $iface
          sed -i 's/STARTMODE=.*/STARTMODE=off/' /etc/sysconfig/network/ifcfg-$iface
        done
      fi
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSS-Req-1.3.3
      - PCI-DSSv4-1.3
      - PCI-DSSv4-1.3.3
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
      - wireless_disable_interfaces

    - name: Service facts
      ansible.builtin.service_facts: null
      when: ( not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman",
        "container"] ) )
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSS-Req-1.3.3
      - PCI-DSSv4-1.3
      - PCI-DSSv4-1.3.3
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
      - wireless_disable_interfaces

    - name: Ensure NetworkManager is installed
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      with_items:
      - NetworkManager
      when: ( not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman",
        "container"] ) )
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSS-Req-1.3.3
      - PCI-DSSv4-1.3
      - PCI-DSSv4-1.3.3
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
      - wireless_disable_interfaces

    - name: NetworkManager Deactivate Wireless Network Interfaces
      ansible.builtin.command: nmcli radio wifi off
      when:
      - ( not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        ) )
      - '''NetworkManager'' in ansible_facts.packages'
      - ansible_facts.services['NetworkManager.service'].state == 'running'
      tags:
      - NIST-800-171-3.1.16
      - NIST-800-53-AC-18(3)
      - NIST-800-53-AC-18(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSS-Req-1.3.3
      - PCI-DSSv4-1.3
      - PCI-DSSv4-1.3.3
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
      - wireless_disable_interfaces

#### Rule Ensure Only One Firewall Service is Active [ref]

The system must have exactly one active firewall service running to avoid conflicts and ensure consistent packet filtering. Only one of the following services should be enabled and active at any time:

- ufw - Uncomplicated Firewall (Ubuntu/Debian default)
- iptables - Classic Linux firewall
- nftables - Next Generation Firewall replacement for iptables

Having zero active firewalls leaves the system vulnerable, while having multiple active firewalls can lead to rule conflicts and security gaps.
Warning: This rule does not come with a remediation. There are specific rules for enabling each firewall which should be enabled instead.

Rationale: | Running multiple firewall services simultaneously can lead to conflicts in rule processing, unpredictable behavior, and potential security gaps. A single firewall service ensures consistent and predictable packet filtering. Having no active firewall service leaves the system exposed to network-based attacks and unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_firewall_single_service_active

References:

cis | 4.1.1

Group File Permissions and Masks Group contains 8 groups and 115 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 12 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 82 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 33 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 Backup 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 is a backup file of `/etc/group`, and as such, it 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_backup_etc_group

References:

nist | AC-6 (1)
pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.4
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_backup_etc_group_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_backup_etc_group_newgroup: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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_backup_etc_group_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns Backup 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 is a backup of `/etc/gshadow`, and as such, it contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_backup_etc_gshadow

References:

nist | AC-6 (1)
pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.8

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_backup_etc_gshadow_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_backup_etc_gshadow_newgroup: '42'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_groupowner_backup_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)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_groupowner_backup_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_backup_etc_gshadow_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_groupowner_backup_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns Backup 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 is a backup file of `/etc/passwd`, and as such, it 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_backup_etc_passwd

References:

nist | AC-6 (1)
pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.2
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_backup_etc_passwd_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_backup_etc_passwd_newgroup: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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_backup_etc_passwd_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns Backup 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 is a backup file of `/etc/shadow`, and as such, it contains the list of local system accounts and password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_backup_etc_shadow

References:

pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.6
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_backup_etc_shadow_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_backup_etc_shadow_newgroup: '42'
      tags:
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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:
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_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_backup_etc_shadow_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSS-Req-8.7
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_backup_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### 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
cis | 7.1.3
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
cis | 7.1.7

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
cis | 7.1.1
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 /etc/security/opasswd File [ref]

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

    $ sudo chgrp root /etc/security/opasswd

Rationale: | The `/etc/security/opasswd` file stores old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_security_opasswd

References:

cis | 7.1.10

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/security/opasswd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/security/opasswd
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_etc_security_opasswd_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_security_opasswd_newgroup: '0'
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/security/opasswd
      ansible.builtin.stat:
        path: /etc/security/opasswd
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/security/opasswd
      ansible.builtin.file:
        path: /etc/security/opasswd
        follow: false
        group: '{{ file_groupowner_etc_security_opasswd_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/security/opasswd.old File [ref]

To properly set the group owner of `/etc/security/opasswd.old`, run the command:

    $ sudo chgrp root /etc/security/opasswd.old

Rationale: | The `/etc/security/opasswd.old` file stores backups of old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_security_opasswd_old

References:

cis | 7.1.10

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/security/opasswd.old" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/security/opasswd.old
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_etc_security_opasswd_old_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_security_opasswd_old_newgroup: '0'
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd_old
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/security/opasswd.old
      ansible.builtin.stat:
        path: /etc/security/opasswd.old
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd_old
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/security/opasswd.old
      ansible.builtin.file:
        path: /etc/security/opasswd.old
        follow: false
        group: '{{ file_groupowner_etc_security_opasswd_old_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_security_opasswd_old
      - 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
cis | 7.1.5
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
cis | 7.1.9

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 Backup group File [ref]

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

    $ sudo chown root /etc/group-

Rationale: | The `/etc/group-` file is a backup file of `/etc/group`, and as such, it 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_backup_etc_group

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.4
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_backup_etc_group_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_backup_etc_group_newown: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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_backup_etc_group_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns Backup gshadow File [ref]

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

    $ sudo chown root /etc/gshadow-

Rationale: | The `/etc/gshadow-` file is a backup of `/etc/gshadow`, and as such, it contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_backup_etc_gshadow

References:

nist | AC-6 (1)
pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.8

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_backup_etc_gshadow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_backup_etc_gshadow_newown: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_owner_backup_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)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_owner_backup_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_backup_etc_gshadow_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7
      - configure_strategy
      - file_owner_backup_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns Backup passwd File [ref]

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

    $ sudo chown root /etc/passwd-

Rationale: | The `/etc/passwd-` file is a backup file of `/etc/passwd`, and as such, it 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_backup_etc_passwd

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.2
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_backup_etc_passwd_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_backup_etc_passwd_newown: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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_backup_etc_passwd_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns Backup shadow File [ref]

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

    $ sudo chown root /etc/shadow-

Rationale: | The `/etc/shadow-` file is a backup file of `/etc/shadow`, and as such, it contains the list of local system accounts and password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_backup_etc_shadow

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.6
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_backup_etc_shadow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_backup_etc_shadow_newown: '0'
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_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_backup_etc_shadow_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_backup_etc_shadow
      - 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
cis | 7.1.3
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
cis | 7.1.7

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
cis | 7.1.1
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 /etc/security/opasswd File [ref]

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

    $ sudo chown root /etc/security/opasswd

Rationale: | The `/etc/security/opasswd` file stores old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_security_opasswd

References:

cis | 7.1.10

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/security/opasswd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/security/opasswd
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_etc_security_opasswd_newown variable if represented by
        uid
      ansible.builtin.set_fact:
        file_owner_etc_security_opasswd_newown: '0'
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/security/opasswd
      ansible.builtin.stat:
        path: /etc/security/opasswd
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/security/opasswd
      ansible.builtin.file:
        path: /etc/security/opasswd
        follow: false
        owner: '{{ file_owner_etc_security_opasswd_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/security/opasswd.old File [ref]

To properly set the owner of `/etc/security/opasswd.old`, run the command:

    $ sudo chown root /etc/security/opasswd.old

Rationale: | The `/etc/security/opasswd.old` file stores backups of old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_security_opasswd_old

References:

cis | 7.1.10

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/security/opasswd.old" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/security/opasswd.old
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_etc_security_opasswd_old_newown variable if represented
        by uid
      ansible.builtin.set_fact:
        file_owner_etc_security_opasswd_old_newown: '0'
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd_old
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/security/opasswd.old
      ansible.builtin.stat:
        path: /etc/security/opasswd.old
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd_old
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/security/opasswd.old
      ansible.builtin.file:
        path: /etc/security/opasswd.old
        follow: false
        owner: '{{ file_owner_etc_security_opasswd_old_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_security_opasswd_old
      - 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
cis | 7.1.5
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
cis | 7.1.9

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 Backup group File [ref]

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

    $ sudo chmod 0644 /etc/group-

Rationale: | The `/etc/group-` file is a backup file of `/etc/group`, and as such, it 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_backup_etc_group

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.4
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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on Backup gshadow File [ref]

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

    $ sudo chmod 0640 /etc/gshadow-

Rationale: | The `/etc/gshadow-` file is a backup of `/etc/gshadow`, and as such, it contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_backup_etc_gshadow

References:

nist | AC-6 (1)
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.8

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)
      - configure_strategy
      - file_permissions_backup_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)
      - configure_strategy
      - file_permissions_backup_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on Backup passwd File [ref]

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

    $ sudo chmod 0644 /etc/passwd-

Rationale: | The `/etc/passwd-` file is a backup file of `/etc/passwd`, and as such, it 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_permissions_backup_etc_passwd

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.2
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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on Backup shadow File [ref]

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

    $ sudo chmod 0640 /etc/shadow-

Rationale: | The `/etc/shadow-` file is a backup file of `/etc/shadow`, and as such, it contains the list of local system accounts and password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_backup_etc_shadow

References:

nist | AC-6 (1)
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
cis | 7.1.6
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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_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:
      - NIST-800-53-AC-6 (1)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_backup_etc_shadow
      - 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
cis | 7.1.3
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
cis | 7.1.7

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
cis | 7.1.1
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 /etc/security/opasswd File [ref]

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

    $ sudo chmod 0600 /etc/security/opasswd

Rationale: | The `/etc/security/opasswd` file stores old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_security_opasswd

References:

cis | 7.1.10

Remediation Shell script ⇲

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

    chmod u-xs,g-xwrs,o-xwrt /etc/security/opasswd

Remediation Ansible snippet ⇲

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

    - name: Test for existence /etc/security/opasswd
      ansible.builtin.stat:
        path: /etc/security/opasswd
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /etc/security/opasswd
      ansible.builtin.file:
        path: /etc/security/opasswd
        mode: u-xs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_security_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/security/opasswd.old File [ref]

To properly set the permissions of `/etc/security/opasswd.old`, run the command:

    $ sudo chmod 0600 /etc/security/opasswd.old

Rationale: | The `/etc/security/opasswd.old` file stores backups of old passwords to prevent password reuse. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_security_opasswd_old

References:

cis | 7.1.10

Remediation Shell script ⇲

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

    chmod u-xs,g-xwrs,o-xwrt /etc/security/opasswd.old

Remediation Ansible snippet ⇲

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

    - name: Test for existence /etc/security/opasswd.old
      ansible.builtin.stat:
        path: /etc/security/opasswd.old
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_etc_security_opasswd_old
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /etc/security/opasswd.old
      ansible.builtin.file:
        path: /etc/security/opasswd.old
        mode: u-xs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_security_opasswd_old
      - 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
cis | 7.1.5
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
cis | 7.1.9

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 Permissions on Files within /var/log Directory Group contains 45 rules
[ref] The `/var/log` directory contains files with logs of error messages in the system and should only be accessed by authorized personnel.

#### Rule Verify Group Who Owns /var/log/auth.log File [ref]

To properly set the group owner of `/var/log/auth.log`, run the command:

    $ sudo chgrp adm /var/log/auth.log

or

    $ sudo chgrp root /var/log/auth.log

Rationale: | The `/var/log/auth.log` file contains records information about user login attempts and authentication processes and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_auth

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

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

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupowner_var_log_auth_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_auth_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupowner_var_log_auth_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - 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: file_groupowner_var_log_auth_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_auth_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_auth_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/auth.log
      ansible.builtin.stat:
        path: /var/log/auth.log
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/auth.log
      ansible.builtin.file:
        path: /var/log/auth.log
        follow: false
        group: '{{ file_groupowner_var_log_auth_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/cloud-init.log* File [ref]

To properly set the group owner of `/var/log/cloud-init.log*`, run the command:

    $ sudo chgrp adm /var/log/cloud-init.log*

or

    $ sudo chgrp root /var/log/cloud-init.log*

Rationale: | The `/var/log/cloud-init.log*` file contains detailed debugging information that helps users troubleshoot cloud-init and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_cloud_init

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "adm and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group root -regextype posix-extended -regex '.*cloud-init\.log.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupowner_var_log_cloud_init_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_cloud_init_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupowner_var_log_cloud_init_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - 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: file_groupowner_var_log_cloud_init_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_cloud_init_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_cloud_init_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*cloud-init\.log.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group
        root -regextype posix-extended -regex ".*cloud-init\.log.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*cloud-init\.log.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_cloud_init_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/*.journal(~) File [ref]

To properly set the group owner of `/var/log/*.journal(~)`, run the command:

    $ sudo chgrp systemd-journal /var/log/*.journal(~)

or

    $ sudo chgrp root /var/log/*.journal(~)

Rationale: | The `/var/log/*.journal(~)` files are system logs managed by the "systemd" service.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_journal

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "systemd-journal and root is not a defined group on the system"
    else
    find -P /var/log/  -type f  ! -group systemd-journal ! -group root -regextype posix-extended -regex '.*\.journal[~]?' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the systemd-journal group is defined
      ansible.builtin.getent:
        database: group
        key: systemd-journal
      ignore_errors: true
      when: file_groupowner_var_log_journal_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_journal_newgroup variable if systemd-journal
        found
      ansible.builtin.set_fact:
        file_groupowner_var_log_journal_newgroup: systemd-journal
      when: ansible_facts.getent_group["systemd-journal"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - 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: file_groupowner_var_log_journal_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_journal_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_journal_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*\.journal[~]? recursively
      ansible.builtin.command: find -P /var/log/  -type f  ! -group systemd-journal !
        -group root -regextype posix-extended -regex ".*\.journal[~]?"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*\.journal[~]?
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_journal_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/lastlog File [ref]

To properly set the group owner of `/var/log/lastlog`, run the command:

    $ sudo chgrp utmp /var/log/lastlog

or

    $ sudo chgrp root /var/log/lastlog

Rationale: | The `/var/log/lastlog` file contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_lastlog

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "utmp and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group utmp ! -group root -regextype posix-extended -regex '.*lastlog(\.[^\/]+)?' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the utmp group is defined
      ansible.builtin.getent:
        database: group
        key: utmp
      ignore_errors: true
      when: file_groupowner_var_log_lastlog_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_lastlog_newgroup variable if utmp found
      ansible.builtin.set_fact:
        file_groupowner_var_log_lastlog_newgroup: utmp
      when: ansible_facts.getent_group["utmp"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - 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: file_groupowner_var_log_lastlog_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_lastlog_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_lastlog_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*lastlog(\.[^\/]+)?
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group utmp !
        -group root -regextype posix-extended -regex ".*lastlog(\.[^\/]+)?"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*lastlog(\.[^\/]+)?
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_lastlog_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/localmessages* File [ref]

To properly set the group owner of `/var/log/localmessages*`, run the command:

    $ sudo chgrp adm /var/log/localmessages*

or

    $ sudo chgrp root /var/log/localmessages*

Rationale: | The `/var/log/localmessages*` file contains log messages from certain boot scripts, including the DHCP client, and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_localmessages

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "adm and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group root -regextype posix-extended -regex '.*localmessages.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupowner_var_log_localmessages_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_localmessages_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupowner_var_log_localmessages_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - 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: file_groupowner_var_log_localmessages_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_localmessages_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_localmessages_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*localmessages.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group
        root -regextype posix-extended -regex ".*localmessages.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*localmessages.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_localmessages_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/messages File [ref]

To properly set the group owner of `/var/log/messages`, run the command:

    $ sudo chgrp root /var/log/messages

Rationale: | The `/var/log/messages` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_messages

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

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" "/var/log/messages" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /var/log/messages
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_var_log_messages_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_var_log_messages_newgroup: '0'
      tags:
      - configure_strategy
      - file_groupowner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/messages
      ansible.builtin.stat:
        path: /var/log/messages
      register: file_exists
      tags:
      - configure_strategy
      - file_groupowner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/messages
      ansible.builtin.file:
        path: /var/log/messages
        follow: false
        group: '{{ file_groupowner_var_log_messages_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/secure File [ref]

To properly set the group owner of `/var/log/secure`, run the command:

    $ sudo chgrp adm /var/log/secure

or

    $ sudo chgrp root /var/log/secure

Rationale: | The `/var/log/secure` file contains information related to authentication and authorization privileges and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_secure

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "adm and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group root -regextype posix-extended -regex '.*secure(.*[-\.].*)?' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupowner_var_log_secure_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_secure_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupowner_var_log_secure_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - 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: file_groupowner_var_log_secure_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_secure_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_secure_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*secure(.*[-\.].*)?
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group
        root -regextype posix-extended -regex ".*secure(.*[-\.].*)?"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*secure(.*[-\.].*)?
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_secure_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/syslog File [ref]

To properly set the group owner of `/var/log/syslog`, run the command:

    $ sudo chgrp adm /var/log/syslog

Rationale: | The `/var/log/syslog` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_syslog

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

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}' 'rsyslog' 2>/dev/null | grep -q '^installed$'; then

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "4 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/var/log/syslog" | grep -E -w -q "4"; then
        chgrp --no-dereference "$newgroup" /var/log/syslog
    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_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_syslog_newgroup variable if represented by
        gid
      ansible.builtin.set_fact:
        file_groupowner_var_log_syslog_newgroup: '4'
      when: '"rsyslog" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/syslog
      ansible.builtin.stat:
        path: /var/log/syslog
      register: file_exists
      when: '"rsyslog" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/syslog
      ansible.builtin.file:
        path: /var/log/syslog
        follow: false
        group: '{{ file_groupowner_var_log_syslog_newgroup }}'
      when:
      - '"rsyslog" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/waagent.log File [ref]

To properly set the group owner of `/var/log/waagent.log`, run the command:

    $ sudo chgrp adm /var/log/waagent.log

or

    $ sudo chgrp root /var/log/waagent.log

Rationale: | The `/var/log/waagent.log` file contains Azure Linux Guest Agent records events that can be used for troubleshooting and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_waagent

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "adm and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group root -regextype posix-extended -regex '.*waagent.log.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupowner_var_log_waagent_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_waagent_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupowner_var_log_waagent_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - 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: file_groupowner_var_log_waagent_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_waagent_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_waagent_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*waagent.log.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group adm ! -group
        root -regextype posix-extended -regex ".*waagent.log.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*waagent.log.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_waagent_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /var/log/(b|w)tmp(.*|-*) File [ref]

To properly set the group owner of `/var/log/(b|w)tmp(.*|-*)`, run the command:

    $ sudo chgrp utmp /var/log/(b|w)tmp(.*|-*)

or

    $ sudo chgrp root /var/log/(b|w)tmp(.*|-*)

Rationale: | The `/var/log/(b|w)tmp(.*|-*)` file contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_var_log_wbtmp

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "utmp and root is not a defined group on the system"
    else
    find -P /var/log/ -maxdepth 1 -type f  ! -group utmp ! -group root -regextype posix-extended -regex '.*(b|w)tmp((\.|-)[^\/]+)?' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the utmp group is defined
      ansible.builtin.getent:
        database: group
        key: utmp
      ignore_errors: true
      when: file_groupowner_var_log_wbtmp_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_wbtmp_newgroup variable if utmp found
      ansible.builtin.set_fact:
        file_groupowner_var_log_wbtmp_newgroup: utmp
      when: ansible_facts.getent_group["utmp"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - 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: file_groupowner_var_log_wbtmp_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_var_log_wbtmp_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_var_log_wbtmp_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*(b|w)tmp((\.|-)[^\/]+)?
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -group utmp !
        -group root -regextype posix-extended -regex ".*(b|w)tmp((\.|-)[^\/]+)?"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/ file(s) matching .*(b|w)tmp((\.|-)[^\/]+)?
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_var_log_wbtmp_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupowner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify ownership of log files [ref]

Any operating system providing too much information in error messages risks compromising the data and security of the structure, and content of error messages needs to be carefully considered by the organization. Organizations carefully consider the structure/content of error messages. The extent to which information systems are able to identify and handle error conditions is guided by organizational policy and operational requirements. Information that could be exploited by adversaries includes, for example, erroneous logon attempts with passwords entered by mistake as the username, mission/business information that can be derived from (if not stated explicitly by) information recorded, and personal information, such as account numbers, social security numbers, and credit card numbers.

Rationale: | The Debian 12 must generate error messages that provide information necessary for corrective actions without revealing information that could be exploited by adversaries.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log

References:

cis | 6.1.4.1

#### Rule Verify Groupownership of Files in /var/log/apt [ref]

To properly set the group owner of `/var/log/apt/*`, run the command:

    $ sudo chgrp adm /var/log/apt/*

or

    $ sudo chgrp root /var/log/apt/*

Rationale: | The `/var/log/apt` directory contains information about APT and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log_apt

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "adm and root is not a defined group on the system"
    else
    find -P /var/log/apt/ -maxdepth 1 -type f  ! -group adm ! -group root -regextype posix-extended -regex '.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the adm group is defined
      ansible.builtin.getent:
        database: group
        key: adm
      ignore_errors: true
      when: file_groupownerships_var_log_apt_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_apt_newgroup variable if adm found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_apt_newgroup: adm
      when: ansible_facts.getent_group["adm"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - 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: file_groupownerships_var_log_apt_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_apt_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_apt_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/apt/ file(s) matching .*
      ansible.builtin.command: find -P /var/log/apt/ -maxdepth 1 -type f  ! -group adm
        ! -group root -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/apt/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownerships_var_log_apt_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Groupownership of Files in /var/log/gdm [ref]

To properly set the group owner of `/var/log/gdm/*`, run the command:

    $ sudo chgrp gdm /var/log/gdm/*

or

    $ sudo chgrp root /var/log/gdm/*

Rationale: | The `/var/log/gdm` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log_gdm

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "gdm and root is not a defined group on the system"
    else
    find -P /var/log/gdm/  -type f  ! -group gdm ! -group root -regextype posix-extended -regex '.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the gdm group is defined
      ansible.builtin.getent:
        database: group
        key: gdm
      ignore_errors: true
      when: file_groupownerships_var_log_gdm_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_gdm_newgroup variable if gdm found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_gdm_newgroup: gdm
      when: ansible_facts.getent_group["gdm"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - 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: file_groupownerships_var_log_gdm_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_gdm_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_gdm_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/gdm/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/gdm/  -type f  ! -group gdm ! -group root
        -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/gdm/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownerships_var_log_gdm_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Groupownership of Files in /var/log/gdm3 [ref]

To properly set the group owner of `/var/log/gdm3/*`, run the command:

    $ sudo chgrp gdm /var/log/gdm3/*

or

    $ sudo chgrp gdm3 /var/log/gdm3/*

or

    $ sudo chgrp root /var/log/gdm3/*

Rationale: | The `/var/log/gdm3` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log_gdm3

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "gdm and gdm3 and root is not a defined group on the system"
    else
    find -P /var/log/gdm3/  -type f  ! -group gdm ! -group gdm3 ! -group root -regextype posix-extended -regex '.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the gdm group is defined
      ansible.builtin.getent:
        database: group
        key: gdm
      ignore_errors: true
      when: file_groupownerships_var_log_gdm3_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_gdm3_newgroup variable if gdm found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_gdm3_newgroup: gdm
      when: ansible_facts.getent_group["gdm"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the gdm3 group is defined
      ansible.builtin.getent:
        database: group
        key: gdm3
      ignore_errors: true
      when: file_groupownerships_var_log_gdm3_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_gdm3_newgroup variable if gdm3 found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_gdm3_newgroup: gdm3
      when: ansible_facts.getent_group["gdm3"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - 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: file_groupownerships_var_log_gdm3_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_gdm3_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_gdm3_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/gdm3/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/gdm3/  -type f  ! -group gdm ! -group
        gdm3 ! -group root -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/gdm3/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownerships_var_log_gdm3_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Groupownership of Files in /var/log/landscape [ref]

To properly set the group owner of `/var/log/landscape/*`, run the command:

    $ sudo chgrp root /var/log/landscape/*

or

    $ sudo chgrp landscape /var/log/landscape/*

Rationale: | The `/var/log/landscape` directory contains information about the landscape-client and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log_landscape

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root and landscape is not a defined group on the system"
    else
    find -P /var/log/landscape/ -maxdepth 1 -type f  ! -group root ! -group landscape -regextype posix-extended -regex '^.*$' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when: file_groupownerships_var_log_landscape_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_landscape_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_landscape_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the landscape group is defined
      ansible.builtin.getent:
        database: group
        key: landscape
      ignore_errors: true
      when: file_groupownerships_var_log_landscape_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_landscape_newgroup variable if landscape
        found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_landscape_newgroup: landscape
      when: ansible_facts.getent_group["landscape"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/landscape/ file(s) matching ^.*$
      ansible.builtin.command: find -P /var/log/landscape/ -maxdepth 1 -type f  ! -group
        root ! -group landscape -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/landscape/ file(s) matching ^.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownerships_var_log_landscape_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Grouponwership of Files in /var/log/sssd [ref]

To properly set the group owner of `/var/log/sssd/*`, run the command:

    $ sudo chgrp sssd /var/log/sssd/*

or

    $ sudo chgrp root /var/log/sssd/*

Rationale: | The `/var/log/sssd` directory contains debug logs for the System Security Services Daemon (SSSD) and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownerships_var_log_sssd

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

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

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "sssd and root is not a defined group on the system"
    else
    find -P /var/log/sssd/  -type f  ! -group sssd ! -group root -regextype posix-extended -regex '.*' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the sssd group is defined
      ansible.builtin.getent:
        database: group
        key: sssd
      ignore_errors: true
      when: file_groupownerships_var_log_sssd_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_sssd_newgroup variable if sssd found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_sssd_newgroup: sssd
      when: ansible_facts.getent_group["sssd"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - 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: file_groupownerships_var_log_sssd_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownerships_var_log_sssd_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupownerships_var_log_sssd_newgroup: root
      when: ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/sssd/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/sssd/  -type f  ! -group sssd ! -group
        root -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/sssd/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownerships_var_log_sssd_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_groupownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/auth.log File [ref]

To properly set the owner of `/var/log/auth.log`, run the command:

    $ sudo chown syslog /var/log/auth.log

or

    $ sudo chown root /var/log/auth.log

Rationale: | The `/var/log/auth.log` file contains records information about user login attempts and authentication processes and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_auth

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "syslog" >/dev/null 2>&1; then
      newown="syslog"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "syslog and root is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/var/log/auth.log" | grep -E -w -q "syslog|root"; then
        chown --no-dereference "$newown" /var/log/auth.log
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the syslog user is defined
      ansible.builtin.getent:
        database: passwd
        key: syslog
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_auth_newown variable if syslog found
      ansible.builtin.set_fact:
        file_owner_var_log_auth_newown: syslog
      when: ansible_facts.getent_passwd["syslog"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_owner_var_log_auth_newown is undefined
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_auth_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_auth_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/auth.log
      ansible.builtin.stat:
        path: /var/log/auth.log
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/auth.log
      ansible.builtin.file:
        path: /var/log/auth.log
        follow: false
        owner: '{{ file_owner_var_log_auth_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/cloud-init.log File [ref]

To properly set the owner of `/var/log/cloud-init.log`, run the command:

    $ sudo chown syslog /var/log/cloud-init.log

or

    $ sudo chown root /var/log/cloud-init.log

Rationale: | The `/var/log/cloud-init.log` file contains detailed debugging information that helps users troubleshoot cloud-init and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_cloud_init

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "syslog" >/dev/null 2>&1; then
      newown="syslog"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "syslog and root is not a defined user on the system"
    else

    find -P /var/log/ -maxdepth 1 -type f  ! -user syslog ! -user root -regextype posix-extended -regex '.*cloud-init\.log.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the syslog user is defined
      ansible.builtin.getent:
        database: passwd
        key: syslog
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_cloud_init_newown variable if syslog found
      ansible.builtin.set_fact:
        file_owner_var_log_cloud_init_newown: syslog
      when: ansible_facts.getent_passwd["syslog"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_owner_var_log_cloud_init_newown is undefined
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_cloud_init_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_cloud_init_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*cloud-init\.log.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user syslog !
        -user root -regextype posix-extended -regex ".*cloud-init\.log.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*cloud-init\.log.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_cloud_init_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_cloud_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/*.journal(~) Files [ref]

To properly set the owner of `/var/log/*.journal(~)`, run the command:

    $ sudo chown root /var/log/*.journal(~)

Rationale: | The `/var/log/*.journal(~)` files are system logs managed by the "systemd" service.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_journal

References:

cis | 6.1.4.1

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

    find -P /var/log/  -type f  ! -user 0 -regextype posix-extended -regex '.*\.journal(~)?$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_var_log_journal_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_var_log_journal_newown: '0'
      tags:
      - configure_strategy
      - file_owner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*\.journal(~)?$ recursively
      ansible.builtin.command: find -P /var/log/  -type f  ! -user 0 -regextype posix-extended
        -regex ".*\.journal(~)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*\.journal(~)?$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_journal_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_journal
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/lastlog File [ref]

To properly set the owner of `/var/log/lastlog`, run the command:

    $ sudo chown root /var/log/lastlog

Rationale: | The `/var/log/lastlog` file contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_lastlog

References:

cis | 6.1.4.1

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

    find -P /var/log/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '.*lastlog(\.[^\/]+)?$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_var_log_lastlog_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_var_log_lastlog_newown: '0'
      tags:
      - configure_strategy
      - file_owner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*lastlog(\.[^\/]+)?$
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex ".*lastlog(\.[^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*lastlog(\.[^\/]+)?$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_lastlog_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/localmessages File [ref]

To properly set the owner of `/var/log/localmessages`, run the command:

    $ sudo chown syslog /var/log/localmessages

or

    $ sudo chown root /var/log/localmessages

Rationale: | The `/var/log/localmessages` file contains log messages from certain boot scripts, including the DHCP client, and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_localmessages

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "syslog" >/dev/null 2>&1; then
      newown="syslog"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "syslog and root is not a defined user on the system"
    else

    find -P /var/log/ -maxdepth 1 -type f  ! -user syslog ! -user root -regextype posix-extended -regex '.*localmessages.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the syslog user is defined
      ansible.builtin.getent:
        database: passwd
        key: syslog
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_localmessages_newown variable if syslog found
      ansible.builtin.set_fact:
        file_owner_var_log_localmessages_newown: syslog
      when: ansible_facts.getent_passwd["syslog"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_owner_var_log_localmessages_newown is undefined
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_localmessages_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_localmessages_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*localmessages.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user syslog !
        -user root -regextype posix-extended -regex ".*localmessages.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*localmessages.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_localmessages_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/messages File [ref]

To properly set the owner of `/var/log/messages`, run the command:

    $ sudo chown root /var/log/messages

Rationale: | The `/var/log/messages` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_messages

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

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" "/var/log/messages" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /var/log/messages
    fi

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_var_log_messages_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_var_log_messages_newown: '0'
      tags:
      - configure_strategy
      - file_owner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/messages
      ansible.builtin.stat:
        path: /var/log/messages
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/messages
      ansible.builtin.file:
        path: /var/log/messages
        follow: false
        owner: '{{ file_owner_var_log_messages_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/secure File [ref]

To properly set the owner of `/var/log/secure`, run the command:

    $ sudo chown syslog /var/log/secure

or

    $ sudo chown root /var/log/secure

Rationale: | The `/var/log/secure` file contains information related to authentication and authorization privileges and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_secure

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "syslog" >/dev/null 2>&1; then
      newown="syslog"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "syslog and root is not a defined user on the system"
    else

    find -P /var/log/ -maxdepth 1 -type f  ! -user syslog ! -user root -regextype posix-extended -regex '.*secure(.*[-\.].*)?' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the syslog user is defined
      ansible.builtin.getent:
        database: passwd
        key: syslog
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_secure_newown variable if syslog found
      ansible.builtin.set_fact:
        file_owner_var_log_secure_newown: syslog
      when: ansible_facts.getent_passwd["syslog"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_owner_var_log_secure_newown is undefined
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_secure_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_secure_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*secure(.*[-\.].*)?
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user syslog !
        -user root -regextype posix-extended -regex ".*secure(.*[-\.].*)?"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*secure(.*[-\.].*)?
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_secure_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/syslog File [ref]

To properly set the owner of `/var/log/syslog`, run the command:

    $ sudo chown root /var/log/syslog

Rationale: | The `/var/log/syslog` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_syslog

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

Remediation Shell script ⇲

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

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

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

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_syslog_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_syslog_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /var/log/syslog
      ansible.builtin.stat:
        path: /var/log/syslog
      register: file_exists
      tags:
      - configure_strategy
      - file_owner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/syslog
      ansible.builtin.file:
        path: /var/log/syslog
        follow: false
        owner: '{{ file_owner_var_log_syslog_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/waagent.log File [ref]

To properly set the owner of `/var/log/waagent.log`, run the command:

    $ sudo chown syslog /var/log/waagent.log

or

    $ sudo chown root /var/log/waagent.log

Rationale: | The `/var/log/waagent.log` file contains Azure Linux Guest Agent records events that can be used for troubleshooting and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_waagent

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "syslog" >/dev/null 2>&1; then
      newown="syslog"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "syslog and root is not a defined user on the system"
    else

    find -P /var/log/ -maxdepth 1 -type f  ! -user syslog ! -user root -regextype posix-extended -regex '.*waagent.log.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the syslog user is defined
      ansible.builtin.getent:
        database: passwd
        key: syslog
      ignore_errors: true
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_waagent_newown variable if syslog found
      ansible.builtin.set_fact:
        file_owner_var_log_waagent_newown: syslog
      when: ansible_facts.getent_passwd["syslog"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_owner_var_log_waagent_newown is undefined
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_var_log_waagent_newown variable if root found
      ansible.builtin.set_fact:
        file_owner_var_log_waagent_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*waagent.log.*
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user syslog !
        -user root -regextype posix-extended -regex ".*waagent.log.*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*waagent.log.*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_waagent_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log/(b|w)tmp(.*|-*) File [ref]

To properly set the owner of `/var/log/(b|w)tmp(.*|-*)`, run the command:

    $ sudo chown root /var/log/(b|w)tmp(.*|-*)

Rationale: | The `/var/log/(b|w)tmp(.*|-*)` file contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_var_log_wbtmp

References:

cis | 6.1.4.1

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

    find -P /var/log/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '.*(b|w)tmp((\.|-)[^\/]+)?$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_var_log_wbtmp_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_var_log_wbtmp_newown: '0'
      tags:
      - configure_strategy
      - file_owner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/ file(s) matching .*(b|w)tmp((\.|-)[^\/]+)?$
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex ".*(b|w)tmp((\.|-)[^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_owner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/ file(s) matching .*(b|w)tmp((\.|-)[^\/]+)?$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_var_log_wbtmp_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_owner_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify ownership of log files [ref]

Any operating system providing too much information in error messages risks compromising the data and security of the structure, and content of error messages needs to be carefully considered by the organization. Organizations carefully consider the structure/content of error messages. The extent to which information systems are able to identify and handle error conditions is guided by organizational policy and operational requirements. Information that could be exploited by adversaries includes, for example, erroneous logon attempts with passwords entered by mistake as the username, mission/business information that can be derived from (if not stated explicitly by) information recorded, and personal information, such as account numbers, social security numbers, and credit card numbers.

Rationale: | The Debian 12 must generate error messages that provide information necessary for corrective actions without revealing information that could be exploited by adversaries.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log

References:

cis | 6.1.4.1

#### Rule Verify Ownership of Files in /var/log/apt [ref]

To properly set the owner of `/var/log/apt/*`, run the command:

    $ sudo chown root /var/log/apt/*

Rationale: | The `/var/log/apt` directory contains information about APT and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log_apt

References:

cis | 6.1.4.1

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

    find -P /var/log/apt/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_ownerships_var_log_apt_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_ownerships_var_log_apt_newown: '0'
      tags:
      - configure_strategy
      - file_ownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/apt/ file(s) matching ^.*$
      ansible.builtin.command: find -P /var/log/apt/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_ownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/apt/ file(s) matching ^.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownerships_var_log_apt_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_ownerships_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership of Files in /var/log/gdm [ref]

To properly set the owner of `/var/log/gdm/*`, run the command:

    $ sudo chown root /var/log/gdm/*

Rationale: | The `/var/log/gdm` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log_gdm

References:

cis | 6.1.4.1

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

    find -P /var/log/gdm/  -type f  ! -user 0 -regextype posix-extended -regex '.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_ownerships_var_log_gdm_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_ownerships_var_log_gdm_newown: '0'
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/gdm/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/gdm/  -type f  ! -user 0 -regextype posix-extended
        -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/gdm/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownerships_var_log_gdm_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership of Files in /var/log/gdm3 [ref]

To properly set the owner of `/var/log/gdm3/*`, run the command:

    $ sudo chown root /var/log/gdm3/*

Rationale: | The `/var/log/gdm3` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log_gdm3

References:

cis | 6.1.4.1

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

    find -P /var/log/gdm3/  -type f  ! -user 0 -regextype posix-extended -regex '.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_ownerships_var_log_gdm3_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_ownerships_var_log_gdm3_newown: '0'
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/gdm3/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/gdm3/  -type f  ! -user 0 -regextype posix-extended
        -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/gdm3/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownerships_var_log_gdm3_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_ownerships_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership of Files in /var/log/landscape [ref]

To properly set the owner of `/var/log/landscape/*`, run the command:

    $ sudo chown root /var/log/landscape/*

or

    $ sudo chown landscape /var/log/landscape/*

Rationale: | The `/var/log/landscape` directory contains information about the landscape-client and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log_landscape

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "root" >/dev/null 2>&1; then
      newown="root"
    elif id "landscape" >/dev/null 2>&1; then
      newown="landscape"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "root and landscape is not a defined user on the system"
    else

    find -P /var/log/landscape/ -maxdepth 1 -type f  ! -user root ! -user landscape -regextype posix-extended -regex '^.*$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownerships_var_log_landscape_newown variable if root found
      ansible.builtin.set_fact:
        file_ownerships_var_log_landscape_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the landscape user is defined
      ansible.builtin.getent:
        database: passwd
        key: landscape
      ignore_errors: true
      when: file_ownerships_var_log_landscape_newown is undefined
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownerships_var_log_landscape_newown variable if landscape found
      ansible.builtin.set_fact:
        file_ownerships_var_log_landscape_newown: landscape
      when: ansible_facts.getent_passwd["landscape"] is defined
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/landscape/ file(s) matching ^.*$
      ansible.builtin.command: find -P /var/log/landscape/ -maxdepth 1 -type f  ! -user
        root ! -user landscape -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/landscape/ file(s) matching ^.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownerships_var_log_landscape_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_ownerships_var_log_landscape
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership of Files in /var/log/sssd [ref]

To properly set the owner of `/var/log/sssd/*`, run the command:

    $ sudo chown sssd /var/log/sssd/*

or

    $ sudo chown root /var/log/sssd/*

Rationale: | The `/var/log/sssd` directory contains debug logs for the System Security Services Daemon (SSSD) and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownerships_var_log_sssd

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    newown=""
    if id "sssd" >/dev/null 2>&1; then
      newown="sssd"
    elif id "root" >/dev/null 2>&1; then
      newown="root"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "sssd and root is not a defined user on the system"
    else

    find -P /var/log/sssd/  -type f  ! -user sssd ! -user root -regextype posix-extended -regex '.*' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Check that the sssd user is defined
      ansible.builtin.getent:
        database: passwd
        key: sssd
      ignore_errors: true
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownerships_var_log_sssd_newown variable if sssd found
      ansible.builtin.set_fact:
        file_ownerships_var_log_sssd_newown: sssd
      when: ansible_facts.getent_passwd["sssd"] is defined
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root user is defined
      ansible.builtin.getent:
        database: passwd
        key: root
      ignore_errors: true
      when: file_ownerships_var_log_sssd_newown is undefined
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownerships_var_log_sssd_newown variable if root found
      ansible.builtin.set_fact:
        file_ownerships_var_log_sssd_newown: root
      when: ansible_facts.getent_passwd["root"] is defined
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /var/log/sssd/ file(s) matching .* recursively
      ansible.builtin.command: find -P /var/log/sssd/  -type f  ! -user sssd ! -user root
        -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /var/log/sssd/ file(s) matching .*
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownerships_var_log_sssd_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_ownerships_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on files in the /var/log/apt/.* directory [ref]

To properly set the permissions of `/var/log/apt/.*`, run the command:

    $ sudo chmod 0644 /var/log/apt/.*

Rationale: | The `/var/log/apt` directory contains information about APT and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_apt

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/apt/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type f -regextype posix-extended -regex '^.*$' -exec chmod u-xs,g-xws,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/apt/ file(s)
      ansible.builtin.command: find -P /var/log/apt/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type
        f -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/apt/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_apt
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/auth.log File [ref]

To properly set the permissions of `/var/log/auth.log`, run the command:

    $ sudo chmod 0640 /var/log/auth.log

Rationale: | The `/var/log/auth.log` file contains records information about user login attempts and authentication processes and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_auth

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwrt /var/log/auth.log

Remediation Ansible snippet ⇲

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

    - name: Test for existence /var/log/auth.log
      ansible.builtin.stat:
        path: /var/log/auth.log
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /var/log/auth.log
      ansible.builtin.file:
        path: /var/log/auth.log
        mode: u-xs,g-xws,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_var_log_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/cloud-init.log(.*) Files [ref]

To properly set the permissions of `/var/log/cloud-init.log`, run the command:

    $ sudo chmod 0644 /var/log/cloud-init.log

Rationale: | The `/var/log/cloud-init.log` file contains detailed debugging information that helps users troubleshoot cloud-init and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_cloud-init

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type f -regextype posix-extended -regex '.*cloud-init.log([^\/]+)?$' -exec chmod u-xs,g-xws,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type
        f -regextype posix-extended -regex ".*cloud-init.log([^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_cloud-init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_cloud-init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions of Files in /var/log/gdm [ref]

To properly set the permissions of `/var/log/gdm/*`, run the command:

    $ sudo chmod 0660 /var/log/gdm/*

Rationale: | The `/var/log/gdm` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_gdm

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/gdm/  -perm /u+xs,g+xs,o+xwrt  -type f -regextype posix-extended -regex '.*' -exec chmod u-xs,g-xs,o-xwrt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/gdm/ file(s) recursively
      ansible.builtin.command: find -P /var/log/gdm/  -perm /u+xs,g+xs,o+xwrt  -type f
        -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/gdm/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xs,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_gdm
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions of Files in /var/log/gdm3 [ref]

To properly set the permissions of `/var/log/gdm3/*`, run the command:

    $ sudo chmod 0660 /var/log/gdm3/*

Rationale: | The `/var/log/gdm3` directory contains information about the GDM daemon and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_gdm3

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/gdm3/  -perm /u+xs,g+xs,o+xwrt  -type f -regextype posix-extended -regex '.*' -exec chmod u-xs,g-xs,o-xwrt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/gdm3/ file(s) recursively
      ansible.builtin.command: find -P /var/log/gdm3/  -perm /u+xs,g+xs,o+xwrt  -type
        f -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/gdm3/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xs,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_gdm3
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/lastlog(.*) Files [ref]

To properly set the permissions of `/var/log/lastlog`, run the command:

    $ sudo chmod 0664 /var/log/lastlog

Rationale: | The `/var/log/lastlog` file contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_lastlog

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xs,o+xwt  -type f -regextype posix-extended -regex '.*lastlog(\.[^\/]+)?$' -exec chmod u-xs,g-xs,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xs,o+xwt  -type
        f -regextype posix-extended -regex ".*lastlog(\.[^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xs,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/localmessages(.*) Files [ref]

To properly set the permissions of `/var/log/localmessages`, run the command:

    $ sudo chmod 0644 /var/log/localmessages

Rationale: | The `/var/log/localmessages` file contains log messages from certain boot scripts, including the DHCP client, and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_localmessages

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type f -regextype posix-extended -regex '.*localmessages([^\/]+)?$' -exec chmod u-xs,g-xws,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type
        f -regextype posix-extended -regex ".*localmessages([^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_localmessages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/messages File [ref]

To properly set the permissions of `/var/log/messages`, run the command:

    $ sudo chmod 0600 /var/log/messages

Rationale: | The `/var/log/messages` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_messages

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

Remediation Shell script ⇲

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

    chmod u-xs,g-xwrs,o-xwrt /var/log/messages

Remediation Ansible snippet ⇲

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

    - name: Test for existence /var/log/messages
      ansible.builtin.stat:
        path: /var/log/messages
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /var/log/messages
      ansible.builtin.file:
        path: /var/log/messages
        mode: u-xs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/secure File [ref]

To properly set the permissions of `/var/log/secure`, run the command:

    $ sudo chmod 0640 /var/log/secure

Rationale: | The `/var/log/secure` file contains information related to authentication and authorization privileges and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_secure

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwrt /var/log/secure

Remediation Ansible snippet ⇲

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

    - name: Test for existence /var/log/secure
      ansible.builtin.stat:
        path: /var/log/secure
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /var/log/secure
      ansible.builtin.file:
        path: /var/log/secure
        mode: u-xs,g-xws,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_var_log_secure
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions of Files in /var/log/sssd [ref]

To properly set the permissions of `/var/log/sssd/*`, run the command:

    $ sudo chmod 0660 /var/log/sssd/*

Rationale: | The `/var/log/sssd` directory contains debug logs for the System Security Services Daemon (SSSD) and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_sssd

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/sssd/ -maxdepth 1 -perm /u+xs,g+xs,o+xwrt  -type f -regextype posix-extended -regex '.*' -exec chmod u-xs,g-xs,o-xwrt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/sssd/ file(s)
      ansible.builtin.command: find -P /var/log/sssd/ -maxdepth 1 -perm /u+xs,g+xs,o+xwrt  -type
        f -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/sssd/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xs,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_sssd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/syslog File [ref]

To properly set the permissions of `/var/log/syslog`, run the command:

    $ sudo chmod 0640 /var/log/syslog

Rationale: | The `/var/log/syslog` file contains logs of error messages in the system and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_syslog

References:

os-srg | SRG-OS-000206-GPOS-00084
cis | 6.1.4.1

Remediation Shell script ⇲

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

    chmod u-xs,g-xws,o-xwrt /var/log/syslog

Remediation Ansible snippet ⇲

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

    - name: Test for existence /var/log/syslog
      ansible.builtin.stat:
        path: /var/log/syslog
      register: file_exists
      tags:
      - configure_strategy
      - file_permissions_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /var/log/syslog
      ansible.builtin.file:
        path: /var/log/syslog
        mode: u-xs,g-xws,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_var_log_syslog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/waagent.log(.*) Files [ref]

To properly set the permissions of `/var/log/waagent.log`, run the command:

    $ sudo chmod 0644 /var/log/waagent.log

Rationale: | The `/var/log/waagent.log` file contains Azure Linux Guest Agent records events that can be used for troubleshooting and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_waagent

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type f -regextype posix-extended -regex '.*waagent.log([^\/]+)?$' -exec chmod u-xs,g-xws,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type
        f -regextype posix-extended -regex ".*waagent.log([^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_waagent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log/wtmp(.*) Files [ref]

To properly set the permissions of `/var/log/(b|w)tmp(.*|-*)`, run the command:

    $ sudo chmod 0664 /var/log/(b|w)tmp(.*|-*)

Rationale: | The `/var/log/(b|w)tmp(.*|-*)` files contains logs of reports the most recent login of all users and should only be accessed by authorized personnel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_wbtmp

References:

cis | 6.1.4.1

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xs,o+xwt  -type f -regextype posix-extended -regex '.*(b|w)tmp((\.|-)[^\/]+)?$' -exec chmod u-xs,g-xs,o-xwt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xs,o+xwt  -type
        f -regextype posix-extended -regex ".*(b|w)tmp((\.|-)[^\/]+)?$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - configure_strategy
      - file_permissions_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xs,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - configure_strategy
      - file_permissions_var_log_wbtmp
      - low_complexity
      - low_disruption
      - medium_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
cis | 7.1.11
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
cis | 7.1.12
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
cis | 7.1.12
pcidss4 | 2.2.6, 2.2

#### Rule Verify permissions of log files [ref]

Any operating system providing too much information in error messages risks compromising the data and security of the structure, and content of error messages needs to be carefully considered by the organization. Organizations carefully consider the structure/content of error messages. The extent to which information systems are able to identify and handle error conditions is guided by organizational policy and operational requirements. Information that could be exploited by adversaries includes, for example, erroneous logon attempts with passwords entered by mistake as the username, mission/business information that can be derived from (if not stated explicitly by) information recorded, and personal information, such as account numbers, social security numbers, and credit card numbers.

Rationale: | The Debian 12 must generate error messages that provide information necessary for corrective actions without revealing information that could be exploited by adversaries.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_permissions_local_var_log

References:

nist | SI-11(a), SI-11(b), SI-11.1(iii)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000205-GPOS-00083
cis | 6.1.4.1
pcidss4 | 10.3.1, 10.3

Remediation Shell script ⇲

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

    find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwrt  -type f -regextype posix-extended -regex '.*' -exec chmod u-xs,g-xws,o-xwrt {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /var/log/ file(s)
      ansible.builtin.command: find -P /var/log/ -maxdepth 1 -perm /u+xs,g+xws,o+xwrt  -type
        f -regextype posix-extended -regex ".*"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - NIST-800-53-SI-11.1(iii)
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - permissions_local_var_log

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - NIST-800-53-SI-11.1(iii)
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - permissions_local_var_log

Group Restrict Dynamic Mounting and Unmounting of Filesystems Group contains 10 rules

[ref] Linux includes a number of facilities for the automated addition and removal of filesystems on a running system. These facilities may be necessary in many environments, but this capability also carries some risk -- whether direct risk from allowing users to introduce arbitrary filesystems, or risk that software flaws in the automated mount facility itself could allow an attacker to compromise the system.
This command can be used to list the types of filesystems that are available to the currently executing kernel:

    $ find /lib/modules/`uname -r`/kernel/fs -type f -name '*.ko'

If these filesystems are not required then they can be explicitly disabled in a configuratio file in `/etc/modprobe.d`.

#### Rule Remove autofs Package [ref]

autofs allows automatic mounting of devices, typically including CD/DVDs and USB drives. The `autofs` package can be removed with the following command:

     $ apt-get remove autofs

Rationale: | With automounting enabled anyone with physical access could attach a USB drive or disc and have its contents available in the filesystem even if they lacked permissions to mount it themselves.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_autofs_removed

References:

cis | 2.1.1

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove autofs
    # from the system, and may remove any packages
    # that depend on autofs. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "autofs"

Remediation Puppet snippet ⇲

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

    include remove_autofs

    class remove_autofs {
      package { 'autofs':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Remove autofs Package: Ensure autofs is removed'
      ansible.builtin.package:
        name: autofs
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_autofs_removed

#### Rule Disable the Automounter [ref]

The `autofs` daemon mounts and unmounts filesystems, such as user home directories shared via NFS, on demand. In addition, autofs can be used to handle removable media, and the default configuration provides the cdrom device as `/misc/cd`. However, this method of providing access to removable media is not common, so autofs can almost always be disabled if NFS is not in use. Even if NFS is required, it may be possible to configure filesystem mounts statically by editing `/etc/fstab` rather than relying on the automounter.
The `autofs` service can be disabled with the following command:

    $ sudo systemctl mask --now autofs.service

Rationale: | Disabling the automounter permits the administrator to statically control filesystem mounting through `/etc/fstab`. Additionally, automatically mounting filesystems permits easy introduction of unknown devices, thereby facilitating malicious activity.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_autofs_disabled

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | APO13.01, DSS01.04, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.4.6
hipaa | 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.310(d)(1), 164.310(d)(2), 164.312(a)(1), 164.312(a)(2)(iv), 164.312(b)
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.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.6
iso27001-2013 | A.11.2.6, A.13.1.1, A.13.2.1, A.18.1.4, A.6.2.1, A.6.2.2, 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-7(a), CM-7(b), CM-6(a), MP-7
nist-csf | PR.AC-1, PR.AC-3, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227
cis | 2.1.1

Remediation Puppet snippet ⇲

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

    include disable_autofs

    class disable_autofs {
      service {'autofs':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_autofs_disabled

    - name: Disable the Automounter - Disable service autofs
      block:

      - name: Disable the Automounter - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable the Automounter - Ensure autofs.service is Masked
        ansible.builtin.systemd:
          name: autofs.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("autofs.service", multiline=True)

      - name: Unit Socket Exists - autofs.socket
        ansible.builtin.command: systemctl -q list-unit-files autofs.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable the Automounter - Disable Socket autofs
        ansible.builtin.systemd:
          name: autofs.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("autofs.socket", multiline=True)
      tags:
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_autofs_disabled
      - special_service_block
      when: ( "autofs" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["autofs"]

#### Rule Disable Mounting of cramfs [ref]

To configure the system to prevent the `cramfs` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/cramfs.conf`:

    install cramfs /bin/false

This entry will cause a non-zero return value during a `cramfs` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install cramfs /bin/true

This effectively prevents usage of this uncommon filesystem. The `cramfs` filesystem type is a compressed read-only Linux filesystem embedded in small footprint systems. A `cramfs` image can be used without having to first decompress the image.

Rationale: | Removing support for unneeded filesystem types reduces the local attack surface of the server.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_cramfs_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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-000095-GPOS-00049
cis | 1.1.1.1

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

    if LC_ALL=C grep -q -m 1 "^install cramfs" /etc/modprobe.d/cramfs.conf ; then

    	sed -i 's#^install cramfs.*#install cramfs /bin/false#g' /etc/modprobe.d/cramfs.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/cramfs.conf
    	echo "install cramfs /bin/false" >> /etc/modprobe.d/cramfs.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist cramfs$" /etc/modprobe.d/cramfs.conf ; then
    	echo "blacklist cramfs" >> /etc/modprobe.d/cramfs.conf
    fi

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

#### Rule Disable Mounting of freevxfs [ref]

To configure the system to prevent the `freevxfs` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/freevxfs.conf`:

    install freevxfs /bin/false

This entry will cause a non-zero return value during a `freevxfs` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install freevxfs /bin/true

This effectively prevents usage of this uncommon filesystem.

Rationale: | Linux kernel modules which implement filesystems that are not needed by the local system should be disabled.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_freevxfs_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
cis | 1.1.1.2

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

    if LC_ALL=C grep -q -m 1 "^install freevxfs" /etc/modprobe.d/freevxfs.conf ; then

    	sed -i 's#^install freevxfs.*#install freevxfs /bin/false#g' /etc/modprobe.d/freevxfs.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/freevxfs.conf
    	echo "install freevxfs /bin/false" >> /etc/modprobe.d/freevxfs.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist freevxfs$" /etc/modprobe.d/freevxfs.conf ; then
    	echo "blacklist freevxfs" >> /etc/modprobe.d/freevxfs.conf
    fi

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

#### Rule Disable Mounting of hfs [ref]

To configure the system to prevent the `hfs` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/hfs.conf`:

    install hfs /bin/false

This entry will cause a non-zero return value during a `hfs` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install hfs /bin/true

This effectively prevents usage of this uncommon filesystem.

Rationale: | Linux kernel modules which implement filesystems that are not needed by the local system should be disabled.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_hfs_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
cis | 1.1.1.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

    if LC_ALL=C grep -q -m 1 "^install hfs" /etc/modprobe.d/hfs.conf ; then

    	sed -i 's#^install hfs.*#install hfs /bin/false#g' /etc/modprobe.d/hfs.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/hfs.conf
    	echo "install hfs /bin/false" >> /etc/modprobe.d/hfs.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist hfs$" /etc/modprobe.d/hfs.conf ; then
    	echo "blacklist hfs" >> /etc/modprobe.d/hfs.conf
    fi

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

#### Rule Disable Mounting of hfsplus [ref]

To configure the system to prevent the `hfsplus` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/hfsplus.conf`:

    install hfsplus /bin/false

This entry will cause a non-zero return value during a `hfsplus` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install hfsplus /bin/true

This effectively prevents usage of this uncommon filesystem.

Rationale: | Linux kernel modules which implement filesystems that are not needed by the local system should be disabled.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_hfsplus_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
cis | 1.1.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

    if LC_ALL=C grep -q -m 1 "^install hfsplus" /etc/modprobe.d/hfsplus.conf ; then

    	sed -i 's#^install hfsplus.*#install hfsplus /bin/false#g' /etc/modprobe.d/hfsplus.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/hfsplus.conf
    	echo "install hfsplus /bin/false" >> /etc/modprobe.d/hfsplus.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist hfsplus$" /etc/modprobe.d/hfsplus.conf ; then
    	echo "blacklist hfsplus" >> /etc/modprobe.d/hfsplus.conf
    fi

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

#### Rule Disable Mounting of jffs2 [ref]

To configure the system to prevent the `jffs2` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/jffs2.conf`:

    install jffs2 /bin/false

This entry will cause a non-zero return value during a `jffs2` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install jffs2 /bin/true

This effectively prevents usage of this uncommon filesystem.

Rationale: | Linux kernel modules which implement filesystems that are not needed by the local system should be disabled.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_jffs2_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
cis | 1.1.1.5

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

    if LC_ALL=C grep -q -m 1 "^install jffs2" /etc/modprobe.d/jffs2.conf ; then

    	sed -i 's#^install jffs2.*#install jffs2 /bin/false#g' /etc/modprobe.d/jffs2.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/jffs2.conf
    	echo "install jffs2 /bin/false" >> /etc/modprobe.d/jffs2.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist jffs2$" /etc/modprobe.d/jffs2.conf ; then
    	echo "blacklist jffs2" >> /etc/modprobe.d/jffs2.conf
    fi

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

#### Rule Ensure overlayfs kernel module is not available [ref]

To configure the system to prevent the `overlayfs` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/overlayfs.conf`:

    install overlayfs /bin/false

This entry will cause a non-zero return value during a `overlayfs` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install overlayfs /bin/true

overlayfs is a Linux filesystem that layers multiple filesystems to create a single unified view which allows a user to "merge" several mount points into a unified filesystem.

Rationale: | The overlayfs has known CVE's. Disabling the overlayfs reduces the local attack surface by removing support for unnecessary filesystem types and mitigates potential risks associated with unauthorized execution of setuid files, enhancing the overall system security.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_overlayfs_disabled

References:

cis | 1.1.1.6

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

    if LC_ALL=C grep -q -m 1 "^install overlayfs" /etc/modprobe.d/overlayfs.conf ; then

    	sed -i 's#^install overlayfs.*#install overlayfs /bin/false#g' /etc/modprobe.d/overlayfs.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/overlayfs.conf
    	echo "install overlayfs /bin/false" >> /etc/modprobe.d/overlayfs.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist overlayfs$" /etc/modprobe.d/overlayfs.conf ; then
    	echo "blacklist overlayfs" >> /etc/modprobe.d/overlayfs.conf
    fi

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

#### Rule Disable Mounting of udf [ref]

To configure the system to prevent the `udf` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/udf.conf`:

    install udf /bin/false

This entry will cause a non-zero return value during a `udf` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install udf /bin/true

This effectively prevents usage of this uncommon filesystem. The `udf` filesystem type is the universal disk format used to implement the ISO/IEC 13346 and ECMA-167 specifications. This is an open vendor filesystem type for data storage on a broad range of media. This filesystem type is necessary to support writing DVDs and newer optical disc formats.

Rationale: | Removing support for unneeded filesystem types reduces the local attack surface of the system.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_udf_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.4.6
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
cis | 1.1.1.8

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

    if LC_ALL=C grep -q -m 1 "^install udf" /etc/modprobe.d/udf.conf ; then

    	sed -i 's#^install udf.*#install udf /bin/false#g' /etc/modprobe.d/udf.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/udf.conf
    	echo "install udf /bin/false" >> /etc/modprobe.d/udf.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist udf$" /etc/modprobe.d/udf.conf ; then
    	echo "blacklist udf" >> /etc/modprobe.d/udf.conf
    fi

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

#### Rule Disable Modprobe Loading of USB Storage Driver [ref]

To prevent USB storage devices from being used, configure the kernel module loading system to prevent automatic loading of the USB storage driver. To configure the system to prevent the `usb-storage` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/usb-storage.conf`:

    install usb-storage /bin/false

This entry will cause a non-zero return value during a `usb-storage` module installation and additionally convey the meaning of the entry to the user in form of an error message. If you would like to omit a non-zero return value and an error message, you may want to add a different line instead (both `/bin/true` and `/bin/false` are allowed by OVAL and will be accepted by the scan):

    install usb-storage /bin/true

This will prevent the `modprobe` program from loading the `usb-storage` module, but will not prevent an administrator (or another program) from using the `insmod` program to load the module manually.

Rationale: | USB storage devices such as thumb drives can be used to introduce malicious software.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_usb-storage_disabled

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | APO13.01, DSS01.04, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.1.21
hipaa | 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.310(d)(1), 164.310(d)(2), 164.312(a)(1), 164.312(a)(2)(iv), 164.312(b)
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.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.6
iso27001-2013 | A.11.2.6, A.13.1.1, A.13.2.1, A.18.1.4, A.6.2.1, A.6.2.2, 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-7(a), CM-7(b), CM-6(a), MP-7
nist-csf | PR.AC-1, PR.AC-3, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000141-CTR-000315
cis | 1.1.1.9
pcidss4 | 3.4.2, 3.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

    if LC_ALL=C grep -q -m 1 "^install usb-storage" /etc/modprobe.d/usb-storage.conf ; then

    	sed -i 's#^install usb-storage.*#install usb-storage /bin/false#g' /etc/modprobe.d/usb-storage.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/usb-storage.conf
    	echo "install usb-storage /bin/false" >> /etc/modprobe.d/usb-storage.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist usb-storage$" /etc/modprobe.d/usb-storage.conf ; then
    	echo "blacklist usb-storage" >> /etc/modprobe.d/usb-storage.conf
    fi

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

Group Restrict Partition Mount Options Group contains 19 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 nodev Option to /dev/shm [ref]

The `nodev` mount option can be used to prevent creation of device files in `/dev/shm`. Legitimate character and block devices should not exist within temporary directories like `/dev/shm`. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/dev/shm`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_dev_shm_nodev

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
cis | 1.1.2.2.2
ism | 1409

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 {

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /dev/shm)"

        # 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|nodev)(,|$)//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="tmpfs"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo "tmpfs /dev/shm tmpfs defaults,${previous_mount_opts}nodev 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 "nodev"; 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,nodev|" /etc/fstab
        fi

        if mkdir -p "/dev/shm"; then
            if mountpoint -q "/dev/shm"; then
                mount -o remount --target "/dev/shm"
            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_dev_shm_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /dev/shm: Check information associated to mountpoint'
      command: findmnt  '/dev/shm'
      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_dev_shm_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /dev/shm: 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_dev_shm_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /dev/shm: If /dev/shm not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /dev/shm
        - tmpfs
        - tmpfs
        - 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"] ) )
      - ("" | 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_dev_shm_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /dev/shm: Make sure nodev option is part of the to /dev/shm
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" 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_dev_shm_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /dev/shm: Ensure /dev/shm is mounted with nodev option'
      mount:
        path: /dev/shm
        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 ("" |
        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_dev_shm_nodev
      - no_reboot_needed

#### Rule Add noexec Option to /dev/shm [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/dev/shm`. It can be dangerous to allow the execution of binaries from world-writable temporary storage directories such as `/dev/shm`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/dev/shm`.
Rationale: | Allowing users to execute binaries from world-writable directories such as `/dev/shm` can expose the system to potential compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_dev_shm_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
cis | 1.1.2.2.4
ism | 1409

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 {

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /dev/shm)"

        # 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="tmpfs"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo "tmpfs /dev/shm tmpfs 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 "/dev/shm"; then
            if mountpoint -q "/dev/shm"; then
                mount -o remount --target "/dev/shm"
            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_dev_shm_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /dev/shm: Check information associated to mountpoint'
      command: findmnt  '/dev/shm'
      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_dev_shm_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /dev/shm: 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_dev_shm_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /dev/shm: If /dev/shm not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /dev/shm
        - tmpfs
        - tmpfs
        - 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"] ) )
      - ("" | 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_dev_shm_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /dev/shm: Make sure noexec option is part of the to
        /dev/shm 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-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_dev_shm_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /dev/shm: Ensure /dev/shm is mounted with noexec option'
      mount:
        path: /dev/shm
        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 ("" |
        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_dev_shm_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /dev/shm [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/dev/shm`. 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 `/dev/shm`.
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_dev_shm_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
cis | 1.1.2.2.3
ism | 1409

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 {

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /dev/shm)"

        # 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="tmpfs"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo "tmpfs /dev/shm tmpfs 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 "/dev/shm"; then
            if mountpoint -q "/dev/shm"; then
                mount -o remount --target "/dev/shm"
            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_dev_shm_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /dev/shm: Check information associated to mountpoint'
      command: findmnt  '/dev/shm'
      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_dev_shm_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /dev/shm: 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_dev_shm_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /dev/shm: If /dev/shm not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /dev/shm
        - tmpfs
        - tmpfs
        - 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"] ) )
      - ("" | 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_dev_shm_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /dev/shm: Make sure nosuid option is part of the to
        /dev/shm 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_dev_shm_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /dev/shm: Ensure /dev/shm is mounted with nosuid option'
      mount:
        path: /dev/shm
        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 ("" |
        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_dev_shm_nosuid
      - no_reboot_needed

#### Rule Add nodev Option to /home [ref]

The `nodev` mount option can be used to prevent device files from being created in `/home`. 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 `/home`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_home_nodev

References:

os-srg | SRG-OS-000368-GPOS-00154
cis | 1.1.2.3.2

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|nodev)(,|$)//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}nodev 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 "nodev"; 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,nodev|" /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:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

    - name: 'Add nodev 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:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

    - name: 'Add nodev 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:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

    - name: 'Add nodev 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:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

    - name: 'Add nodev Option to /home: Make sure nodev option is part of the to /home
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

    - name: 'Add nodev Option to /home: Ensure /home is mounted with nodev 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:
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

#### 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
cis | 1.1.2.3.3

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 /tmp [ref]

The `nodev` mount option can be used to prevent device files from being created in `/tmp`. Legitimate character and block devices should not exist within temporary directories like `/tmp`. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/tmp`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_tmp_nodev

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
cis | 1.1.2.1.2

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|nodev)(,|$)//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}nodev 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 "nodev"; 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,nodev|" /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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /tmp: Make sure nodev option is part of the to /tmp options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /tmp: Ensure /tmp is mounted with nodev 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_nodev
      - 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
cis | 1.1.2.1.4

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|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 " /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 "/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_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
cis | 1.1.2.1.3

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 nodev Option to /var/log/audit [ref]

The `nodev` mount option can be used to prevent device files from being created in `/var/log/audit`. 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 `/var/log/audit`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_log_audit_nodev

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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000368-GPOS-00154
cis | 1.1.2.7.2

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/audit" > /dev/null || findmnt --fstab "/var/log/audit" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/log/audit 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/audit")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/log/audit' 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/audit in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/log/audit)"

        # 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|nodev)(,|$)//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/audit  defaults,${previous_mount_opts}nodev 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 "nodev"; 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,nodev|" /etc/fstab
        fi

        if mkdir -p "/var/log/audit"; then
            if mountpoint -q "/var/log/audit"; then
                mount -o remount --target "/var/log/audit"
            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_audit_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log/audit: Check information associated to mountpoint'
      command: findmnt --fstab '/var/log/audit'
      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/audit" 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_audit_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log/audit: 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/audit" 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_audit_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log/audit: If /var/log/audit 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/audit
        - ''
        - ''
        - 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/audit" 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_audit_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log/audit: Make sure nodev option is part of the
        to /var/log/audit options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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/audit" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nodev" 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_audit_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log/audit: Ensure /var/log/audit is mounted with
        nodev option'
      mount:
        path: /var/log/audit
        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/audit" 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_audit_nodev
      - no_reboot_needed

#### Rule Add noexec Option to /var/log/audit [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/var/log/audit`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/log/audit`.
Rationale: | Allowing users to execute binaries from directories containing audit log files such as `/var/log/audit` 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_audit_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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000368-GPOS-00154
cis | 1.1.2.7.4

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/audit" > /dev/null || findmnt --fstab "/var/log/audit" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/log/audit 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/audit")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/log/audit' 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/audit in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/log/audit)"

        # 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/audit  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/audit"; then
            if mountpoint -q "/var/log/audit"; then
                mount -o remount --target "/var/log/audit"
            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_audit_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log/audit: Check information associated to mountpoint'
      command: findmnt --fstab '/var/log/audit'
      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/audit" 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_audit_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log/audit: 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/audit" 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_audit_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log/audit: If /var/log/audit 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/audit
        - ''
        - ''
        - 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/audit" 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_audit_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log/audit: Make sure noexec option is part of the
        to /var/log/audit 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/audit" 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_audit_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log/audit: Ensure /var/log/audit is mounted with
        noexec option'
      mount:
        path: /var/log/audit
        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/audit" 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_audit_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /var/log/audit [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/var/log/audit`. The SUID and SGID permissions should not be required in directories containing audit log files. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/log/audit`.
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 audit log files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_log_audit_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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000368-GPOS-00154
cis | 1.1.2.7.3

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/audit" > /dev/null || findmnt --fstab "/var/log/audit" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/log/audit 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/audit")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/log/audit' 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/audit in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/log/audit)"

        # 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/audit  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/audit"; then
            if mountpoint -q "/var/log/audit"; then
                mount -o remount --target "/var/log/audit"
            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_audit_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log/audit: Check information associated to mountpoint'
      command: findmnt --fstab '/var/log/audit'
      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/audit" 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_audit_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log/audit: 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/audit" 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_audit_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log/audit: If /var/log/audit 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/audit
        - ''
        - ''
        - 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/audit" 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_audit_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log/audit: Make sure nosuid option is part of the
        to /var/log/audit 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/audit" 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_audit_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log/audit: Ensure /var/log/audit is mounted with
        nosuid option'
      mount:
        path: /var/log/audit
        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/audit" 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_audit_nosuid
      - no_reboot_needed

#### Rule Add nodev Option to /var/log [ref]

The `nodev` mount option can be used to prevent device files from being created in `/var/log`. 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 `/var/log`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_log_nodev

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
cis | 1.1.2.6.2

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|nodev)(,|$)//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}nodev 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 "nodev"; 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,nodev|" /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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log: Make sure nodev option is part of the to /var/log
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/log: Ensure /var/log is mounted with nodev 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_nodev
      - 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
cis | 1.1.2.6.4

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
cis | 1.1.2.6.3

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 nodev Option to /var [ref]

The `nodev` mount option can be used to prevent device files from being created in `/var`. 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 `/var`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_nodev

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
cis | 1.1.2.4.2

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|nodev)(,|$)//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}nodev 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 "nodev"; 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,nodev|" /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:
      - 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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:
      - 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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:
      - 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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:
      - 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var: Make sure nodev option is part of the to /var options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var: Ensure /var is mounted with nodev 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:
      - 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_nodev
      - 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
cis | 1.1.2.4.3

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 nodev Option to /var/tmp [ref]

The `nodev` mount option can be used to prevent device files from being created in `/var/tmp`. Legitimate character and block devices should not exist within temporary directories like `/var/tmp`. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/tmp`.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_tmp_nodev

References:

os-srg | SRG-OS-000368-GPOS-00154
cis | 1.1.2.5.2

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|nodev)(,|$)//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}nodev 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 "nodev"; 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,nodev|" /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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev 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_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/tmp: Make sure nodev option is part of the to /var/tmp
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      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 "nodev" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /var/tmp: Ensure /var/tmp is mounted with nodev 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_nodev
      - 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
cis | 1.1.2.5.4

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
cis | 1.1.2.5.3

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 2 groups and 4 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 2 rules

[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 All Users [ref]

To disable core dumps for all users, add the following line to `/etc/security/limits.conf`, or to a file within the `/etc/security/limits.d/` directory:

    *     hard   core    0

Rationale: | A core dump includes a memory image taken at the time the operating system terminates an application. The memory image could contain sensitive data and is generally useful only for developers trying to debug problems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_disable_users_coredumps

References:

cis-csc | 1, 12, 13, 15, 16, 2, 7, 8
cobit5 | APO13.01, BAI04.04, DSS01.03, DSS03.05, DSS05.07
isa-62443-2013 | SR 6.2, SR 7.1, SR 7.2
iso27001-2013 | A.12.1.3, A.17.2.1
nist | CM-6, SC-7(10)
nist-csf | DE.CM-1, PR.DS-4
os-srg | SRG-OS-000480-GPOS-00227
cis | 1.5.3
pcidss4 | 3.3.1.1, 3.3.1, 3.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

    SECURITY_LIMITS_FILE="/etc/security/limits.conf"
    DROPIN_DIR="/etc/security/limits.d"
    DROPIN_FILE="$DROPIN_DIR/10-ssg-hardening.conf"
    REGEX_CORRECT_VALUE="^\s*\*\s+hard\s+core\s+0\s*$"

    # Remove bad configuration in drop-ins
    if [ -d "$DROPIN_DIR" ]; then
        for override in "$DROPIN_DIR"/*.conf; do
            if [ -f "$override" ] && ! grep -qE "$REGEX_CORRECT_VALUE" "$override"; then
                sed -ir -E '/^[[:space:]]*\*[[:space:]]+hard[[:space:]]+core[[:space:]]+/ s/^/#/' "$override"
            fi
        done
    fi

    if [ -d "$DROPIN_DIR" ] && grep -qEr "$REGEX_CORRECT_VALUE" "$DROPIN_DIR"; then
        exit 0
    elif [ ! -d "$DROPIN_DIR" ] && grep -qE "$REGEX_CORRECT_VALUE" "$SECURITY_LIMITS_FILE"; then
        exit 0
    else
        mkdir -p "$DROPIN_DIR"
        echo "*     hard   core    0" >> $DROPIN_FILE
    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
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Set dirs, files and regex variables
      ansible.builtin.set_fact:
        limits_dropin_dir: /etc/security/limits.d
        limits_dropin_file: /etc/security/limits.d/10-ssg-hardening.conf
        limits_main_file: /etc/security/limits.conf
        limits_correct_regex: ^\s*\*\s+hard\s+core\s+0\s*$
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Find valid drop-ins for core limit
      ansible.builtin.find:
        paths: '{{ limits_dropin_dir }}'
        patterns: '*.conf'
        contains: '{{ limits_correct_regex }}'
        file_type: file
      register: valid_dropins
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Find all drop-ins with any core limit
      ansible.builtin.find:
        paths: '{{ limits_dropin_dir }}'
        patterns: '*.conf'
        contains: ^\s*\*\s+hard\s+core\s+
        file_type: file
      register: all_dropins
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Get invalid drop-ins
      ansible.builtin.set_fact:
        invalid_dropins: '{{ all_dropins.files | rejectattr(''path'', ''in'', valid_dropins.files
          | map(attribute=''path'') | list) | map(attribute=''path'') | list }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Comment invalid * hard core lines in drop-ins
      ansible.builtin.replace:
        path: '{{ item }}'
        regexp: (^\s*\*\s+hard\s+core\s+.*$)
        replace: '#\1'
      loop: '{{ invalid_dropins }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - invalid_dropins | length > 0
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Check if main limits.conf contains correct
        core limit
      ansible.builtin.find:
        paths: /etc/security
        patterns: limits.conf
        contains: '{{ limits_correct_regex }}'
        file_type: file
      register: main_valid
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - not (valid_dropins.matched | default(0) > 0)
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Set fact if configuration is valid
      ansible.builtin.set_fact:
        core_limit_valid: '{{ (valid_dropins.matched | default(0)) > 0 or (main_valid.matched
          | default(0)) > 0 }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Ensure drop-in directory exists
      ansible.builtin.file:
        path: '{{ limits_dropin_dir }}'
        state: directory
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - not core_limit_valid
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Core Dumps for All Users - Deploy 10-ssg-hardening.conf drop-in with
        correct core limit
      ansible.builtin.copy:
        dest: '{{ limits_dropin_file }}'
        content: |
          *     hard   core    0
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpam-runtime" in ansible_facts.packages'
      - not core_limit_valid
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_users_coredumps
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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
cis | 1.5.3
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 1 rule

[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 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
cis | 1.5.1
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

#### 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
cis | 1.5.2
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

Group Services Group contains 45 groups and 118 rules

[ref] The best protection against vulnerable software is running less software. This section describes how to review the software which Debian 12 installs on a system and disable software which is not needed. It then enumerates the software packages installed on a default Debian 12 system and provides guidance about which ones can be safely disabled.
Debian 12 provides a convenient minimal install option that essentially installs the bare necessities for a functional system. When building Debian 12 systems, it is highly recommended to select the minimal packages and then build up the system from there.

Group Avahi Server Group contains 1 group and 2 rules
[ref] The Avahi daemon implements the DNS Service Discovery and Multicast DNS protocols, which provide service and host discovery on a network. It allows a system to automatically identify resources on the network, such as printers or web servers. This capability is also known as mDNSresponder and is a major part of Zeroconf networking.
Group Disable Avahi Server if Possible Group contains 2 rules
[ref] Because the Avahi daemon service keeps an open network port, it is subject to network attacks. Disabling it can reduce the system's vulnerability to such attacks.

#### Rule Uninstall avahi Server Package [ref]

If the system does not need to have an Avahi server which implements the DNS Service Discovery and Multicast DNS protocols, the avahi-autoipd and avahi packages can be uninstalled.
Rationale: | Automatic discovery of network services is not normally required for system functionality. It is recommended to remove this package to reduce the potential attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_avahi_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
cis | 2.1.2

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove avahi
    # from the system, and may remove any packages
    # that depend on avahi. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "avahi"

Remediation Puppet snippet ⇲

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

    include remove_avahi

    class remove_avahi {
      package { 'avahi':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall avahi Server Package: Ensure avahi is removed'
      ansible.builtin.package:
        name: avahi
        state: absent
      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_avahi_removed

#### Rule Disable Avahi Server Software [ref]

The `avahi-daemon` service can be disabled with the following command:

    $ sudo systemctl mask --now avahi-daemon.service

Rationale: | Because the Avahi daemon service keeps an open network port, it is subject to network attacks. Its functionality is convenient but is only appropriate if the local network can be trusted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_avahi-daemon_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
cis | 2.1.2
ism | 1409
pcidss4 | 2.2.4, 2.2

Remediation Puppet snippet ⇲

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

    include disable_avahi-daemon

    class disable_avahi-daemon {
      service {'avahi-daemon':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_avahi-daemon_disabled

    - name: Disable Avahi Server Software - Disable service avahi-daemon
      block:

      - name: Disable Avahi Server Software - Collect systemd Services Present in the
          System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Avahi Server Software - Ensure avahi-daemon.service is Masked
        ansible.builtin.systemd:
          name: avahi-daemon.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("avahi-daemon.service", multiline=True)

      - name: Unit Socket Exists - avahi-daemon.socket
        ansible.builtin.command: systemctl -q list-unit-files avahi-daemon.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Avahi Server Software - Disable Socket avahi-daemon
        ansible.builtin.systemd:
          name: avahi-daemon.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("avahi-daemon.socket", multiline=True)
      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
      - service_avahi-daemon_disabled
      - special_service_block
      when: ( "avahi" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["avahi-daemon"]

Group Cron and At Daemons Group contains 1 group and 32 rules
[ref] The cron and at services are used to allow commands to be executed at a later time. The cron service is required by almost all systems to perform necessary maintenance tasks, while at may or may not be required on a given system. Both daemons should be configured defensively.
Group Restrict at and cron to Authorized Users if Necessary Group contains 12 rules

[ref] The `/etc/cron.allow` and `/etc/at.allow` files contain lists of users who are allowed to use `cron` and at to delay execution of processes. If these files exist and if the corresponding files `/etc/cron.deny` and `/etc/at.deny` do not exist, then only users listed in the relevant allow files can run the crontab and `at` commands to submit jobs to be run at scheduled intervals. On many systems, only the system administrator needs the ability to schedule jobs. Note that even if a given user is not listed in `cron.allow`, cron jobs can still be run as that user. The `cron.allow` file controls only administrative access to the crontab command for scheduling and modifying cron jobs.
To restrict `at` and `cron` to only authorized users:

- Remove the `cron.deny` file:

      $ sudo rm /etc/cron.deny

- Edit `/etc/cron.allow`, adding one line for each user allowed to use the crontab command to create cron jobs.
- Remove the `at.deny` file:

      $ sudo rm /etc/at.deny

- Edit `/etc/at.allow`, adding one line for each user allowed to use the at command to create at jobs.

#### Rule Ensure that /etc/at.allow exists [ref]

The file `/etc/at.allow` should exist and should be used instead of `/etc/at.deny`.
Rationale: | Using the at.allow file to control who can run at jobs enforces this who can schedule jobs. It is easier to manage an allow list than a deny list.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_at_allow_exists

References:

cis | 2.4.2.1

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

    touch /etc/at.allow
        chown 0 /etc/at.allow
        chmod 0640 /etc/at.allow

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - file_at_allow_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure that /etc/at.allow exists - Add empty /etc/at.allow
      ansible.builtin.file:
        path: /etc/at.allow
        state: touch
        owner: '0'
        mode: '0640'
        modification_time: preserve
        access_time: preserve
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - file_at_allow_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure that /etc/cron.allow exists [ref]

The file `/etc/cron.allow` should exist and should be used instead of `/etc/cron.deny`.
Rationale: | Access to `crontab` should be restricted. It is easier to manage an allow list than a deny list. Therefore, `/etc/cron.allow` needs to be created and used instead of `/etc/cron.deny`. Regardless of the existence of any of these files, the root administrative user is always allowed to setup a crontab.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_cron_allow_exists

References:

cis | 2.4.1.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

    touch /etc/cron.allow
        chown 0 /etc/cron.allow
        chmod 0600 /etc/cron.allow

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - file_cron_allow_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure that /etc/cron.allow exists - Add empty /etc/cron.allow
      ansible.builtin.file:
        path: /etc/cron.allow
        state: touch
        owner: '0'
        mode: '0600'
        modification_time: preserve
        access_time: preserve
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - file_cron_allow_exists
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure that /etc/cron.deny does not exist [ref]

The file `/etc/cron.deny` should not exist. Use `/etc/cron.allow` instead.
Rationale: | Access to `cron` should be restricted. It is easier to manage an allow list than a deny list.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_cron_deny_not_exist

References:

cis | 2.4.1.8
pcidss4 | 2.2.6, 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

    if [[ -f  /etc/cron.deny ]]; then
            rm /etc/cron.deny
        fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - disable_strategy
      - file_cron_deny_not_exist
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure that /etc/cron.deny does not exist - Remove /etc/cron.deny
      ansible.builtin.file:
        path: /etc/cron.deny
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - disable_strategy
      - file_cron_deny_not_exist
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/at.allow file [ref]

If `/etc/at.allow` exists, it must be group-owned by `root`. To properly set the group owner of `/etc/at.allow`, run the command:

    $ sudo chgrp root /etc/at.allow

Rationale: | If the owner of the at.allow file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_at_allow

References:

cis | 2.4.2.1
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

    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/at.allow" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/at.allow
    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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_at_allow_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_at_allow_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/at.allow
      ansible.builtin.stat:
        path: /etc/at.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/at.allow
      ansible.builtin.file:
        path: /etc/at.allow
        follow: false
        group: '{{ file_groupowner_at_allow_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/at.deny file [ref]

If `/etc/at.deny` exists, it must be group-owned by `root`. To properly set the group owner of `/etc/at.deny`, run the command:

    $ sudo chgrp root /etc/at.deny

Rationale: | If the owner of the at.deny file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_at_deny

References:

cis | 2.4.2.1

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/at.deny" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/at.deny
    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_at_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

#### Rule Verify Group Who Owns /etc/cron.allow file [ref]

If `/etc/cron.allow` exists, it must be group-owned by `root`. To properly set the group owner of `/etc/cron.allow`, run the command:

    $ sudo chgrp root /etc/cron.allow

Rationale: | If the owner of the cron.allow file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_cron_allow

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.8
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

    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/cron.allow" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/cron.allow
    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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_allow_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_allow_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/cron.allow
      ansible.builtin.stat:
        path: /etc/cron.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.allow
      ansible.builtin.file:
        path: /etc/cron.allow
        follow: false
        group: '{{ file_groupowner_cron_allow_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/at.allow file [ref]

If `/etc/at.allow` exists, it must be owned by `root`. To properly set the owner of `/etc/at.allow`, run the command:

    $ sudo chown root /etc/at.allow

Rationale: | If the owner of the at.allow file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_at_allow

References:

cis | 2.4.2.1
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

    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/at.allow" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/at.allow
    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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_at_allow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_at_allow_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/at.allow
      ansible.builtin.stat:
        path: /etc/at.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/at.allow
      ansible.builtin.file:
        path: /etc/at.allow
        follow: false
        owner: '{{ file_owner_at_allow_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/at.deny file [ref]

If `/etc/at.deny` exists, it must be owned by `root`. To properly set the owner of `/etc/at.deny`, run the command:

    $ sudo chown root /etc/at.deny

Rationale: | If the owner of the at.deny file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_at_deny

References:

cis | 2.4.2.1

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/at.deny" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/at.deny
    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_at_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

#### Rule Verify User Who Owns /etc/cron.allow file [ref]

If `/etc/cron.allow` exists, it must be owned by `root`. To properly set the owner of `/etc/cron.allow`, run the command:

    $ sudo chown root /etc/cron.allow

Rationale: | If the owner of the cron.allow file is not set to root, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_allow

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.8
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

    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/cron.allow" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/cron.allow
    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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_allow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_allow_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/cron.allow
      ansible.builtin.stat:
        path: /etc/cron.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/cron.allow
      ansible.builtin.file:
        path: /etc/cron.allow
        follow: false
        owner: '{{ file_owner_cron_allow_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/at.allow file [ref]

If `/etc/at.allow` exists, it must have permissions `0640` or more restrictive. To properly set the permissions of `/etc/at.allow`, run the command:

    $ sudo chmod 0640 /etc/at.allow

Rationale: | If the permissions of the at.allow file are not set to 0640 or more restrictive, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_at_allow

References:

cis | 2.4.2.1
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-xws,o-xwrt /etc/at.allow

    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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/at.allow
      ansible.builtin.stat:
        path: /etc/at.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/at.allow
      ansible.builtin.file:
        path: /etc/at.allow
        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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_at_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/at.deny file [ref]

If `/etc/at.deny` exists, it must have permissions `0640` or more restrictive. To properly set the permissions of `/etc/at.deny`, run the command:

    $ sudo chmod 0640 /etc/at.deny

Rationale: | If the permissions of the at.deny file are not set to 0640 or more restrictive, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_at_deny

References:

cis | 2.4.2.1

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/at.deny

    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_at_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/at.deny
      ansible.builtin.file:
        path: /etc/at.deny
        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_at_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/cron.allow file [ref]

If `/etc/cron.allow` exists, it must have permissions `0640` or more restrictive. To properly set the permissions of `/etc/cron.allow`, run the command:

    $ sudo chmod 0640 /etc/cron.allow

Rationale: | If the permissions of the cron.allow file are not set to 0640 or more restrictive, the possibility exists for an unauthorized user to view or edit sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_allow

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.8
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-xws,o-xwrt /etc/cron.allow

    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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/cron.allow
      ansible.builtin.stat:
        path: /etc/cron.allow
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/cron.allow
      ansible.builtin.file:
        path: /etc/cron.allow
        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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_cron_allow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Install the cron service [ref]

The Cron service should be installed.
Rationale: | The cron service allow periodic job execution, needed for almost all administrative tasks and services (software update, log rotating, etc.). Access to cron service should be restricted to administrative accounts only.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_cron_installed

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, 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 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-6(a)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.1
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 "cron"

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

Remediation Puppet snippet ⇲

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

    include install_cron

    class install_cron {
      package { 'cron':
        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_cron_installed

    - name: Ensure cron is installed
      ansible.builtin.package:
        name: cron
        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_cron_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Enable cron Service [ref]

The `crond` service is used to execute commands at preconfigured times. It is required by almost all systems to perform necessary maintenance tasks, such as notifying root of system activity. The `cron` service can be enabled with the following command:

    $ sudo systemctl enable cron.service

Rationale: | Due to its usage for maintenance and security-supporting tasks, enabling the cron daemon is essential.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_cron_enabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, 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 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-6(a)
nist-csf | PR.IP-1, PR.PT-3
cis | 2.4.1.1

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 'cron.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'cron.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'cron.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_cron

    class enable_cron {
      service {'cron':
        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)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_cron_enabled

    - name: Enable cron Service - Enable service cron
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable cron Service - Enable Service cron
        ansible.builtin.systemd:
          name: cron
          enabled: true
          state: started
          masked: false
        when:
        - '"cron" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_cron_enabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["cron"]

#### Rule Verify Group Who Owns cron.d [ref]

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

    $ sudo chgrp root /etc/cron.d

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_cron_d

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.7
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

    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/cron.d/ -maxdepth 0 -type d  ! -group 0 -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_d_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_d_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.d/
      ansible.builtin.file:
        path: /etc/cron.d/
        follow: false
        state: directory
        group: '{{ file_groupowner_cron_d_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns cron.daily [ref]

To properly set the group owner of `/etc/cron.daily`, run the command:

    $ sudo chgrp root /etc/cron.daily

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_cron_daily

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.4
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

    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/cron.daily/ -maxdepth 0 -type d  ! -group 0 -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_daily_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_daily_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.daily/
      ansible.builtin.file:
        path: /etc/cron.daily/
        follow: false
        state: directory
        group: '{{ file_groupowner_cron_daily_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns cron.hourly [ref]

To properly set the group owner of `/etc/cron.hourly`, run the command:

    $ sudo chgrp root /etc/cron.hourly

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_cron_hourly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.3
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

    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/cron.hourly/ -maxdepth 0 -type d  ! -group 0 -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_hourly_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_hourly_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.hourly/
      ansible.builtin.file:
        path: /etc/cron.hourly/
        follow: false
        state: directory
        group: '{{ file_groupowner_cron_hourly_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns cron.monthly [ref]

To properly set the group owner of `/etc/cron.monthly`, run the command:

    $ sudo chgrp root /etc/cron.monthly

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_cron_monthly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.6
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

    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/cron.monthly/ -maxdepth 0 -type d  ! -group 0 -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_monthly_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_monthly_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.monthly/
      ansible.builtin.file:
        path: /etc/cron.monthly/
        follow: false
        state: directory
        group: '{{ file_groupowner_cron_monthly_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns cron.weekly [ref]

To properly set the group owner of `/etc/cron.weekly`, run the command:

    $ sudo chgrp root /etc/cron.weekly

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_cron_weekly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.5
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

    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/cron.weekly/ -maxdepth 0 -type d  ! -group 0 -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_weekly_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_weekly_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.weekly/
      ansible.builtin.file:
        path: /etc/cron.weekly/
        follow: false
        state: directory
        group: '{{ file_groupowner_cron_weekly_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns Crontab [ref]

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

    $ sudo chgrp root /etc/crontab

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_crontab

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.2
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

    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/crontab" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/crontab
    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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_crontab_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_crontab_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crontab
      ansible.builtin.stat:
        path: /etc/crontab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/crontab
      ansible.builtin.file:
        path: /etc/crontab
        follow: false
        group: '{{ file_groupowner_crontab_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on cron.d [ref]

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

    $ sudo chown root /etc/cron.d

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_d

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.7
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

    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/cron.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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_d_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_d_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/cron.d/
      ansible.builtin.file:
        path: /etc/cron.d/
        follow: false
        state: directory
        owner: '{{ file_owner_cron_d_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on cron.daily [ref]

To properly set the owner of `/etc/cron.daily`, run the command:

    $ sudo chown root /etc/cron.daily

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_daily

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.4
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

    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/cron.daily/ -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_daily_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_daily_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/cron.daily/
      ansible.builtin.file:
        path: /etc/cron.daily/
        follow: false
        state: directory
        owner: '{{ file_owner_cron_daily_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on cron.hourly [ref]

To properly set the owner of `/etc/cron.hourly`, run the command:

    $ sudo chown root /etc/cron.hourly

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_hourly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.3
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

    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/cron.hourly/ -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_hourly_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_hourly_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/cron.hourly/
      ansible.builtin.file:
        path: /etc/cron.hourly/
        follow: false
        state: directory
        owner: '{{ file_owner_cron_hourly_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on cron.monthly [ref]

To properly set the owner of `/etc/cron.monthly`, run the command:

    $ sudo chown root /etc/cron.monthly

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_monthly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.6
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

    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/cron.monthly/ -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_monthly_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_monthly_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/cron.monthly/
      ansible.builtin.file:
        path: /etc/cron.monthly/
        follow: false
        state: directory
        owner: '{{ file_owner_cron_monthly_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on cron.weekly [ref]

To properly set the owner of `/etc/cron.weekly`, run the command:

    $ sudo chown root /etc/cron.weekly

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_cron_weekly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.5
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

    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/cron.weekly/ -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:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_weekly_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_weekly_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/cron.weekly/
      ansible.builtin.file:
        path: /etc/cron.weekly/
        follow: false
        state: directory
        owner: '{{ file_owner_cron_weekly_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on crontab [ref]

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

    $ sudo chown root /etc/crontab

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 user to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_crontab

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.2
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

    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/crontab" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/crontab
    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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_crontab_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_crontab_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crontab
      ansible.builtin.stat:
        path: /etc/crontab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/crontab
      ansible.builtin.file:
        path: /etc/crontab
        follow: false
        owner: '{{ file_owner_crontab_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on cron.d [ref]

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

    $ sudo chmod 0700 /etc/cron.d

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_d

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.7
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 -H /etc/cron.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:
      - 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_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/cron.d/ file(s)
      ansible.builtin.command: 'find -P /etc/cron.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: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/cron.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on cron.daily [ref]

To properly set the permissions of `/etc/cron.daily`, run the command:

    $ sudo chmod 0700 /etc/cron.daily

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_daily

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.4
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 -H /etc/cron.daily/ -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:
      - 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_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/cron.daily/ file(s)
      ansible.builtin.command: 'find -P /etc/cron.daily/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/cron.daily/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_daily
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on cron.hourly [ref]

To properly set the permissions of `/etc/cron.hourly`, run the command:

    $ sudo chmod 0700 /etc/cron.hourly

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_hourly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.3
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 -H /etc/cron.hourly/ -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:
      - 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_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/cron.hourly/ file(s)
      ansible.builtin.command: 'find -P /etc/cron.hourly/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/cron.hourly/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_hourly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on cron.monthly [ref]

To properly set the permissions of `/etc/cron.monthly`, run the command:

    $ sudo chmod 0700 /etc/cron.monthly

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_monthly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.6
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 -H /etc/cron.monthly/ -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:
      - 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_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/cron.monthly/ file(s)
      ansible.builtin.command: 'find -P /etc/cron.monthly/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/cron.monthly/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_monthly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on cron.weekly [ref]

To properly set the permissions of `/etc/cron.weekly`, run the command:

    $ sudo chmod 0700 /etc/cron.weekly

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_cron_weekly

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.5
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 -H /etc/cron.weekly/ -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:
      - 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_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/cron.weekly/ file(s)
      ansible.builtin.command: 'find -P /etc/cron.weekly/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/cron.weekly/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_cron_weekly
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on crontab [ref]

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

    $ sudo chmod 0600 /etc/crontab

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 have the correct access rights to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_crontab

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
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.4.1.2
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/crontab

    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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crontab
      ansible.builtin.stat:
        path: /etc/crontab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - 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_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /etc/crontab
      ansible.builtin.file:
        path: /etc/crontab
        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-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Deprecated services Group contains 1 rule
[ref] Some deprecated software services impact the overall system security due to their behavior (leak of confidentiality in network exchange, usage as uncontrolled communication channel, risk associated with the service due to its old age, etc.

#### Rule Uninstall the nis package [ref]

The support for Yellowpages should not be installed unless it is required.
Rationale: | NIS is the historical SUN service for central account management, more and more replaced by LDAP. NIS does not support efficiently security constraints, ACL, etc. and should not be used.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_nis_removed

References:

cis | 2.2.1

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove nis
    # from the system, and may remove any packages
    # that depend on nis. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "nis"

Remediation Puppet snippet ⇲

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

    include remove_nis

    class remove_nis {
      package { 'nis':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall the nis package: Ensure nis is removed'
      ansible.builtin.package:
        name: nis
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_nis_removed

Group DHCP Group contains 1 group and 3 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 3 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
cis | 2.1.3
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 Disable DHCPD6 Service [ref]

The `dhcp6` service should be disabled on any system that does not need to act as a DHCP server. The `dhcpd6` service can be disabled with the following command:

    $ sudo systemctl mask --now dhcpd6.service

Rationale: | Unmanaged or unintentionally activated DHCP servers may provide faulty information to clients, interfering with the operation of a legitimate site DHCP server if there is one.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_dhcpd6_disabled

References:

cis | 2.1.3

Remediation Puppet snippet ⇲

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

    include disable_dhcpd6

    class disable_dhcpd6 {
      service {'dhcpd6':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_dhcpd6_disabled

    - name: Disable DHCPD6 Service - Disable service dhcpd6
      block:

      - name: Disable DHCPD6 Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable DHCPD6 Service - Ensure dhcpd6.service is Masked
        ansible.builtin.systemd:
          name: dhcpd6.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("dhcpd6.service", multiline=True)

      - name: Unit Socket Exists - dhcpd6.socket
        ansible.builtin.command: systemctl -q list-unit-files dhcpd6.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable DHCPD6 Service - Disable Socket dhcpd6
        ansible.builtin.systemd:
          name: dhcpd6.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("dhcpd6.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_dhcpd6_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["dhcpd6"]

#### Rule Disable DHCP Service [ref]

The `dhcpd` service should be disabled on any system that does not need to act as a DHCP server. The `dhcpd` service can be disabled with the following command:

    $ sudo systemctl mask --now dhcpd.service

Rationale: | Unmanaged or unintentionally activated DHCP servers may provide faulty information to clients, interfering with the operation of a legitimate site DHCP server if there is one.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_dhcpd_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
cis | 2.1.3

Remediation Puppet snippet ⇲

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

    include disable_dhcpd

    class disable_dhcpd {
      service {'dhcpd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - service_dhcpd_disabled

    - name: Disable DHCP Service - Disable service dhcpd
      block:

      - name: Disable DHCP Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable DHCP Service - Ensure dhcpd.service is Masked
        ansible.builtin.systemd:
          name: dhcpd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("dhcpd.service", multiline=True)

      - name: Unit Socket Exists - dhcpd.socket
        ansible.builtin.command: systemctl -q list-unit-files dhcpd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable DHCP Service - Disable Socket dhcpd
        ansible.builtin.systemd:
          name: dhcpd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("dhcpd.socket", multiline=True)
      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
      - service_dhcpd_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["dhcpd"]

Group DNS Server Group contains 1 group and 4 rules
[ref] Most organizations have an operational need to run at least one nameserver. However, there are many common attacks involving DNS server software, and this server software should be disabled on any system on which it is not needed.
Group Disable DNS Server Group contains 2 rules
[ref] DNS software should be disabled on any systems which does not need to be a nameserver. Note that the BIND DNS server software is not installed on Debian 12 by default. The remainder of this section discusses secure configuration of systems which must be nameservers.

#### Rule Uninstall bind Package [ref]

The `named` service is provided by the `bind` package. The `bind` package can be removed with the following command:

    $ apt-get remove bind

Rationale: | If there is no need to make DNS server software available, removing it provides a safeguard against its activation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_bind_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
cis | 2.1.4

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove bind
    # from the system, and may remove any packages
    # that depend on bind. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "bind"

Remediation Puppet snippet ⇲

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

    include remove_bind

    class remove_bind {
      package { 'bind':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall bind Package: Ensure bind is removed'
      ansible.builtin.package:
        name: bind
        state: absent
      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
      - low_severity
      - no_reboot_needed
      - package_bind_removed

#### Rule Disable named Service [ref]

The `named` service can be disabled with the following command:

    $ sudo systemctl mask --now named.service

Rationale: | All network services involve some risk of compromise due to implementation flaws and should be disabled if possible.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_named_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
cis | 2.1.4

Remediation Puppet snippet ⇲

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

    include disable_named

    class disable_named {
      service {'named':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - service_named_disabled

    - name: Disable named Service - Disable service named
      block:

      - name: Disable named Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable named Service - Ensure named.service is Masked
        ansible.builtin.systemd:
          name: named.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("named.service", multiline=True)

      - name: Unit Socket Exists - named.socket
        ansible.builtin.command: systemctl -q list-unit-files named.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable named Service - Disable Socket named
        ansible.builtin.systemd:
          name: named.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("named.socket", multiline=True)
      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
      - service_named_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["named"]

#### Rule Uninstall dnsmasq Package [ref]

dnsmasq is a lightweight tool that provides DNS caching, DNS forwarding and DHCP (Dynamic Host Configuration Protocol) services.
The `dnsmasq` package can be removed with the following command:

    $ apt-get remove dnsmasq

Rationale: | Unless a system is specifically designated to act as a DNS caching, DNS forwarding and/or DHCP server, it is recommended that the package be removed to reduce the potential attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_dnsmasq_removed

References:

cis | 2.1.5

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove dnsmasq
    # from the system, and may remove any packages
    # that depend on dnsmasq. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "dnsmasq"

Remediation Puppet snippet ⇲

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

    include remove_dnsmasq

    class remove_dnsmasq {
      package { 'dnsmasq':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall dnsmasq Package: Ensure dnsmasq is removed'
      ansible.builtin.package:
        name: dnsmasq
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_dnsmasq_removed

#### Rule Disable dnsmasq Service [ref]

The `dnsmasq` service can be disabled with the following command:

    $ sudo systemctl mask --now dnsmasq.service

Rationale: | Unless a system is specifically designated to act as a DNS caching, DNS forwarding and/or DHCP server, it is recommended that the package be removed to reduce the potential attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_dnsmasq_disabled

References:

cis | 2.1.5

Remediation Puppet snippet ⇲

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

    include disable_dnsmasq

    class disable_dnsmasq {
      service {'dnsmasq':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_dnsmasq_disabled

    - name: Disable dnsmasq Service - Disable service dnsmasq
      block:

      - name: Disable dnsmasq Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable dnsmasq Service - Ensure dnsmasq.service is Masked
        ansible.builtin.systemd:
          name: dnsmasq.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("dnsmasq.service", multiline=True)

      - name: Unit Socket Exists - dnsmasq.socket
        ansible.builtin.command: systemctl -q list-unit-files dnsmasq.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable dnsmasq Service - Disable Socket dnsmasq
        ansible.builtin.systemd:
          name: dnsmasq.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("dnsmasq.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_dnsmasq_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["dnsmasq"]

Group FTP Server Group contains 1 group and 4 rules

[ref] FTP is a common method for allowing remote access to files. Like telnet, the FTP protocol is unencrypted, which means that passwords and other data transmitted during the session can be captured and that the session is vulnerable to hijacking. Therefore, running the FTP server software is not recommended.
However, there are some FTP server configurations which may be appropriate for some environments, particularly those which allow only read-only anonymous access as a means of downloading data available to the public.

Group Disable vsftpd if Possible Group contains 2 rules
[ref] To minimize attack surface, disable vsftpd if at all possible.

#### Rule Uninstall vsftpd Package [ref]

The `vsftpd` package can be removed with the following command:

     $ apt-get remove vsftpd

Rationale: | Removing the `vsftpd` package decreases the risk of its accidental activation.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_vsftpd_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), IA-5(1)(c), IA-5(1).1(v), CM-7, CM-7.1(ii)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000074-GPOS-00042, SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
cis | 2.1.6

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove vsftpd
    # from the system, and may remove any packages
    # that depend on vsftpd. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "vsftpd"

Remediation Puppet snippet ⇲

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

    include remove_vsftpd

    class remove_vsftpd {
      package { 'vsftpd':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall vsftpd Package: Ensure vsftpd is removed'
      ansible.builtin.package:
        name: vsftpd
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-CM-7.1(ii)
      - NIST-800-53-IA-5(1)(c)
      - NIST-800-53-IA-5(1).1(v)
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_vsftpd_removed

#### Rule Disable vsftpd Service [ref]

The `vsftpd` service can be disabled with the following command:

    $ sudo systemctl mask --now vsftpd.service

Rationale: | Running FTP server software provides a network-based avenue of attack, and should be disabled if not needed. Furthermore, the FTP protocol is unencrypted and creates a risk of compromising sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_vsftpd_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
cis | 2.1.6

Remediation Puppet snippet ⇲

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

    include disable_vsftpd

    class disable_vsftpd {
      service {'vsftpd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - service_vsftpd_disabled

    - name: Disable vsftpd Service - Disable service vsftpd
      block:

      - name: Disable vsftpd Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable vsftpd Service - Ensure vsftpd.service is Masked
        ansible.builtin.systemd:
          name: vsftpd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("vsftpd.service", multiline=True)

      - name: Unit Socket Exists - vsftpd.socket
        ansible.builtin.command: systemctl -q list-unit-files vsftpd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable vsftpd Service - Disable Socket vsftpd
        ansible.builtin.systemd:
          name: vsftpd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("vsftpd.socket", multiline=True)
      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
      - service_vsftpd_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["vsftpd"]

#### Rule Remove ftp Package [ref]

FTP (File Transfer Protocol) is a traditional and widely used standard tool for transferring files between a server and clients over a network, especially where no authentication is necessary (permits anonymous users to connect to a server).
The `ftp` package can be removed with the following command:

    $ apt-get remove ftp

Rationale: | FTP does not protect the confidentiality of data or authentication credentials. It is recommended SFTP be used if file transfer is required. Unless there is a need to run the system as a FTP server (for example, to allow anonymous downloads), it is recommended that the package be removed to reduce the potential attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_ftp_removed

References:

cis | 2.2.6
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove ftp
    # from the system, and may remove any packages
    # that depend on ftp. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "ftp"

Remediation Puppet snippet ⇲

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

    include remove_ftp

    class remove_ftp {
      package { 'ftp':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Remove ftp Package: Ensure ftp is removed'
      ansible.builtin.package:
        name: ftp
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_ftp_removed

#### Rule Remove tnftp Package [ref]

tnftp an enhanced FTP client, is the user interface to the Internet standard File Transfer Protocol. The program allows a user to transfer files to and from a remote network site. The `ftp` package can be removed with the following command:

    $ apt-get remove ftp

Rationale: | Unless there is a need to run the system using Internet standard File Transfer Protocol (for example, to allow anonymous downloads), it is recommended that the package be removed to reduce the potential attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_tnftp_removed

References:

cis | 2.2.6

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove tnftp
    # from the system, and may remove any packages
    # that depend on tnftp. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "tnftp"

Remediation Puppet snippet ⇲

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

    include remove_tnftp

    class remove_tnftp {
      package { 'tnftp':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Remove tnftp Package: Ensure tnftp is removed'
      ansible.builtin.package:
        name: tnftp
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_tnftp_removed

Group Web Server Group contains 2 groups and 4 rules

[ref] The web server is responsible for providing access to content via the HTTP protocol. Web servers represent a significant security risk because:

- The HTTP port is commonly probed by malicious sources
- Web server software is very complex, and includes a long history of vulnerabilities
- The HTTP protocol is unencrypted and vulnerable to passive monitoring

The system's default web server software is Apache 2 and is provided in the RPM package `httpd`.

Group Disable Apache if Possible Group contains 2 rules
[ref] If Apache was installed and activated, but the system does not need to act as a web server, then it should be disabled and removed from the system.

#### Rule Uninstall httpd Package [ref]

The `httpd` package can be removed with the following command:

    $ apt-get remove httpd

Rationale: | If there is no need to make the web server software available, removing it provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_httpd_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
cis | 2.1.18

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove httpd
    # from the system, and may remove any packages
    # that depend on httpd. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "httpd"

Remediation Puppet snippet ⇲

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

    include remove_httpd

    class remove_httpd {
      package { 'httpd':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall httpd Package: Ensure httpd is removed'
      ansible.builtin.package:
        name: httpd
        state: absent
      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
      - no_reboot_needed
      - package_httpd_removed
      - unknown_severity

#### Rule Disable httpd Service [ref]

The `httpd` service can be disabled with the following command:

    $ sudo systemctl mask --now httpd.service

Rationale: | Running web server software provides a network-based avenue of attack, and should be disabled if not needed.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_httpd_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
cis | 2.1.18

Remediation Puppet snippet ⇲

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

    include disable_httpd

    class disable_httpd {
      service {'httpd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_httpd_disabled
      - unknown_severity

    - name: Disable httpd Service - Disable service httpd
      block:

      - name: Disable httpd Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable httpd Service - Ensure httpd.service is Masked
        ansible.builtin.systemd:
          name: httpd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("httpd.service", multiline=True)

      - name: Unit Socket Exists - httpd.socket
        ansible.builtin.command: systemctl -q list-unit-files httpd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable httpd Service - Disable Socket httpd
        ansible.builtin.systemd:
          name: httpd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("httpd.socket", multiline=True)
      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
      - no_reboot_needed
      - service_httpd_disabled
      - special_service_block
      - unknown_severity
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["httpd"]

Group Disable NGINX if Possible Group contains 2 rules
[ref] If NGINX was installed and activated, but the system does not need to act as a web server, then it should be removed from the system.

#### Rule Uninstall nginx Package [ref]

The `nginx` package can be removed with the following command:

    $ apt-get remove nginx

Rationale: | If there is no need to make the web server software available, removing it provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_nginx_removed

References:

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
cis | 2.1.18

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove nginx
    # from the system, and may remove any packages
    # that depend on nginx. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "nginx"

Remediation Puppet snippet ⇲

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

    include remove_nginx

    class remove_nginx {
      package { 'nginx':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall nginx Package: Ensure nginx is removed'
      ansible.builtin.package:
        name: nginx
        state: absent
      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
      - no_reboot_needed
      - package_nginx_removed
      - unknown_severity

#### Rule Disable nginx Service [ref]

The `nginx` service can be disabled with the following command:

    $ sudo systemctl mask --now nginx.service

Rationale: | Running web server software provides a network-based avenue of attack, and should be disabled if not needed.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_nginx_disabled

References:

cis | 2.1.18

Remediation Puppet snippet ⇲

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

    include disable_nginx

    class disable_nginx {
      service {'nginx':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_nginx_disabled
      - unknown_severity

    - name: Disable nginx Service - Disable service nginx
      block:

      - name: Disable nginx Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable nginx Service - Ensure nginx.service is Masked
        ansible.builtin.systemd:
          name: nginx.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("nginx.service", multiline=True)

      - name: Unit Socket Exists - nginx.socket
        ansible.builtin.command: systemctl -q list-unit-files nginx.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable nginx Service - Disable Socket nginx
        ansible.builtin.systemd:
          name: nginx.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("nginx.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_nginx_disabled
      - special_service_block
      - unknown_severity
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["nginx"]

Group IMAP and POP3 Server Group contains 1 group and 2 rules
[ref] Dovecot provides IMAP and POP3 services. It is not installed by default. The project page at http://www.dovecot.org contains more detailed information about Dovecot configuration.
Group Disable Dovecot Group contains 2 rules
[ref] If the system does not need to operate as an IMAP or POP3 server, the dovecot software should be disabled and removed.

#### Rule Uninstall dovecot Package [ref]

The `dovecot` package can be removed with the following command:

    $ apt-get remove dovecot

Rationale: | If there is no need to make the Dovecot software available, removing it provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_dovecot_removed

References:

cis | 2.1.8

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove dovecot
    # from the system, and may remove any packages
    # that depend on dovecot. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "dovecot"

Remediation Puppet snippet ⇲

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

    include remove_dovecot

    class remove_dovecot {
      package { 'dovecot':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall dovecot Package: Ensure dovecot is removed'
      ansible.builtin.package:
        name: dovecot
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_dovecot_removed
      - unknown_severity

#### Rule Disable Dovecot Service [ref]

The `dovecot` service can be disabled with the following command:

    $ sudo systemctl mask --now dovecot.service

Rationale: | Running an IMAP or POP3 server provides a network-based avenue of attack, and should be disabled if not needed.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_dovecot_disabled

References:

cis | 2.1.8

Remediation Puppet snippet ⇲

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

    include disable_dovecot

    class disable_dovecot {
      service {'dovecot':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_dovecot_disabled
      - unknown_severity

    - name: Disable Dovecot Service - Disable service dovecot
      block:

      - name: Disable Dovecot Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Dovecot Service - Ensure dovecot.service is Masked
        ansible.builtin.systemd:
          name: dovecot.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("dovecot.service", multiline=True)

      - name: Unit Socket Exists - dovecot.socket
        ansible.builtin.command: systemctl -q list-unit-files dovecot.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Dovecot Service - Disable Socket dovecot
        ansible.builtin.systemd:
          name: dovecot.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("dovecot.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_dovecot_disabled
      - special_service_block
      - unknown_severity
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["dovecot"]

Group LDAP Group contains 2 groups and 3 rules
[ref] LDAP is a popular directory service, that is, a standardized way of looking up information from a central database. Debian 12 includes software that enables a system to act as both an LDAP client and server.
Group Configure OpenLDAP Clients Group contains 1 rule

[ref] This section provides information on which security settings are important to configure in OpenLDAP clients by manually editing the appropriate configuration files. Debian 12 provides an automated configuration tool called authconfig and a graphical wrapper for authconfig called `system-config-authentication`. However, these tools do not provide as much control over configuration as manual editing of configuration files. The authconfig tools do not allow you to specify locations of SSL certificate files, which is useful when trying to use SSL cleanly across several protocols. Installation and configuration of OpenLDAP on Debian 12 is available at
Warning: Before configuring any system to be an LDAP client, ensure that a working LDAP server is present on the network.

#### Rule Ensure LDAP client is not installed [ref]

The Lightweight Directory Access Protocol (LDAP) is a service that provides a method for looking up information from a central database. The `openldap-clients` package can be removed with the following command:

    $ apt-get remove openldap-clients

Rationale: | If the system does not need to act as an LDAP client, it is recommended that the software is removed to reduce the potential attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_openldap-clients_removed

References:

cis | 2.2.5

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove openldap-clients
    # from the system, and may remove any packages
    # that depend on openldap-clients. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "openldap-clients"

Remediation Puppet snippet ⇲

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

    include remove_openldap-clients

    class remove_openldap-clients {
      package { 'openldap-clients':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Ensure LDAP client is not installed: Ensure openldap-clients is removed'
      ansible.builtin.package:
        name: openldap-clients
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_openldap-clients_removed

Group Configure OpenLDAP Server Group contains 2 rules
[ref] This section details some security-relevant settings for an OpenLDAP server.

#### Rule Uninstall openldap-servers Package [ref]

The openldap-servers package is not installed by default on a Debian 12 system. It is needed only by the OpenLDAP server, not by the clients which use LDAP for authentication. If the system is not intended for use as an LDAP Server it should be removed.
Rationale: | Unnecessary packages should not be installed to decrease the attack surface of the system. While this software is clearly essential on an LDAP server, it is not necessary on typical desktop or workstation systems.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_openldap-servers_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
cis | 2.1.7

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove openldap-servers
    # from the system, and may remove any packages
    # that depend on openldap-servers. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "openldap-servers"

Remediation Puppet snippet ⇲

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

    include remove_openldap-servers

    class remove_openldap-servers {
      package { 'openldap-servers':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall openldap-servers Package: Ensure openldap-servers is removed'
      ansible.builtin.package:
        name: openldap-servers
        state: absent
      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
      - low_severity
      - no_reboot_needed
      - package_openldap-servers_removed

#### Rule Disable LDAP Server (slapd) [ref]

The Lightweight Directory Access Protocol (LDAP) is a service that provides a method for looking up information from a central database.
Rationale: | If the system will not need to act as an LDAP server, it is recommended that the software be disabled to reduce the potential attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_slapd_disabled

References:

cis | 2.1.7

Remediation Puppet snippet ⇲

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

    include disable_slapd

    class disable_slapd {
      service {'slapd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_slapd_disabled

    - name: Disable LDAP Server (slapd) - Disable service slapd
      block:

      - name: Disable LDAP Server (slapd) - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable LDAP Server (slapd) - Ensure slapd.service is Masked
        ansible.builtin.systemd:
          name: slapd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("slapd.service", multiline=True)

      - name: Unit Socket Exists - slapd.socket
        ansible.builtin.command: systemctl -q list-unit-files slapd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable LDAP Server (slapd) - Disable Socket slapd
        ansible.builtin.systemd:
          name: slapd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("slapd.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_slapd_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["slapd"]

Group Mail Server Software Group contains 1 group and 2 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 12 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 1 rule
[ref] This section discusses settings for Postfix in a submission-only e-mail configuration.

#### 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
cis | 2.1.21
pcidss4 | 1.4.2, 1.4

#### Rule Ensure Mail Transfer Agent is not Listening on any non-loopback Address [ref]

Mail Transfer Agents (MTA), such as sendmail and Postfix, are used to listen for incoming mail and transfer the messages to the appropriate user or mail server. If the system is not intended to be a mail server, it is recommended that the MTA be configured to only process local mail.
Rationale: | The software for all Mail Transfer Agents is complex and most have a long history of security issues. While it is important to ensure that the system can process local mail messages, it is not necessary to have the MTA's daemon listening on a port unless the server is intended to be a mail server that receives and processes mail from other systems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_has_nonlocal_mta

References:

cis | 2.1.21

Group NFS and RPC Group contains 4 groups and 4 rules

[ref] The Network File System is a popular distributed filesystem for the Unix environment, and is very widely deployed. This section discusses the circumstances under which it is possible to disable NFS and its dependencies, and then details steps which should be taken to secure NFS's configuration. This section is relevant to systems operating as NFS clients, as well as to those operating as NFS servers.

Group Disable All NFS Services if Possible Group contains 1 group and 2 rules
[ref] If there is not a reason for the system to operate as either an NFS client or an NFS server, follow all instructions in this section to disable subsystems required by NFS. Warning: The steps in this section will prevent a system from operating as either an NFS client or an NFS server. Only perform these steps on systems which do not need NFS at all.
Group Disable Services Used Only by NFS Group contains 2 rules
[ref] If NFS is not needed, disable the NFS client daemons nfslock, rpcgssd, and rpcidmapd. All of these daemons run with elevated privileges, and many listen for network connections. If they are not needed, they should be disabled to improve system security posture.

#### Rule Uninstall rpcbind Package [ref]

The rpcbind utility maps RPC services to the ports on which they listen. RPC processes notify rpcbind when they start, registering the ports they are listening on and the RPC program numbers they expect to serve. The rpcbind service redirects the client to the proper port number so it can communicate with the requested service. If the system does not require RPC (such as for NFS servers) then this service should be disabled. The `rpcbind` package can be removed with the following command:

    $ apt-get remove rpcbind

Rationale: | If the system does not require rpc based services, it is recommended that rpcbind be disabled to reduce the attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_rpcbind_removed

References:

cis | 2.1.12

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 rpcbind
    # from the system, and may remove any packages
    # that depend on rpcbind. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "rpcbind"

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

Remediation Puppet snippet ⇲

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

    include remove_rpcbind

    class remove_rpcbind {
      package { 'rpcbind':
        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_rpcbind_removed

    - name: 'Uninstall rpcbind Package: Ensure rpcbind is removed'
      ansible.builtin.package:
        name: rpcbind
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_rpcbind_removed

#### Rule Disable rpcbind Service [ref]

The rpcbind utility maps RPC services to the ports on which they listen. RPC processes notify rpcbind when they start, registering the ports they are listening on and the RPC program numbers they expect to serve. The rpcbind service redirects the client to the proper port number so it can communicate with the requested service. If the system does not require RPC (such as for NFS servers) then this service should be disabled. The `rpcbind` service can be disabled with the following command:

    $ sudo systemctl mask --now rpcbind.service

Rationale: | If the system does not require rpc based services, it is recommended that rpcbind be disabled to reduce the attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_service_rpcbind_disabled

References:

cis | 2.1.12
pcidss4 | 2.2.4, 2.2

Remediation Puppet snippet ⇲

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

    include disable_rpcbind

    class disable_rpcbind {
      service {'rpcbind':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - service_rpcbind_disabled

    - name: Disable rpcbind Service - Disable service rpcbind
      block:

      - name: Disable rpcbind Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable rpcbind Service - Ensure rpcbind.service is Masked
        ansible.builtin.systemd:
          name: rpcbind.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("rpcbind.service", multiline=True)

      - name: Unit Socket Exists - rpcbind.socket
        ansible.builtin.command: systemctl -q list-unit-files rpcbind.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable rpcbind Service - Disable Socket rpcbind
        ansible.builtin.systemd:
          name: rpcbind.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("rpcbind.socket", multiline=True)
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - service_rpcbind_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["rpcbind"]

Group Configure NFS Clients Group contains 1 group and 1 rule
[ref] The steps in this section are appropriate for systems which operate as NFS clients.
Group Disable NFS Server Daemons Group contains 1 rule
[ref] There is no need to run the NFS server daemons `nfs` and `rpcsvcgssd` except on a small number of properly secured systems designated as NFS servers. Ensure that these daemons are turned off on clients.

#### Rule Disable Network File System (nfs) [ref]

The Network File System (NFS) service allows remote hosts to mount and interact with shared filesystems on the local system. If the local system is not designated as a NFS server then this service should be disabled. The `nfs-server` service can be disabled with the following command:

    $ sudo systemctl mask --now nfs-server.service

Rationale: | Unnecessary services should be disabled to decrease the attack surface of the system.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_nfs_disabled

References:

cis-csc | 11, 12, 14, 15, 16, 18, 3, 5
cobit5 | DSS05.02, DSS05.04, DSS05.05, DSS05.07, 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
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-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.PT-3
cis | 2.1.9

Remediation Puppet snippet ⇲

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

    include disable_nfs-server

    class disable_nfs-server {
      service {'nfs-server':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_nfs_disabled
      - unknown_severity

    - name: Disable Network File System (nfs) - Disable service nfs-server
      block:

      - name: Disable Network File System (nfs) - Collect systemd Services Present in
          the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Network File System (nfs) - Ensure nfs-server.service is Masked
        ansible.builtin.systemd:
          name: nfs-server.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("nfs-server.service", multiline=True)

      - name: Unit Socket Exists - nfs-server.socket
        ansible.builtin.command: systemctl -q list-unit-files nfs-server.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Network File System (nfs) - Disable Socket nfs-server
        ansible.builtin.systemd:
          name: nfs-server.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("nfs-server.socket", multiline=True)
      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
      - no_reboot_needed
      - service_nfs_disabled
      - special_service_block
      - unknown_severity
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["nfs-server"]

#### Rule Uninstall nfs-kernel-server Package [ref]

The `nfs-kernel-server` package can be removed with the following command:

    $ apt-get remove nfs-kernel-server

Rationale: | If the system does not export NFS shares or act as an NFS client, it is recommended that these services be removed to reduce the remote attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_nfs-kernel-server_removed

References:

cis | 2.1.9

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove nfs-kernel-server
    # from the system, and may remove any packages
    # that depend on nfs-kernel-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "nfs-kernel-server"

Remediation Puppet snippet ⇲

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

    include remove_nfs-kernel-server

    class remove_nfs-kernel-server {
      package { 'nfs-kernel-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall nfs-kernel-server Package: Ensure nfs-kernel-server is removed'
      ansible.builtin.package:
        name: nfs-kernel-server
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_nfs-kernel-server_removed

Group Network Time Protocol Group contains 10 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
cis | 2.3.1.1
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 Install the systemd_timesyncd Service [ref]

The systemd_timesyncd service should be installed.
Rationale: | Time synchronization (using NTP) is required by almost all network and administrative tasks (syslog, cryptographic based services (authentication, etc.), etc.). systemd_timesyncd is a part of the systemd suite and acts as a NTP client.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_timesyncd_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.4
cis | 2.3.1.1

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 "systemd-timesyncd"

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

Remediation Puppet snippet ⇲

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

    include install_systemd-timesyncd

    class install_systemd-timesyncd {
      package { 'systemd-timesyncd':
        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.4
      - enable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_timesyncd_installed

    - name: Ensure systemd-timesyncd is installed
      ansible.builtin.package:
        name: systemd-timesyncd
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4
      - enable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_timesyncd_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "systemd-timesyncd"
    version = "*"

#### Rule The Chronyd service is enabled [ref]

chrony is a daemon which implements the Network Time Protocol (NTP) 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. To enable Chronyd service, you can run: `# systemctl enable chronyd.service` This recommendation only applies if chrony is in use on the system.

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_service_chronyd_enabled

References:

os-srg | SRG-OS-000355-GPOS-00143
anssi | R71
cis | 2.3.1.1
ism | 0988, 1405

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}' 'chrony' 2>/dev/null | grep -q '^installed$'; }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'chrony.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'chrony.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'chrony.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_chrony

    class enable_chrony {
      service {'chrony':
        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:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_chronyd_enabled

    - name: The Chronyd service is enabled - Enable service chrony
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: The Chronyd service is enabled - Enable Service chrony
        ansible.builtin.systemd:
          name: chrony
          enabled: true
          state: started
          masked: false
        when:
        - '"chrony" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_chronyd_enabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["chrony"]

#### Rule Enable systemd_timesyncd Service [ref]

The `systemd_timesyncd` service can be enabled with the following command:

    $ sudo systemctl enable systemd_timesyncd.service

Rationale:

Enabling the `systemd_timesyncd` service ensures that this host uses the ntp protocol to fetch time data from a ntp server. Synchronizing time is essential for authentication services such as Kerberos, but it is also important for maintaining accurate logs and auditing possible security breaches.
Additional information on Ubuntu network time protocol is available at https://help.ubuntu.com/lts/serverguide/NTP.html.en.

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_service_timesyncd_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), AU-8(1)(a)
nist-csf | PR.PT-1
pcidss | Req-10.4
cis | 2.3.1.1
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$' && { ( ! ( dpkg-query --show --showformat='${db:Status-Status}' 'chrony' 2>/dev/null | grep -q '^installed$' ) && ! ( dpkg-query --show --showformat='${db:Status-Status}' 'ntp' 2>/dev/null | grep -q '^installed$' ) ); }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'systemd-timesyncd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'systemd-timesyncd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'systemd-timesyncd.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_systemd-timesyncd

    class enable_systemd-timesyncd {
      service {'systemd-timesyncd':
        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-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.1
      - enable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_timesyncd_enabled

    - name: Enable systemd_timesyncd Service - Enable service systemd-timesyncd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable systemd_timesyncd Service - Enable Service systemd-timesyncd
        ansible.builtin.systemd:
          name: systemd-timesyncd
          enabled: true
          state: started
          masked: false
        when:
        - '"systemd" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.1
      - enable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_timesyncd_enabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( not ( "chrony" in ansible_facts.packages ) and not ( "ntp" in ansible_facts.packages
        ) )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["systemd-timesyncd"]

#### Rule The Chronyd service is disabled [ref]

The `chrony` service can be disabled with the following command:

    $ sudo systemctl mask --now chrony.service

Rationale: | Disabling the `chrony` service ensures that there is only single one time service running.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_chronyd_disabled

References:

cis | 2.3.1.1

Remediation Puppet snippet ⇲

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

    include disable_chrony

    class disable_chrony {
      service {'chrony':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_chronyd_disabled

    - name: The Chronyd service is disabled - Disable service chrony
      block:

      - name: The Chronyd service is disabled - Collect systemd Services Present in the
          System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: The Chronyd service is disabled - Ensure chrony.service is Masked
        ansible.builtin.systemd:
          name: chrony.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("chrony.service", multiline=True)

      - name: Unit Socket Exists - chrony.socket
        ansible.builtin.command: systemctl -q list-unit-files chrony.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: The Chronyd service is disabled - Disable Socket chrony
        ansible.builtin.systemd:
          name: chrony.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("chrony.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_chronyd_disabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["chrony"]

#### Rule Disable systemd_timesyncd Service [ref]

The `systemd_timesyncd` service can be disabled with the following command:

    $ sudo systemctl mask --now systemd_timesyncd.service

Rationale: | Disabling the `systemd_timesyncd` service ensures that there is only single one time service running. Additional information on Ubuntu network time protocol is available at https://ubuntu.com/server/docs/about-time-synchronisation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_timesyncd_disabled

References:

cis | 2.3.1.1

Remediation Puppet snippet ⇲

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

    include disable_systemd-timesyncd

    class disable_systemd-timesyncd {
      service {'systemd-timesyncd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_disabled

    - name: Disable systemd_timesyncd Service - Disable service systemd-timesyncd
      block:

      - name: Disable systemd_timesyncd Service - Collect systemd Services Present in
          the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable systemd_timesyncd Service - Ensure systemd-timesyncd.service is
          Masked
        ansible.builtin.systemd:
          name: systemd-timesyncd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("systemd-timesyncd.service", multiline=True)

      - name: Unit Socket Exists - systemd-timesyncd.socket
        ansible.builtin.command: systemctl -q list-unit-files systemd-timesyncd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable systemd_timesyncd Service - Disable Socket systemd-timesyncd
        ansible.builtin.systemd:
          name: systemd-timesyncd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("systemd-timesyncd.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_disabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd-timesyncd" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["systemd-timesyncd"]

#### Rule Chrony Configure Pool and Server [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_configure_pool_and_server

References:

nist | CM-6(a), AU-8(1)(a)
pcidss | Req-10.4.3
anssi | R71
cis | 2.3.3.1
ism | 0988, 1405

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.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org'

    var_multiple_time_pools='0.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org'

    config_file="/etc/chrony/chrony.conf"

    # Check and configigure servers in /etc/chrony/chrony.conf
    IFS="," read -a SERVERS <<< $var_multiple_time_servers
    for srv in "${SERVERS[@]}"
    do
       NTP_SRV=$(grep -w $srv $config_file)
       if [[ ! "$NTP_SRV" == "server "* ]]
       then
         time_server="server $srv"
         echo $time_server >> "$config_file"
       fi
    done

    # Check and configure pools in /etc/chrony/chrony.conf
    IFS="," read -a POOLS <<< $var_multiple_time_pools
    for srv in "${POOLS[@]}"
    do
       NTP_POOL=$(grep -w $srv $config_file)
       if [[ ! "$NTP_POOL" == "pool "* ]]
       then
         time_server="pool $srv"
         echo $time_server >> "$config_file"
       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-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - chronyd_configure_pool_and_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.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org
      tags:
        - always
    - name: XCCDF Value var_multiple_time_pools # promote to variable
      set_fact:
        var_multiple_time_pools: !!str 0.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org
      tags:
        - always

    - name: Chrony Configure Pool and Server - Add missing / update wrong records for
        remote time servers
      ansible.builtin.lineinfile:
        path: /etc/chrony/chrony.conf
        regexp: ^\s*\bserver\b\s*\b{{ item }}\b$
        state: present
        line: server {{ item }}
        create: true
      with_items:
      - '{{ var_multiple_time_servers.split(",") }}'
      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
      - chronyd_configure_pool_and_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Chrony Configure Pool and Server - Add missing / update wrong records for
        remote time pools
      ansible.builtin.lineinfile:
        path: /etc/chrony/chrony.conf
        regexp: ^\s*\bpool\b\s*\b{{ item }}\b$
        state: present
        line: pool {{ item }}
        create: true
      with_items:
      - '{{ var_multiple_time_pools.split(",") }}'
      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
      - chronyd_configure_pool_and_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure that chronyd is running under chrony user account [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. To ensure that chronyd is running under chrony user account, add or edit the `OPTIONS` variable in `/etc/sysconfig/chronyd` to include `-u chrony`:

    OPTIONS="-u chrony"

This recommendation only applies if chrony is in use on the system.

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_run_as_chrony_user

References:

cis | 2.3.3.2
pcidss4 | 10.6.3, 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

    if grep -q 'OPTIONS=.*' /etc/sysconfig/chronyd; then
    	# trying to solve cases where the parameter after OPTIONS
    	#may or may not be enclosed in quotes
    	sed -i -E -e 's/\s*-u\s*\w+\s*/ /' -e 's/^([\s]*OPTIONS=["]?[^"]*)("?)/\1 -u chrony\2/' /etc/sysconfig/chronyd
    else
    	echo 'OPTIONS="-u chrony"' >> /etc/sysconfig/chronyd
    fi

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

#### Rule Ensure a Single Time Synchronization Service is in Use [ref]

The system must have exactly one active time synchronization service to avoid conflicts and ensure consistent time synchronization. Only one of the following services should be enabled and active at any time:

- chrony - A versatile NTP implementation
- systemd-timesyncd - A lightweight NTP client

Having zero active time synchronization services leaves the system without accurate time synchronization, while having multiple active services can lead to unexpected and unreliable results.
Warning: This rule does not come with a remediation. There are specific rules for enabling each time synchronization service, which should be used instead.

Rationale:

Running multiple time synchronization services simultaneously can lead to conflicts in time synchronization, unpredictable behavior, and unreliable results. A single service ensures consistent and accurate time synchronization. Having no active time synchronization service leaves the system without accurate time synchronization, which can affect security mechanisms, log consistency, and forensic investigations.

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

References:

cis | 2.3.1.1

#### Rule Configure Systemd Timesyncd Servers [ref]

`systemd-timesyncd` is a daemon that has been added for synchronizing the system clock across the network. The `systemd-timesyncd` daemon implements: - Implements an SNTP client - Runs with minimal privileges - Saves the current clock to disk every time a new NTP sync has been acquired - Is hooked up with networkd to only operate when network connectivity is available Add or edit server or pool lines to `/etc/systemd/timesyncd.conf` as appropriate:

    server <remote-server>

Multiple servers may be configured.

Rationale: | Configuring `systemd-timesyncd` ensures time synchronization is working properly.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_timesyncd_configured

References:

pcidss | Req-10.4.3
cis | 2.3.2.1

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}' 'systemd' 2>/dev/null | grep -q '^installed$'; }; then

    var_multiple_time_servers='0.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org'

    IFS=',' read -r -a time_servers_array <<< "$var_multiple_time_servers"
    preferred_ntp_servers_array=("${time_servers_array[@]:0:2}")
    preferred_ntp_servers=$( echo "${preferred_ntp_servers_array[@]}"|sed -e 's/\s\+/,/g' )
    fallback_ntp_servers_array=("${time_servers_array[@]:2}")
    fallback_ntp_servers=$( echo "${fallback_ntp_servers_array[@]}"|sed -e 's/\s\+/,/g' )

    IFS=" " mapfile -t current_cfg_arr < <(ls -1 /etc/systemd/timesyncd.d/* /etc/systemd/timesyncd.conf.d/* 2>/dev/null)

    config_file="/etc/systemd/timesyncd.d/oscap-remedy.conf"

    current_cfg_arr+=( "/etc/systemd/timesyncd.conf" )
    # Comment existing NTP FallbackNTP settings
    for current_cfg in "${current_cfg_arr[@]}"
    do
        sed -i 's/^NTP/#&/g' "$current_cfg"
        sed -i 's/^FallbackNTP/#&/g' "$current_cfg"
    done

    # Create /etc/systemd/timesyncd.d if it doesn't exist
    if [ ! -d "/etc/systemd/timesyncd.d" ]
    then
        mkdir /etc/systemd/timesyncd.d
    fi

    # Set primary fallback NTP servers in drop-in configuration
    echo "NTP=$preferred_ntp_servers" >> "$config_file"
    echo "FallbackNTP=$fallback_ntp_servers" >> "$config_file"

    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:
      - PCI-DSS-Req-10.4.3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_configured
    - name: XCCDF Value var_multiple_time_servers # promote to variable
      set_fact:
        var_multiple_time_servers: !!str 0.debian.pool.ntp.org,1.debian.pool.ntp.org,2.debian.pool.ntp.org,3.debian.pool.ntp.org
      tags:
        - always

    - name: Configure Systemd Timesyncd Servers - Set Primary NTP Servers
      ansible.builtin.set_fact:
        preferred_ntp_servers: '{{ var_multiple_time_servers.split(",") | slice(2)| first
          | join(",") }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.4.3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_configured

    - name: Configure Systemd Timesyncd Servers - Set Fallback NTP Servers
      ansible.builtin.set_fact:
        fallback_ntp_servers: '{{ var_multiple_time_servers.split(",") | slice(2)| list
          | last | join(",") }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.4.3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_configured

    - name: Configure Systemd Timesyncd Servers - Add missing / update wrong records for
        NTP servers
      ansible.builtin.lineinfile:
        path: /etc/systemd/timesyncd.d/oscap-remedy.conf
        regexp: ^\s*NTP\s*=
        state: present
        line: NTP={{ preferred_ntp_servers }}
        create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.4.3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_configured

    - name: Configure Systemd Timesyncd Servers - Add missing / update wrong records for
        fallback servers
      ansible.builtin.lineinfile:
        path: /etc/systemd/timesyncd.d/oscap-remedy.conf
        regexp: ^\s*FallbackNTP\s*=
        state: present
        line: FallbackNTP={{ fallback_ntp_servers }}
        create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.4.3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_timesyncd_configured

Group Obsolete Services Group contains 6 groups and 13 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 12 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 2 rules
[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 12.

#### 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
cis | 2.1.19
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

#### Rule Disable xinetd Service [ref]

The `xinetd` service can be disabled with the following command:

    $ sudo systemctl mask --now xinetd.service

Rationale: | The xinetd service provides a dedicated listener service for some programs, which is no longer necessary for commonly-used network services. Disabling it ensures that these uncommon services are not running, and also prevents attacks against xinetd itself.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_xinetd_disabled

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
cui | 3.4.7
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
cis | 2.1.19
ism | 1409

Remediation Puppet snippet ⇲

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

    include disable_xinetd

    class disable_xinetd {
      service {'xinetd':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.7
      - 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
      - service_xinetd_disabled

    - name: Disable xinetd Service - Disable service xinetd
      block:

      - name: Disable xinetd Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable xinetd Service - Ensure xinetd.service is Masked
        ansible.builtin.systemd:
          name: xinetd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("xinetd.service", multiline=True)

      - name: Unit Socket Exists - xinetd.socket
        ansible.builtin.command: systemctl -q list-unit-files xinetd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable xinetd Service - Disable Socket xinetd
        ansible.builtin.systemd:
          name: xinetd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("xinetd.socket", multiline=True)
      tags:
      - NIST-800-171-3.4.7
      - 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
      - service_xinetd_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["xinetd"]

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 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
cis | 2.1.10
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

#### Rule Disable ypserv Service [ref]

The `ypserv` service, which allows the system to act as a client in a NIS or NIS+ domain, should be disabled. The `ypserv` service can be disabled with the following command:

    $ sudo systemctl mask --now ypserv.service

Rationale: | Disabling the `ypserv` service ensures the system is not acting as a client in a NIS or NIS+ domain. This service should be disabled unless in use.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_ypserv_disabled

References:

cis | 2.1.10

Remediation Puppet snippet ⇲

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

    include disable_ypserv

    class disable_ypserv {
      service {'ypserv':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - medium_severity
      - no_reboot_needed
      - service_ypserv_disabled

    - name: Disable ypserv Service - Disable service ypserv
      block:

      - name: Disable ypserv Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable ypserv Service - Ensure ypserv.service is Masked
        ansible.builtin.systemd:
          name: ypserv.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("ypserv.service", multiline=True)

      - name: Unit Socket Exists - ypserv.socket
        ansible.builtin.command: systemctl -q list-unit-files ypserv.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable ypserv Service - Disable Socket ypserv
        ansible.builtin.systemd:
          name: ypserv.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("ypserv.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_ypserv_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["ypserv"]

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 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
cis | 2.2.2
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

#### Rule Remove Rsh Trust Files [ref]

The files `/etc/hosts.equiv` and `~/.rhosts` (in each user's home directory) list remote hosts and users that are trusted by the local system when using the rshd daemon. To remove these files, run the following command to delete them from any location:

    $ sudo rm /etc/hosts.equiv

    $ rm ~/.rhosts

Rationale: | This action is only meaningful if `.rhosts` support is permitted through PAM. Trust files are convenient, but when used in conjunction with the R-services, they can allow unauthenticated access to a system.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_no_rsh_trust_files

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
cis | 7.2.10

Group Chat/Messaging Services Group contains 1 rule
[ref] The talk software makes it possible for users to send and receive messages across systems through a terminal session.

#### 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
cis | 2.2.3
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 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 12.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_inetutils-telnet_removed

References:

cis | 2.2.4

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove inetutils-telnet
    # from the system, and may remove any packages
    # that depend on inetutils-telnet. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "inetutils-telnet"

Remediation Puppet snippet ⇲

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

    include remove_inetutils-telnet

    class remove_inetutils-telnet {
      package { 'inetutils-telnet':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Remove telnet Clients: Ensure inetutils-telnet is removed'
      ansible.builtin.package:
        name: inetutils-telnet
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_inetutils-telnet_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 12.
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
cis | 2.2.4
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
cis | 2.1.16
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 Disable tftp Service [ref]

The `tftp` service should be disabled. The `tftp` service can be disabled with the following command:

    $ sudo systemctl mask --now tftp.service

Rationale: | Disabling the `tftp` service ensures the system is not acting as a TFTP server, which does not provide encryption or authentication.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_service_tftp_disabled

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
cis | 2.1.16

Remediation Puppet snippet ⇲

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

    include disable_tftp

    class disable_tftp {
      service {'tftp':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_tftp_disabled

    - name: Disable tftp Service - Disable service tftp
      block:

      - name: Disable tftp Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable tftp Service - Ensure tftp.service is Masked
        ansible.builtin.systemd:
          name: tftp.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("tftp.service", multiline=True)

      - name: Unit Socket Exists - tftp.socket
        ansible.builtin.command: systemctl -q list-unit-files tftp.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable tftp Service - Disable Socket tftp
        ansible.builtin.systemd:
          name: tftp.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("tftp.socket", multiline=True)
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_tftp_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["tftp"]

#### Rule Uninstall rsync Package [ref]

The rsyncd service can be used to synchronize files between systems over network links. The `rsync` package can be removed with the following command:

    $ apt-get remove rsync

Rationale: | The rsyncd service presents a security risk as it uses unencrypted protocols for communication.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsync_removed

References:

cis | 2.1.13

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove rsync
    # from the system, and may remove any packages
    # that depend on rsync. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "rsync"

Remediation Puppet snippet ⇲

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

    include remove_rsync

    class remove_rsync {
      package { 'rsync':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall rsync Package: Ensure rsync is removed'
      ansible.builtin.package:
        name: rsync
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsync_removed

#### Rule Ensure rsyncd service is disabled [ref]

The `rsyncd` service can be disabled with the following command:

    $ sudo systemctl mask --now rsyncd.service

Rationale: | The rsyncd service presents a security risk as it uses unencrypted protocols for communication.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_rsyncd_disabled

References:

cis | 2.1.13
pcidss4 | 2.2.4, 2.2

Remediation Puppet snippet ⇲

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

    include disable_rsyncd

    class disable_rsyncd {
      service {'rsyncd':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_rsyncd_disabled

    - name: Ensure rsyncd service is disabled - Disable service rsyncd
      block:

      - name: Ensure rsyncd service is disabled - Collect systemd Services Present in
          the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Ensure rsyncd service is disabled - Ensure rsyncd.service is Masked
        ansible.builtin.systemd:
          name: rsyncd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("rsyncd.service", multiline=True)

      - name: Unit Socket Exists - rsyncd.socket
        ansible.builtin.command: systemctl -q list-unit-files rsyncd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Ensure rsyncd service is disabled - Disable Socket rsyncd
        ansible.builtin.systemd:
          name: rsyncd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("rsyncd.socket", multiline=True)
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_rsyncd_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["rsyncd"]

Group Print Support Group contains 2 rules

[ref] The Common Unix Printing System (CUPS) service provides both local and network printing support. A system running the CUPS service can accept print jobs from other systems, process them, and send them to the appropriate printer. It also provides an interface for remote administration through a web browser. The CUPS service is installed and activated by default. The project homepage and more detailed documentation are available at http://www.cups.org.

#### Rule Uninstall CUPS Package [ref]

The `cups` package can be removed with the following command:

    $ apt-get remove cups

Rationale: | If the system does not need to print jobs or accept print jobs from other systems, it is recommended that CUPS be removed to reduce the potential attack surface.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_cups_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
cis | 2.1.11

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove cups
    # from the system, and may remove any packages
    # that depend on cups. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "cups"

Remediation Puppet snippet ⇲

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

    include remove_cups

    class remove_cups {
      package { 'cups':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall CUPS Package: Ensure cups is removed'
      ansible.builtin.package:
        name: cups
        state: absent
      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
      - no_reboot_needed
      - package_cups_removed
      - unknown_severity

#### Rule Disable the CUPS Service [ref]

The `cups` service can be disabled with the following command:

    $ sudo systemctl mask --now cups.service

Rationale: | Turn off unneeded services to reduce attack surface.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_cups_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
cis | 2.1.11

Remediation Puppet snippet ⇲

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

    include disable_cups

    class disable_cups {
      service {'cups':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_cups_disabled
      - unknown_severity

    - name: Disable the CUPS Service - Disable service cups
      block:

      - name: Disable the CUPS Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable the CUPS Service - Ensure cups.service is Masked
        ansible.builtin.systemd:
          name: cups.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("cups.service", multiline=True)

      - name: Unit Socket Exists - cups.socket
        ansible.builtin.command: systemctl -q list-unit-files cups.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable the CUPS Service - Disable Socket cups
        ansible.builtin.systemd:
          name: cups.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("cups.socket", multiline=True)
      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
      - no_reboot_needed
      - service_cups_disabled
      - special_service_block
      - unknown_severity
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["cups"]

Group Proxy Server Group contains 1 group and 2 rules

[ref] A proxy server is a very desirable target for a potential adversary because much (or all) sensitive data for a given infrastructure may flow through it. Therefore, if one is required, the system acting as a proxy server should be dedicated to that purpose alone and be stored in a physically secure location. The system's default proxy server software is Squid, and provided in an RPM package of the same name.

Group Disable Squid if Possible Group contains 2 rules
[ref] If Squid was installed and activated, but the system does not need to act as a proxy server, then it should be disabled and removed.

#### Rule Uninstall squid Package [ref]

The `squid` package can be removed with the following command:

     $ apt-get remove squid

Rationale: | If there is no need to make the proxy server software available, removing it provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_squid_removed

References:

cis | 2.1.17
ism | 1409

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove squid
    # from the system, and may remove any packages
    # that depend on squid. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "squid"

Remediation Puppet snippet ⇲

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

    include remove_squid

    class remove_squid {
      package { 'squid':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall squid Package: Ensure squid is removed'
      ansible.builtin.package:
        name: squid
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_squid_removed
      - unknown_severity

#### Rule Disable Squid [ref]

The `squid` service can be disabled with the following command:

    $ sudo systemctl mask --now squid.service

Rationale: | Running proxy server software provides a network-based avenue of attack, and should be removed if not needed.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_service_squid_disabled

References:

cis | 2.1.17
ism | 1409

Remediation Puppet snippet ⇲

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

    include disable_squid

    class disable_squid {
      service {'squid':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - no_reboot_needed
      - service_squid_disabled
      - unknown_severity

    - name: Disable Squid - Disable service squid
      block:

      - name: Disable Squid - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Squid - Ensure squid.service is Masked
        ansible.builtin.systemd:
          name: squid.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("squid.service", multiline=True)

      - name: Unit Socket Exists - squid.socket
        ansible.builtin.command: systemctl -q list-unit-files squid.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Squid - Disable Socket squid
        ansible.builtin.systemd:
          name: squid.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("squid.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - service_squid_disabled
      - special_service_block
      - unknown_severity
      when: ( "squid" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["squid"]

Group Samba(SMB) Microsoft Windows File Sharing Server Group contains 1 group and 2 rules

[ref] When properly configured, the Samba service allows Linux systems to provide file and print sharing to Microsoft Windows systems. There are two software packages that provide Samba support. The first, `samba-client`, provides a series of command line tools that enable a client system to access Samba shares. The second, simply labeled `samba`, provides the Samba service. It is this second package that allows a Linux system to act as an Active Directory server, a domain controller, or as a domain member. Only the `samba-client` package is installed by default.

Group Disable Samba if Possible Group contains 2 rules
[ref] Even after the Samba server package has been installed, it will remain disabled. Do not enable this service unless it is absolutely necessary to provide Microsoft Windows file and print sharing functionality.

#### Rule Uninstall Samba Package [ref]

The `samba` package can be removed with the following command:

     $ apt-get remove samba

Rationale: | If there is no need to make the Samba software available, removing it provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_samba_removed

References:

cis | 2.1.14

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove samba
    # from the system, and may remove any packages
    # that depend on samba. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "samba"

Remediation Puppet snippet ⇲

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

    include remove_samba

    class remove_samba {
      package { 'samba':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall Samba Package: Ensure samba is removed'
      ansible.builtin.package:
        name: samba
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_samba_removed
      - unknown_severity

#### Rule Disable Samba [ref]

The `smb` service can be disabled with the following command:

    $ sudo systemctl mask --now smb.service

Rationale: | Running a Samba server provides a network-based avenue of attack, and should be disabled if not needed.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_service_smb_disabled

References:

cis | 2.1.14

Remediation Puppet snippet ⇲

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

    include disable_smb

    class disable_smb {
      service {'smb':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - service_smb_disabled

    - name: Disable Samba - Disable service smb
      block:

      - name: Disable Samba - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Samba - Ensure smb.service is Masked
        ansible.builtin.systemd:
          name: smb.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("smb.service", multiline=True)

      - name: Unit Socket Exists - smb.socket
        ansible.builtin.command: systemctl -q list-unit-files smb.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable Samba - Disable Socket smb
        ansible.builtin.systemd:
          name: smb.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("smb.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - service_smb_disabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["smb"]

Group SNMP Server Group contains 1 group and 2 rules
[ref] The Simple Network Management Protocol allows administrators to monitor the state of network devices, including computers. Older versions of SNMP were well-known for weak security, such as plaintext transmission of the community string (used for authentication) and usage of easily-guessable choices for the community string.
Group Disable SNMP Server if Possible Group contains 2 rules
[ref] The system includes an SNMP daemon that allows for its remote monitoring, though it not installed by default. If it was installed and activated but is not needed, the software should be disabled and removed.

#### Rule Uninstall net-snmp Package [ref]

The `snmp` package provides the snmpd service. The `snmp` package can be removed with the following command:

    $ apt-get remove snmp

Rationale: | If there is no need to run SNMP server software, removing the package provides a safeguard against its activation.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_net-snmp_removed

References:

cis | 2.1.15
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove net-snmp
    # from the system, and may remove any packages
    # that depend on net-snmp. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "net-snmp"

Remediation Puppet snippet ⇲

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

    include remove_net-snmp

    class remove_net-snmp {
      package { 'net-snmp':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall net-snmp Package: Ensure net-snmp is removed'
      ansible.builtin.package:
        name: net-snmp
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_net-snmp_removed
      - unknown_severity

#### Rule Disable snmpd Service [ref]

The `snmpd` service can be disabled with the following command:

    $ sudo systemctl mask --now snmpd.service

Rationale: | Running SNMP software provides a network-based avenue of attack, and should be disabled if not needed.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_service_snmpd_disabled

References:

cis | 2.1.15
ism | 1311

Remediation Puppet snippet ⇲

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

    include disable_snmpd

    class disable_snmpd {
      service {'snmpd':
        enable => false,
        ensure => 'stopped',
      }
    }

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
      - service_snmpd_disabled

    - name: Disable snmpd Service - Disable service snmpd
      block:

      - name: Disable snmpd Service - Collect systemd Services Present in the System
        ansible.builtin.command: systemctl -q list-unit-files --type service
        register: service_exists
        changed_when: false
        failed_when: service_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable snmpd Service - Ensure snmpd.service is Masked
        ansible.builtin.systemd:
          name: snmpd.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("snmpd.service", multiline=True)

      - name: Unit Socket Exists - snmpd.socket
        ansible.builtin.command: systemctl -q list-unit-files snmpd.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable snmpd Service - Disable Socket snmpd
        ansible.builtin.systemd:
          name: snmpd.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("snmpd.socket", multiline=True)
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - service_snmpd_disabled
      - special_service_block
      when: ( "snmpd" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["snmpd"]

Group SSH Server Group contains 1 group and 25 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 20 rules
[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 Set SSH Client Alive Count Max [ref]

The SSH server sends at most `ClientAliveCountMax` messages during a SSH session and waits for a response from the SSH client. The option `ClientAliveInterval` configures timeout after each `ClientAliveCountMax` message. If the SSH server does not receive a response from the client, then the connection is considered unresponsive and terminated. For SSH earlier than v8.2, a `ClientAliveCountMax` value of `0` causes a timeout precisely when the `ClientAliveInterval` is set. Starting with v8.2, a value of `0` disables the timeout functionality completely. If the option is set to a number greater than `0`, then the session will be disconnected after `ClientAliveInterval * ClientAliveCountMax` seconds without receiving a keep alive message.

Rationale: | This ensures a user login will be terminated as soon as the `ClientAliveInterval` is reached.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_keepalive

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
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.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 | 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
pcidss | Req-8.1.8
os-srg | SRG-OS-000163-GPOS-00072, SRG-OS-000279-GPOS-00109
cis | 5.1.7
pcidss4 | 8.2.8, 8.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

    var_sshd_set_keepalive='3'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*ClientAliveCountMax\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' "ClientAliveCountMax $var_sshd_set_keepalive" > "/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.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_keepalive
    - name: XCCDF Value var_sshd_set_keepalive # promote to variable
      set_fact:
        var_sshd_set_keepalive: !!str 3
      tags:
        - always

    - name: Set SSH Client Alive Count Max
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*ClientAliveCountMax\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*ClientAliveCountMax\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*ClientAliveCountMax\s+
          line: ClientAliveCountMax {{ var_sshd_set_keepalive }}
          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.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_keepalive

#### Rule Set SSH Client Alive Interval [ref]

SSH allows administrators to set a network responsiveness timeout interval. After this interval has passed, the unresponsive client will be automatically logged out.
To set this timeout interval, edit the following line in `/etc/ssh/sshd_config` as follows:

    ClientAliveInterval 300

The timeout interval is given in seconds. For example, have a timeout of 10 minutes, set interval to 600.
If a shorter timeout has already been set for the login shell, that value will preempt any SSH setting made in `/etc/ssh/sshd_config`. Keep in mind that some processes may stop SSH from correctly detecting that the user is idle.
Warning: SSH disconnecting unresponsive clients will not have desired effect without also configuring ClientAliveCountMax in the SSH service configuration.
Warning: Following conditions may prevent the SSH session to time out:

- Remote processes on the remote machine generates output. As the output has to be transferred over the network to the client, the timeout is reset every time such transfer happens.
- Any `scp` or `sftp` activity by the same user to the host resets the timeout.

Rationale: | Terminating an idle ssh 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_sshd_set_idle_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
pcidss | Req-8.1.8
os-srg | SRG-OS-000126-GPOS-00066, SRG-OS-000163-GPOS-00072, SRG-OS-000279-GPOS-00109, SRG-OS-000395-GPOS-00175
cis | 5.1.7
pcidss4 | 8.2.8, 8.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

    sshd_idle_timeout_value='300'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*ClientAliveInterval\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' "ClientAliveInterval $sshd_idle_timeout_value" > "/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.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
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_idle_timeout
    - name: XCCDF Value sshd_idle_timeout_value # promote to variable
      set_fact:
        sshd_idle_timeout_value: !!str 300
      tags:
        - always

    - name: Set SSH Client Alive Interval
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*ClientAliveInterval\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*ClientAliveInterval\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*ClientAliveInterval\s+
          line: ClientAliveInterval {{ sshd_idle_timeout_value }}
          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.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
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_idle_timeout

#### Rule Disable Host-Based Authentication [ref]

SSH's cryptographic host-based authentication is more secure than `.rhosts` authentication. However, it is not recommended that hosts unilaterally trust one another, even within an organization.
The default SSH configuration disables host-based authentication. The appropriate configuration is used if no value is set for `HostbasedAuthentication`.
To explicitly disable host-based authentication, add or correct the following line in `/etc/ssh/sshd_config`:

    HostbasedAuthentication no

Rationale: | SSH trust relationships mean a compromise on one host can allow an attacker to move trivially to other hosts.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_disable_host_auth

References:

cis-csc | 11, 12, 14, 15, 16, 18, 3, 5, 9
cjis | 5.5.6
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.03, DSS06.06
cui | 3.1.12
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, 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.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
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 | AC-3, AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.IP-1, PR.PT-3
ospp | FIA_UAU.1
os-srg | SRG-OS-000480-GPOS-00229
cis | 5.1.10
ism | 0421, 0422, 0484, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.1, 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$'; then

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*HostbasedAuthentication\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' "HostbasedAuthentication 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.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - disable_host_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable Host-Based Authentication
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*HostbasedAuthentication\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*HostbasedAuthentication\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*HostbasedAuthentication\s+
          line: HostbasedAuthentication 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.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - disable_host_auth
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Disable SSH Access via Empty Passwords [ref]

Disallow SSH login with empty passwords. The default SSH configuration disables logins with empty passwords. The appropriate configuration is used if no value is set for `PermitEmptyPasswords`.
To explicitly disallow SSH login from accounts with empty passwords, add or correct the following line in `/etc/ssh/sshd_config`:

    PermitEmptyPasswords no

Any accounts with empty passwords should be disabled immediately, and PAM configuration should prevent users from being able to assign themselves empty passwords.

Rationale: | Configuring this setting for the SSH daemon provides additional assurance that remote login via SSH will require a password, even in the event of misconfiguration elsewhere.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_empty_passwords

References:

cis-csc | 11, 12, 13, 14, 15, 16, 18, 3, 5, 9
cjis | 5.5.6
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
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, 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 | AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.DS-5, PR.IP-1, PR.PT-3
ospp | FIA_UAU.1
pcidss | Req-2.2.4
os-srg | SRG-OS-000106-GPOS-00053, SRG-OS-000480-GPOS-00229, SRG-OS-000480-GPOS-00227
cis | 5.1.19
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*PermitEmptyPasswords\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' "PermitEmptyPasswords 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-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_empty_passwords

    - name: Disable SSH Access via Empty Passwords
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*PermitEmptyPasswords\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*PermitEmptyPasswords\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*PermitEmptyPasswords\s+
          line: PermitEmptyPasswords 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-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_empty_passwords

#### Rule Disable SSH Forwarding [ref]

The DisableForwarding parameter disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.
To explicitly disable SSHD forwarding, add or correct the following line in `/etc/ssh/sshd_config`:

    DisableForwarding yes

Rationale: | Disable ssh forwarding unless there is an operational requirement to use it. Leaving port forwarding enabled can expose the organization to security risks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_forwarding

References:

cis | 5.1.8

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*DisableForwarding\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' "DisableForwarding yes" > "/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:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_forwarding

    - name: Disable SSH Forwarding
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*DisableForwarding\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*DisableForwarding\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*DisableForwarding\s+
          line: DisableForwarding yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_forwarding

#### Rule Disable GSSAPI Authentication [ref]

Unless needed, SSH should not permit extraneous or unnecessary authentication mechanisms like GSSAPI.
The default SSH configuration disallows authentications based on GSSAPI. The appropriate configuration is used if no value is set for `GSSAPIAuthentication`.
To explicitly disable GSSAPI authentication, add or correct the following line in `/etc/ssh/sshd_config`:

    GSSAPIAuthentication no

Rationale: | GSSAPI authentication is used to provide additional authentication mechanisms to applications. Allowing GSSAPI authentication through SSH exposes the system's GSSAPI to remote hosts, increasing the attack surface of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_gssapi_auth

References:

cis-csc | 11, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.1.12
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.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-7(a), CM-7(b), CM-6(a), AC-17(a)
nist-csf | PR.IP-1
ospp | FTP_ITC_EXT.1, FCS_SSH_EXT.1.2
os-srg | SRG-OS-000364-GPOS-00151, SRG-OS-000480-GPOS-00227
cis | 5.1.9
ism | 0418, 1055, 1402

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*GSSAPIAuthentication\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' "GSSAPIAuthentication 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:
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_gssapi_auth

    - name: Disable GSSAPI Authentication
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*GSSAPIAuthentication\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*GSSAPIAuthentication\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*GSSAPIAuthentication\s+
          line: GSSAPIAuthentication no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_gssapi_auth

#### Rule Disable SSH Support for .rhosts Files [ref]

SSH can emulate the behavior of the obsolete rsh command in allowing users to enable insecure access to their accounts via `.rhosts` files.
The default SSH configuration disables support for `.rhosts`. The appropriate configuration is used if no value is set for `IgnoreRhosts`.
To explicitly disable support for .rhosts files, add or correct the following line in `/etc/ssh/sshd_config`:

    IgnoreRhosts yes

Rationale: | SSH trust relationships mean a compromise on one host can allow an attacker to move trivially to other hosts.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_rhosts

References:

cis-csc | 11, 12, 14, 15, 16, 18, 3, 5, 9
cjis | 5.5.6
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.03, DSS06.06
cui | 3.1.12
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 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.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 | AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
cis | 5.1.11
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*IgnoreRhosts\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' "IgnoreRhosts yes" > "/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.12
      - NIST-800-53-AC-17(a)
      - 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.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_rhosts

    - name: Disable SSH Support for .rhosts Files
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*IgnoreRhosts\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*IgnoreRhosts\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*IgnoreRhosts\s+
          line: IgnoreRhosts yes
          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.12
      - NIST-800-53-AC-17(a)
      - 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.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_rhosts

#### 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
cis | 5.1.20
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 Do Not Allow SSH Environment Options [ref]

Ensure that users are not able to override environment variables of the SSH daemon.
The default SSH configuration disables environment processing. The appropriate configuration is used if no value is set for `PermitUserEnvironment`.
To explicitly disable Environment options, add or correct the following `/etc/ssh/sshd_config`:

    PermitUserEnvironment no

Rationale: | SSH environment options potentially allow users to bypass access restriction in some configurations.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_do_not_permit_user_env

References:

cis-csc | 11, 3, 9
cjis | 5.5.6
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.1.12
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.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 | AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1
pcidss | Req-2.2.4
os-srg | SRG-OS-000480-GPOS-00229
cis | 5.1.21
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*PermitUserEnvironment\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' "PermitUserEnvironment 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.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - 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_do_not_permit_user_env

    - name: Do Not Allow SSH Environment Options
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*PermitUserEnvironment\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*PermitUserEnvironment\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*PermitUserEnvironment\s+
          line: PermitUserEnvironment 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.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - 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_do_not_permit_user_env

#### Rule Enable PAM [ref]

UsePAM Enables the Pluggable Authentication Module interface. If set to “yes” this will enable PAM authentication using ChallengeResponseAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. To enable PAM authentication, add or correct the following line in `/etc/ssh/sshd_config`:

    UsePAM yes

Rationale: | When UsePAM is set to yes, PAM runs through account and session types properly. This is important if you want to restrict access to services based off of IP, time or other factors of the account. Additionally, you can make sure users inherit certain environment variables on login or disallow access to the server.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_enable_pam

References:

os-srg | SRG-OS-000125-GPOS-00065
cis | 5.1.22
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*UsePAM\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' "UsePAM yes" > "/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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pam

    - name: Enable PAM
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*UsePAM\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*UsePAM\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*UsePAM\s+
          line: UsePAM yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pam

#### Rule Enable SSH Warning Banner [ref]

To enable the warning banner and ensure it is consistent across the system, add or correct the following line in `/etc/ssh/sshd_config`:

    Banner /etc/issue.net

Another section contains information on how to create an appropriate system-wide warning banner.

Rationale: | The warning message reinforces policy awareness during the logon process and facilitates possible legal action against attackers. Alternatively, systems whose ownership should not be obvious should ensure usage of a banner that does not provide easy attribution.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_enable_warning_banner_net

References:

cjis | 5.5.6
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.9
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.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 | AC-8(a), AC-8(c), AC-17(a), CM-6(a)
nist-csf | PR.AC-7
os-srg | SRG-OS-000023-GPOS-00006, SRG-OS-000228-GPOS-00088
cis | 5.1.5

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*Banner\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' "Banner /etc/issue.net" > "/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.9
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner_net

    - name: Enable SSH Warning Banner
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*Banner\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*Banner\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*Banner\s+
          line: Banner /etc/issue.net
          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.9
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner_net

#### Rule Limit Users' SSH Access [ref]

By default, the SSH configuration allows any user with an account to access the system. There are several options available to limit which users and group can access the system via SSH. It is recommended that at least one of the following options be leveraged: - AllowUsers variable gives the system administrator the option of allowing specific users to ssh into the system. The list consists of space separated user names. Numeric user IDs are not recognized with this variable. If a system administrator wants to restrict user access further by specifically allowing a user's access only from a particular host, the entry can be specified in the form of user@host. - AllowGroups variable gives the system administrator the option of allowing specific groups of users to ssh into the system. The list consists of space separated group names. Numeric group IDs are not recognized with this variable. - DenyUsers variable gives the system administrator the option of denying specific users to ssh into the system. The list consists of space separated user names. Numeric user IDs are not recognized with this variable. If a system administrator wants to restrict user access further by specifically denying a user's access from a particular host, the entry can be specified in the form of user@host. - DenyGroups variable gives the system administrator the option of denying specific groups of users to ssh into the system. The list consists of space separated group names. Numeric group IDs are not recognized with this variable.
Warning: Automated remediation is not available for this configuration check because each system has unique user names and group names.

Rationale: | Specifying which accounts are allowed SSH access into the system reduces the possibility of unauthorized access to the system.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_limit_user_access

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.1.12
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
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 | AC-3, CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.PT-3
pcidss | Req-2.2.4
cis | 5.1.4
pcidss4 | 2.2.6, 2.2

#### Rule Ensure SSH LoginGraceTime is configured [ref]

The `LoginGraceTime` parameter to the SSH server specifies the time allowed for successful authentication to the SSH server. The longer the Grace period is the more open unauthenticated connections can exist. Like other session controls in this session the Grace Period should be limited to appropriate limits to ensure the service is available for needed access.
Rationale: | Setting the `LoginGraceTime` parameter to a low number will minimize the risk of successful brute force attacks to the SSH server. It will also limit the number of concurrent unauthenticated connections.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_login_grace_time

References:

cis | 5.1.13
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

    var_sshd_set_login_grace_time='60'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*LoginGraceTime\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' "LoginGraceTime $var_sshd_set_login_grace_time" > "/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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_login_grace_time
    - name: XCCDF Value var_sshd_set_login_grace_time # promote to variable
      set_fact:
        var_sshd_set_login_grace_time: !!str 60
      tags:
        - always

    - name: Ensure SSH LoginGraceTime is configured
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*LoginGraceTime\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*LoginGraceTime\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*LoginGraceTime\s+
          line: LoginGraceTime {{ var_sshd_set_login_grace_time }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_login_grace_time

#### Rule Set LogLevel to INFO [ref]

The INFO parameter specifies that record login and logout activity will be logged.
The default SSH configuration sets the log level to INFO. The appropriate configuration is used if no value is set for `LogLevel`.
To explicitly specify the log level in SSH, add or correct the following line in `/etc/ssh/sshd_config`:

    LogLevel INFO

Rationale:

SSH provides several logging levels with varying amounts of verbosity. `DEBUG` is specifically not recommended other than strictly for debugging SSH communications since it provides so much data that it is difficult to identify important security information. `INFO` level is the basic level that only records login activity of SSH users. In many situations, such as Incident Response, it is important to determine when a particular user was active on a system. The logout record can eliminate those users who disconnected, which helps narrow the field.

Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_loglevel_info

References:

nist | AC-17(a), CM-6(a)
cis | 5.1.14
ism | 1409

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*LogLevel\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' "LogLevel INFO" > "/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:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_loglevel_info

    - name: Set LogLevel to INFO
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*LogLevel\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*LogLevel\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*LogLevel\s+
          line: LogLevel INFO
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_loglevel_info

#### Rule Set SSH authentication attempt limit [ref]

The `MaxAuthTries` parameter specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. to set MaxAUthTries edit `/etc/ssh/sshd_config` as follows:

    MaxAuthTries 4

Rationale: | Setting the MaxAuthTries parameter to a low number will minimize the risk of successful brute force attacks to the SSH server.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_max_auth_tries

References:

cis | 5.1.16
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
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

    sshd_max_auth_tries_value='4'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*MaxAuthTries\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' "MaxAuthTries $sshd_max_auth_tries_value" > "/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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_max_auth_tries
    - name: XCCDF Value sshd_max_auth_tries_value # promote to variable
      set_fact:
        sshd_max_auth_tries_value: !!str 4
      tags:
        - always

    - name: Set SSH authentication attempt limit
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*MaxAuthTries\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*MaxAuthTries\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*MaxAuthTries\s+
          line: MaxAuthTries {{ sshd_max_auth_tries_value }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_max_auth_tries

#### Rule Set SSH MaxSessions limit [ref]

The `MaxSessions` parameter specifies the maximum number of open sessions permitted from a given connection. To set MaxSessions edit `/etc/ssh/sshd_config` as follows:

    MaxSessions 10

Rationale: | To protect a system from denial of service due to a large number of concurrent sessions, use the rate limiting function of MaxSessions to protect availability of sshd logins and prevent overwhelming the daemon.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_max_sessions

References:

cis | 5.1.17
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

    var_sshd_max_sessions='10'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*MaxSessions\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' "MaxSessions $var_sshd_max_sessions" > "/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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_max_sessions
    - name: XCCDF Value var_sshd_max_sessions # promote to variable
      set_fact:
        var_sshd_max_sessions: !!str 10
      tags:
        - always

    - name: Set SSH MaxSessions limit
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*MaxSessions\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*MaxSessions\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*MaxSessions\s+
          line: MaxSessions {{ var_sshd_max_sessions }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_max_sessions

#### Rule Ensure SSH MaxStartups is configured [ref]

The MaxStartups parameter specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. To configure MaxStartups, you should add or edit the following line in the `/etc/ssh/sshd_config` file:

    MaxStartups 10:30:60

Rationale: | To protect a system from denial of service due to a large number of pending authentication connection attempts, use the rate limiting function of MaxStartups to protect availability of sshd logins and prevent overwhelming the daemon.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_maxstartups

References:

cis | 5.1.18
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

    var_sshd_set_maxstartups='10:30:60'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*MaxStartups\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' "MaxStartups $var_sshd_set_maxstartups" > "/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:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_maxstartups
    - name: XCCDF Value var_sshd_set_maxstartups # promote to variable
      set_fact:
        var_sshd_set_maxstartups: !!str 10:30:60
      tags:
        - always

    - name: Ensure SSH MaxStartups is configured
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*MaxStartups\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*MaxStartups\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*MaxStartups\s+
          line: MaxStartups {{ var_sshd_set_maxstartups }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_set_maxstartups

#### Rule Use Only Strong Ciphers [ref]

Limit the ciphers to strong algorithms. Counter (CTR) mode is also preferred over cipher-block chaining (CBC) mode. The following line in `/etc/ssh/sshd_config` demonstrates use of those ciphers:

    Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

The man page `sshd_config(5)` contains a list of supported ciphers.

Rationale:

Based on research conducted at various institutions, it was determined that the symmetric portion of the SSH Transport Protocol (as described in RFC 4253) has security weaknesses that allowed recovery of up to 32 bits of plaintext from a block of ciphertext that was encrypted with the Cipher Block Chaining (CBD) method. From that research, new Counter mode algorithms (as described in RFC4344) were designed that are not vulnerable to these types of attacks and these algorithms are now recommended for standard use.

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

References:

cis | 5.1.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

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*Ciphers\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' "Ciphers aes128-ctr,aes192-ctr,aes256-ctr,chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com" > "/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

#### Rule Use Only Strong Key Exchange algorithms [ref]

Limit the Key Exchange to strong algorithms. The following line in `/etc/ssh/sshd_config` demonstrates use of those:

    KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256

Rationale: | Key exchange is any method in cryptography by which cryptographic keys are exchanged between two parties, allowing use of a cryptographic algorithm. If the sender and receiver wish to exchange encrypted messages, each must be equipped to encrypt messages to be sent and decrypt messages received
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_use_strong_kex

References:

pcidss | Req-2.3
cis | 5.1.12
pcidss4 | 2.2.7, 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

    sshd_strong_kex='sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*KexAlgorithms\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' "KexAlgorithms $sshd_strong_kex" > "/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:
      - PCI-DSS-Req-2.3
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_use_strong_kex
    - name: XCCDF Value sshd_strong_kex # promote to variable
      set_fact:
        sshd_strong_kex: !!str sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
      tags:
        - always

    - name: Use Only Strong Key Exchange algorithms
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*KexAlgorithms\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*KexAlgorithms\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*KexAlgorithms\s+
          line: KexAlgorithms {{ sshd_strong_kex }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-2.3
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_use_strong_kex

#### Rule Use Only Strong MACs [ref]

Limit the MACs to strong hash algorithms. The following line in `/etc/ssh/sshd_config` demonstrates use of those MACs:

    MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256

Rationale:

MD5 and 96-bit MAC algorithms are considered weak and have been shown to increase exploitability in SSH downgrade attacks. Weak algorithms continue to have a great deal of attention as a weak spot that can be exploited with expanded computing power. An attacker that breaks the algorithm could take advantage of a MiTM position to decrypt the SSH tunnel and capture credentials and information

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

References:

nist | AC-17 (2)
os-srg | SRG-OS-000250-GPOS-00093
cis | 5.1.15

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

    sshd_strong_macs='hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256'

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*MACs\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' "MACs $sshd_strong_macs" > "/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:
      - NIST-800-53-AC-17 (2)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_use_strong_macs
    - name: XCCDF Value sshd_strong_macs # promote to variable
      set_fact:
        sshd_strong_macs: !!str hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256
      tags:
        - always

    - name: Use Only Strong MACs
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*MACs\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*MACs\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*MACs\s+
          line: MACs {{ sshd_strong_macs }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17 (2)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_use_strong_macs

#### 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
cis | 5.1.1

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 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
cis | 5.1.1

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 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
cis | 5.1.1
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
cis | 5.1.2
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
cis | 5.1.3
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 X Window System Group contains 1 group and 1 rule
[ref] The X Window System implementation included with the system is called X.org.
Group Disable X Windows Group contains 1 rule

[ref] Unless there is a mission-critical reason for the system to run a graphical user interface, ensure X is not set to start automatically at boot and remove the X Windows software packages. There is usually no reason to run X Windows on a dedicated server system, as it increases the system's attack surface and consumes system resources. Administrators of server systems should instead login via SSH or on the text console.

#### Rule Remove the X Windows Package Group [ref]

By removing the xorg-x11-server-common package, the system no longer has X Windows installed. If X Windows is not installed then the system cannot boot into graphical user mode. This prevents the system from being accidentally or maliciously booted into a `graphical.target` mode. To do so, run the following command:

    $ sudo apt_get groupremove "X Window System"

    $ sudo apt_get remove xorg-x11-server-common

Warning: The installation and use of a Graphical User Interface (GUI) increases your attack vector and decreases your overall security posture. Removing the package xorg-x11-server-common package will remove the graphical target which might bring your system to an inconsistent state requiring additional configuration to access the system again. If a GUI is an operational requirement, a tailored profile that removes this rule should used before continuing installation.

Rationale: | Unnecessary service packages must not be installed to decrease the attack surface of the system. X windows has a long history of security vulnerabilities and should not be installed unless approved and documented.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_xorg-x11-server-common_removed

References:

cis-csc | 12, 15, 8
cobit5 | APO13.01, DSS01.04, DSS05.02, DSS05.03
isa-62443-2009 | 4.3.3.6.6
isa-62443-2013 | SR 1.13, SR 2.6, 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.13.1.1, A.13.2.1, A.14.1.3, A.6.2.1, A.6.2.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
cis | 2.1.20

Remediation Shell script ⇲

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

    # CAUTION: This remediation script will remove xorg-x11-server-common
    # from the system, and may remove any packages
    # that depend on xorg-x11-server-common. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "xorg-x11-server-common"

Remediation Puppet snippet ⇲

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

    include remove_xorg-x11-server-common

    class remove_xorg-x11-server-common {
      package { 'xorg-x11-server-common':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Remove the X Windows Package Group: Ensure xorg-x11-server-common is removed'
      ansible.builtin.package:
        name: xorg-x11-server-common
        state: absent
      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_xorg-x11-server-common_removed

Group System Accounting with auditd Group contains 12 groups and 80 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 9 groups and 62 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 13 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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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
cis | 6.2.3.9
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

Group Record Execution Attempts to Run ACL Privileged Commands Group contains 2 rules
[ref] At a minimum, the audit system should collect the execution of ACL privileged commands for all users and root.

#### Rule Record Any Attempts to Run chacl [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/chacl -F perm=x -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/chacl -F perm=x -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_execution_chacl

References:

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
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
cis | 6.2.3.17

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/chacl -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 Record Any Attempts to Run setfacl [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/setfacl -F perm=x -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/setfacl -F perm=x -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_execution_setfacl

References:

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
cis | 6.2.3.16

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/setfacl -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 Record Execution Attempts to Run SELinux Privileged Commands Group contains 1 rule
[ref] At a minimum, the audit system should collect the execution of SELinux privileged commands for all users and root.

#### Rule Record Any Attempts to Run chcon [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/chcon -F perm=x -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/chcon -F perm=x -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_execution_chcon

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-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000463-GPOS-00207, SRG-OS-000465-GPOS-00209
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-000501-CTR-001265, SRG-APP-000502-CTR-001270
cis | 6.2.3.15
ism | 0582

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/chcon -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 Record File Deletion Events by User Group contains 4 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
cis | 6.2.3.13
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
cis | 6.2.3.13
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 - 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
cis | 6.2.3.13
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
cis | 6.2.3.13
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
cis | 6.2.3.7
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
cis | 6.2.3.7
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
cis | 6.2.3.7
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
cis | 6.2.3.7
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
cis | 6.2.3.7
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 5 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 - create_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 create_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_create

References:

os-srg | SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222
cis | 6.2.3.19

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
    # 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="create_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:
      - audit_rules_kernel_module_loading_create
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - create_module
        - Set architecture for audit ['create_module'] 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:
      - audit_rules_kernel_module_loading_create
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - create_module
        - Perform remediation of Audit rules for ['create_module'] for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - create_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of create_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:
          - create_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of create_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'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - audit_rules_kernel_module_loading_create
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - create_module
        - Perform remediation of Audit rules for ['create_module'] for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - create_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of create_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:
          - create_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of create_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'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - audit_rules_kernel_module_loading_create
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### 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
cis | 6.2.3.19

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
cis | 6.2.3.19

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
cis | 6.2.3.19

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

#### Rule Ensure auditd Collects Information on Kernel Module Loading and Unloading - query_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 query_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_query

References:

cis | 6.2.3.19

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
    # 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="query_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:
      - audit_rules_kernel_module_loading_query
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - query_module - Set architecture for audit ['query_module'] 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:
      - audit_rules_kernel_module_loading_query
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - query_module - Perform remediation of Audit rules for ['query_module'] for 32bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - query_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of query_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:
          - query_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of query_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'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - audit_rules_kernel_module_loading_query
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - query_module - Perform remediation of Audit rules for ['query_module'] for 64bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - query_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of query_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:
          - query_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of query_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'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - audit_rules_kernel_module_loading_query
      - 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/run/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/run/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/run/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/run/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
cis | 6.2.3.12
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/run/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/run/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
cis | 6.2.3.12
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 3 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
cis | 6.2.3.6
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 - 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 perm=x -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 perm=x -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
cis | 6.2.3.19

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 - usermod [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/sbin/usermod -F perm=x -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/sbin/usermod -F perm=x -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_usermod

References:

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
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
cis | 6.2.3.18

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/sbin/usermod -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
cis | 6.2.3.4
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
cis | 6.2.3.4
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 settimeofday [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 settimeofday -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S settimeofday -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 settimeofday -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S settimeofday -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_settimeofday

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
cis | 6.2.3.4
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_settimeofday
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set architecture for audit tasks
      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_settimeofday
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for settimeofday for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - settimeofday
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of settimeofday 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:
          - settimeofday
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of settimeofday 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_settimeofday
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for settimeofday for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - settimeofday
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of settimeofday 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:
          - settimeofday
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of settimeofday 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_settimeofday
      - 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
cis | 6.2.3.4
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
cis | 6.2.3.20
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 Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor) [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/apparmor/ -p wa -k MAC-policy

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/apparmor/ -p wa -k MAC-policy

Rationale: | The system's mandatory access policy (Apparmor) should not be arbitrarily changed by anything other than administrator action. All changes to MAC policy should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_mac_modification_etc_apparmor

References:

cis | 6.2.3.14

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/apparmor" "$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/apparmor $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/apparmor$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/apparmor -p wa -k MAC-policy" >> "$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/MAC-policy.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/apparmor" /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/MAC-policy.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/MAC-policy.rules"
        # If the MAC-policy.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/apparmor" "$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/apparmor $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/apparmor$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/apparmor -p wa -k MAC-policy" >> "$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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Check if watch rule for /etc/apparmor already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/apparmor\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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Search /etc/audit/rules.d for other rules with specified key MAC-policy
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)MAC-policy$
        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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Use /etc/audit/rules.d/MAC-policy.rules as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/MAC-policy.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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - 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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Add watch rule for /etc/apparmor in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/apparmor -p wa -k MAC-policy
        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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Check if watch rule for /etc/apparmor already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/apparmor\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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor)
        - Add watch rule for /etc/apparmor in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/apparmor -p wa -k MAC-policy
        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:
      - audit_rules_mac_modification_etc_apparmor
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d) [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/apparmor.d/ -p wa -k MAC-policy

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/apparmor.d/ -p wa -k MAC-policy

Rationale: | The system's mandatory access policy (Apparmor) should not be arbitrarily changed by anything other than administrator action. All changes to MAC policy should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_mac_modification_etc_apparmor_d

References:

cis | 6.2.3.14

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/apparmor.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/apparmor.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/apparmor.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/apparmor.d -p wa -k MAC-policy" >> "$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/MAC-policy.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/apparmor.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/MAC-policy.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/MAC-policy.rules"
        # If the MAC-policy.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/apparmor.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/apparmor.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/apparmor.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/apparmor.d -p wa -k MAC-policy" >> "$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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Check if watch rule for /etc/apparmor.d already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/apparmor.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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Search /etc/audit/rules.d for other rules with specified key MAC-policy
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)MAC-policy$
        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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Use /etc/audit/rules.d/MAC-policy.rules as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/MAC-policy.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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - 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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Add watch rule for /etc/apparmor.d in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/apparmor.d -p wa -k MAC-policy
        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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Check if watch rule for /etc/apparmor.d already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/apparmor.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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Mandatory Access Controls (/etc/apparmor.d)
        - Add watch rule for /etc/apparmor.d in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/apparmor.d -p wa -k MAC-policy
        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:
      - audit_rules_mac_modification_etc_apparmor_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - 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
cis | 6.2.3.10
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
cis | 6.2.3.5
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 [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` in order to watch for attempted manual edits of files involved in storing such process information:

    -w /var/run/utmp -p wa -k session
    -w /var/log/btmp -p wa -k session
    -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` file in order to watch for attempted manual edits of files involved in storing such process information:

    -w /var/run/utmp -p wa -k session
    -w /var/log/btmp -p wa -k session
    -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

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.2.3
app-srg-ctr | SRG-APP-000505-CTR-001285
cis | 6.2.3.11

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
    # 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
    # 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: | 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information - 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:
      - 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.2.3
      - audit_rules_session_events
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events When Executables Are Run As Another User [ref]

Verify the system generates an audit record when actions are run as another user. sudo provides users with temporary elevated privileges to perform operations, either as the superuser or another user. If audit is using the "auditctl" tool to load the rules, run the following command:

    $ sudo grep execve /etc/audit/audit.rules

If audit is using the "augenrules" tool to load the rules, run the following command:

    $ sudo grep -r execve /etc/audit/rules.d

    -a always,exit -F arch=b32 -S execve -C euid!=uid -F auid!=unset -k user_emulation

    -a always,exit -F arch=b64  S execve -C euid!=uid -F auid!=unset -k user_emulation

If both the "b32" and "b64" audit rules for "SUID" files are not defined, this is a finding.
Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect.

Rationale:

Creating an audit log of users with temporary elevated privileges and the operation(s) they performed is essential to reporting. Administrators will want to correlate the events written to the audit trail with the records written to sudo's logfile to verify if unauthorized commands have been executed. Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised information 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 threats and the advanced persistent threat.

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

References:

cis | 6.2.3.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="-C euid!=uid"
    	AUID_FILTERS="-F auid!=unset"
    	SYSCALL="execve"
    	KEY="user_emulation"
    	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

#### 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
cis | 6.2.3.1
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
cis | 6.2.3.8
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
cis | 6.2.3.8
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/nsswitch.conf [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/nsswitch.conf -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/nsswitch.conf -p wa -k audit_rules_usergroup_modification

Rationale: | The nsswitch file defines how the system uses various databases and name resolution mechanisms. Any unexpected changes to nsswitch configuration should be investigated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_nsswitch_conf

References:

cis | 6.2.3.8

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/nsswitch.conf" "$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/nsswitch.conf $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/nsswitch.conf$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/nsswitch.conf -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/nsswitch.conf" /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/nsswitch.conf" "$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/nsswitch.conf $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/nsswitch.conf$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/nsswitch.conf -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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - Check
        if watch rule for /etc/nsswitch.conf already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/nsswitch.conf\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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - 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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - 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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - 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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - Add
        watch rule for /etc/nsswitch.conf in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/nsswitch.conf -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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - Check
        if watch rule for /etc/nsswitch.conf already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/nsswitch.conf\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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/nsswitch.conf - Add
        watch rule for /etc/nsswitch.conf in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/nsswitch.conf -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:
      - audit_rules_usergroup_modification_nsswitch_conf
      - 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
cis | 6.2.3.8
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/pam.conf [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/pam.conf -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/pam.conf -p wa -k audit_rules_usergroup_modification

Rationale: | The PAM configuration file defines the authentication mechanism used by PAM-aware applications. Any unexpected changes to PAM configuration should be investigated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_pam_conf

References:

cis | 6.2.3.8

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/pam.conf" "$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/pam.conf $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/pam.conf$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/pam.conf -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/pam.conf" /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/pam.conf" "$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/pam.conf $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/pam.conf$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/pam.conf -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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - Check if
        watch rule for /etc/pam.conf already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/pam.conf\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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - 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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - 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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - 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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - Add watch
        rule for /etc/pam.conf in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/pam.conf -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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - Check if
        watch rule for /etc/pam.conf already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/pam.conf\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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.conf - Add watch
        rule for /etc/pam.conf in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/pam.conf -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:
      - audit_rules_usergroup_modification_pam_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/pam.d/ [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/pam.d/ -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/pam.d/ -p wa -k audit_rules_usergroup_modification

Rationale: | The PAM configuration files in /etc/pam.d define the authentication mechanism used by PAM-aware applications. Any unexpected changes to PAM configuration should be investigated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_pamd

References:

cis | 6.2.3.8

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/pam.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/pam.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/pam.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/pam.d/ -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/pam.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/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/pam.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/pam.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/pam.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/pam.d/ -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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - Check if
        watch rule for /etc/pam.d/ already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/pam.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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - 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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - 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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - 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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - Add watch
        rule for /etc/pam.d/ in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/pam.d/ -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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - Check if
        watch rule for /etc/pam.d/ already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/pam.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:
      - audit_rules_usergroup_modification_pamd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/pam.d/ - Add watch
        rule for /etc/pam.d/ in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/pam.d/ -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:
      - audit_rules_usergroup_modification_pamd
      - 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
cis | 6.2.3.8
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
cis | 6.2.3.8
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 12 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
cis | 6.2.3.3
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 System Audit Logs Must Have Mode 0750 or Less Permissive [ref]

If `log_group` in `/etc/audit/auditd.conf` is set to a group other than the `root` group account, change the mode of the audit log files with the following command:

    $ sudo chmod 0750 /var/log/audit

Otherwise, change the mode of the audit log files with the following command:

    $ sudo chmod 0700 /var/log/audit

Rationale: | If users can write to audit logs, audit trails can be modified or destroyed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_var_log_audit

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 3, 4, 5, 6, 7, 8
cobit5 | APO01.06, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA02.01
isa-62443-2009 | 4.2.3.10, 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.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
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.2, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-004-6 R3.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 R6.5
nist | CM-6(a), AC-6(1), AU-9
nist-csf | DE.AE-3, DE.AE-5, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029
cis | 6.2.4.4

#### Rule System Audit Logs Must Be Group Owned By Root [ref]

All audit logs must be group owned by root user. The path for audit log can be configured via `log_file` parameter in

    /etc/audit/auditd.conf

or, by default, the path for audit log is

    /var/log/audit/

. To properly set the group owner of `/var/log/audit/*`, run the command:

    $ sudo chgrp root /var/log/audit/*

If `log_group` in `/etc/audit/auditd.conf` is set to a group other than the `root` group account, change the group ownership of the audit logs to this specific group.

Rationale: | Unauthorized disclosure of audit records can reveal system and configuration data to attackers, thus compromising its confidentiality.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_group_ownership_var_log_audit

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, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA02.01
cui | 3.3.1
isa-62443-2009 | 4.2.3.10, 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.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 | CM-6(a), AC-6(1), AU-9(4)
nist-csf | DE.AE-3, DE.AE-5, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.5.1
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029, SRG-OS-000206-GPOS-00084
cis | 6.2.4.3
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

    if LC_ALL=C grep -iw log_file /etc/audit/auditd.conf; then
      FILE=$(awk -F "=" '/^log_file/ {print $2}' /etc/audit/auditd.conf | tr -d ' ')
    else
      FILE="/var/log/audit/audit.log"
    fi

    if LC_ALL=C grep -m 1 -q ^log_group /etc/audit/auditd.conf; then
      GROUP=$(awk -F "=" '/log_group/ {print $2}' /etc/audit/auditd.conf | tr -d ' ')
        if ! [ "${GROUP}" == 'root' ]; then
          chgrp ${GROUP} $FILE*
        else
          chgrp root $FILE*
        fi
    else
      chgrp root $FILE*
    fi

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

#### Rule Audit Configuration Files Must Be Owned By Group root [ref]

All audit configuration files must be owned by group root.

    chown :root /etc/audit/audit*.{rules,conf} /etc/audit/rules.d/*

Rationale:

Without the capability to restrict which roles and individuals can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one.

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

References:

os-srg | SRG-OS-000063-GPOS-00032
cis | 6.2.4.7

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$'; 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/audit/ -maxdepth 1 -type f  ! -group 0 -regextype posix-extended -regex '^.*audit(\.rules|d\.conf)$' -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /etc/audit/rules.d/ -maxdepth 1 -type f  ! -group 0 -regextype posix-extended -regex '^.*\.rules$' -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_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Find /etc/audit/ file(s) matching ^.*audit(\.rules|d\.conf)$
      ansible.builtin.command: find -P /etc/audit/ -maxdepth 1 -type f  ! -group 0 -regextype
        posix-extended -regex "^.*audit(\.rules|d\.conf)$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/audit/ file(s) matching ^.*audit(\.rules|d\.conf)$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownership_audit_configuration_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/audit/rules.d/ file(s) matching ^.*\.rules$
      ansible.builtin.command: find -P /etc/audit/rules.d/ -maxdepth 1 -type f  ! -group
        0 -regextype posix-extended -regex "^.*\.rules$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/audit/rules.d/ file(s) matching ^.*\.rules$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownership_audit_configuration_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Audit Configuration Files Must Be Owned By Root [ref]

All audit configuration files must be owned by root user. To properly set the owner of `/etc/audit/`, run the command:

    $ sudo chown root /etc/audit/

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

    $ sudo chown root /etc/audit/rules.d/

Rationale:

Without the capability to restrict which roles and individuals can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one.

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

References:

os-srg | SRG-OS-000063-GPOS-00032
cis | 6.2.4.6

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$'; 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/audit/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*audit(\.rules|d\.conf)$' -exec chown --no-dereference "$newown" {} \;

    find -P /etc/audit/rules.d/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*\.rules$' -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_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Find /etc/audit/ file(s) matching ^.*audit(\.rules|d\.conf)$
      ansible.builtin.command: find -P /etc/audit/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex "^.*audit(\.rules|d\.conf)$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/audit/ file(s) matching ^.*audit(\.rules|d\.conf)$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_audit_configuration_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/audit/rules.d/ file(s) matching ^.*\.rules$
      ansible.builtin.command: find -P /etc/audit/rules.d/ -maxdepth 1 -type f  ! -user
        0 -regextype posix-extended -regex "^.*\.rules$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/audit/rules.d/ file(s) matching ^.*\.rules$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_audit_configuration_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule System Audit Logs Must Be Owned By Root [ref]

All audit logs must be owned by root user. The path for audit log can be configured via `log_file` parameter in

    /etc/audit/auditd.conf

or by default, the path for audit log is

    /var/log/audit/

. To properly set the owner of `/var/log/audit/*`, run the command:

    $ sudo chown root /var/log/audit/*

Rationale: | Unauthorized disclosure of audit records can reveal system and configuration data to attackers, thus compromising its confidentiality.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_var_log_audit_stig

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, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA02.01
cui | 3.3.1
isa-62443-2009 | 4.2.3.10, 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.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 | CM-6(a), AC-6(1), AU-9(4)
nist-csf | DE.AE-3, DE.AE-5, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.5.1
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029, SRG-OS-000206-GPOS-00084
cis | 6.2.4.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

    if LC_ALL=C grep -iw log_file /etc/audit/auditd.conf; then
        FILE=$(awk -F "=" '/^log_file/ {print $2}' /etc/audit/auditd.conf | tr -d ' ')
        chown root $FILE*
    else
        chown root /var/log/audit/audit.log*
    fi

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

#### Rule System Audit Logs Must Have Mode 0640 or Less Permissive [ref]

If `log_group` in `/etc/audit/auditd.conf` is set to a group other than the `root` group account, change the mode of the audit log files with the following command:

    $ sudo chmod 0640 audit_file

Otherwise, change the mode of the audit log files with the following command:

    $ sudo chmod 0600 audit_file

Rationale: | If users can write to audit logs, audit trails can be modified or destroyed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_var_log_audit

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, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA02.01
cui | 3.3.1
isa-62443-2009 | 4.2.3.10, 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.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
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), AU-9(4)
nist-csf | DE.AE-3, DE.AE-5, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.5
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029, SRG-OS-000206-GPOS-00084
app-srg-ctr | SRG-APP-000118-CTR-000240
cis | 6.2.4.1
pcidss4 | 10.3.1, 10.3

Group Configure auditd Data Retention Group contains 7 rules

[ref] The audit system writes data to `/var/log/audit/audit.log`. By default, `auditd` rotates 5 logs by size (6MB), retaining a maximum of 30MB of data in total, and refuses to write entries when the disk is too full. This minimizes the risk of audit data filling its partition and impacting other services. This also minimizes the risk of the audit daemon temporarily disabling the system if it cannot write audit log (which it can be configured to do). For a busy system or a system which is thoroughly auditing system activity, the default settings for data retention may be insufficient. The log file size needed will depend heavily on what types of events are being audited. First configure auditing to log all the events of interest. Then monitor the log size manually for awhile to determine what file size will allow you to keep the required data for the correct time period.
Using a dedicated partition for `/var/log/audit` prevents the `auditd` logs from disrupting system functionality if they fill, and, more importantly, prevents other activity in `/var` from filling the partition and stopping the audit trail. (The audit logs are size-limited and therefore unlikely to grow without bound unless configured to do so.) Some machines may have requirements that no actions occur which cannot be audited. If this is the case, then `auditd` can be configured to halt the machine if it runs out of space. Note: Since older logs are rotated, configuring `auditd` this way does not prevent older logs from being rotated away before they can be viewed. If your system is configured to halt when logging cannot be performed, make sure this can never happen under normal circumstances! Ensure that `/var/log/audit` is on its own partition, and that this partition is larger than the maximum amount of data `auditd` will retain normally.

#### Rule Configure auditd Disk Error Action on Disk Error [ref]

The `auditd` service can be configured to take an action when there is a disk error. Edit the file `/etc/audit/auditd.conf`. Add or modify the following line, substituting ACTION appropriately:

    disk_error_action = ACTION

Set this value to `single` to cause the system to switch to single-user mode for corrective action. Acceptable values also include `syslog`, `exec`, `single`, and `halt` For certain systems, the need for availability outweighs the need to log all actions, and a different setting should be determined. Details regarding all possible values for ACTION are described in the `auditd.conf` man page.

Rationale: | Taking appropriate action in case of disk errors will minimize the possibility of losing audit records.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_disk_error_action

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nist | AU-5(b), AU-5(2), AU-5(1), AU-5(4), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
os-srg | SRG-OS-000047-GPOS-00023
app-srg-ctr | SRG-APP-000098-CTR-000185, SRG-APP-000099-CTR-000190, SRG-APP-000100-CTR-000195, SRG-APP-000100-CTR-000200, SRG-APP-000109-CTR-000215, SRG-APP-000290-CTR-000670, SRG-APP-000357-CTR-000800
cis | 6.2.2.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

    var_auditd_disk_error_action='syslog|single|halt'

    #
    # If disk_error_action present in /etc/audit/auditd.conf, change value
    # to var_auditd_disk_error_action, else
    # add "disk_error_action = $var_auditd_disk_error_action" to /etc/audit/auditd.conf
    #
    var_auditd_disk_error_action="$(echo $var_auditd_disk_error_action | 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' <<< "^disk_error_action")

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

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

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

#### Rule Configure auditd Disk Full Action when Disk Space Is Full [ref]

The `auditd` service can be configured to take an action when disk space is running low but prior to running out of space completely. Edit the file `/etc/audit/auditd.conf`. Add or modify the following line, substituting ACTION appropriately:

    disk_full_action = ACTION

Set this value to `single` to cause the system to switch to single-user mode for corrective action. Acceptable values also include `syslog`, `exec`, `single`, and `halt` For certain systems, the need for availability outweighs the need to log all actions, and a different setting should be determined. Details regarding all possible values for ACTION are described in the `auditd.conf` man page.

Rationale: | Taking appropriate action in case of a filled audit storage volume will minimize the possibility of losing audit records.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_disk_full_action

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nist | AU-5(b), AU-5(2), AU-5(1), AU-5(4), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
os-srg | SRG-OS-000047-GPOS-00023
cis | 6.2.2.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

    var_auditd_disk_full_action='halt|single'

    var_auditd_disk_full_action="$(echo $var_auditd_disk_full_action | 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' <<< "^disk_full_action")

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

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

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

#### Rule Configure auditd mail_acct Action on Low Disk Space [ref]

The `auditd` service can be configured to send email to a designated account in certain situations. Add or correct the following line in `/etc/audit/auditd.conf` to ensure that administrators are notified via email for those situations:

    action_mail_acct = root

Rationale: | Email sent to the root account is typically aliased to the administrators of the system, who can take appropriate action.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_retention_action_mail_acct

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
cui | 3.3.1
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nerc-cip | CIP-003-8 R1.3, CIP-003-8 R3, CIP-003-8 R3.1, CIP-003-8 R3.2, CIP-003-8 R3.3, 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-5(1), AU-5(a), AU-5(2), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.7.a
os-srg | SRG-OS-000046-GPOS-00022, SRG-OS-000343-GPOS-00134
cis | 6.2.2.4

#### Rule Configure auditd admin_space_left Action on Low Disk Space [ref]

The `auditd` service can be configured to take an action when disk space is running low but prior to running out of space completely. Edit the file `/etc/audit/auditd.conf`. Add or modify the following line, substituting ACTION appropriately:

    admin_space_left_action = ACTION

Set this value to `single` to cause the system to switch to single user mode for corrective action. Acceptable values also include `suspend` and `halt`. For certain systems, the need for availability outweighs the need to log all actions, and a different setting should be determined. Details regarding all possible values for ACTION are described in the `auditd.conf` man page.

Rationale: | Administrators should be made aware of an inability to record audit records. If a separate partition or logical volume of adequate size is used, running low on space for audit records should never occur.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_retention_admin_space_left_action

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
cui | 3.3.1
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nist | AU-5(b), AU-5(2), AU-5(1), AU-5(4), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.7
os-srg | SRG-OS-000343-GPOS-00134
cis | 6.2.2.4
pcidss4 | 10.5.1, 10.5

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

    var_auditd_admin_space_left_action='halt'

    var_auditd_admin_space_left_action="$(echo $var_auditd_admin_space_left_action | cut -d \| -f 1)"

    AUDITCONFIG=/etc/audit/auditd.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' <<< "^admin_space_left_action")

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

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

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

#### Rule Configure auditd Max Log File Size [ref]

Determine the amount of audit data (in megabytes) which should be retained in each log file. Edit the file `/etc/audit/auditd.conf`. Add or modify the following line, substituting the correct value of 6 for STOREMB:

    max_log_file = STOREMB

Set the value to `6` (MB) or higher for general-purpose systems. Larger values, of course, support retention of even more audit data.

Rationale: | The total storage for audit log files must be large enough to retain log information over the period required. This is a function of the maximum log file size and the number of logs retained.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_retention_max_log_file

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.16.1.4, A.16.1.5, A.16.1.7
nerc-cip | CIP-004-6 R2.2.3, CIP-004-6 R3.3, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3, CIP-007-3 R6.5
nist | AU-11, CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.7
cis | 6.2.2.1

#### Rule Configure auditd max_log_file_action Upon Reaching Maximum Log Size [ref]

The default action to take when the logs reach their maximum size is to rotate the log files, discarding the oldest one. To configure the action taken by `auditd`, add or correct the line in `/etc/audit/auditd.conf`:

    max_log_file_action = ACTION

Possible values for ACTION are described in the `auditd.conf` man page. These include:

- `ignore`
- `syslog`
- `suspend`
- `rotate`
- `keep_logs`

Set the `ACTION` to `keep_logs`. The setting is case-insensitive.

Rationale: | Automatically rotating logs (by setting this to `rotate`) minimizes the chances of the system unexpectedly running out of disk space by being overwhelmed with log data. However, for systems that must never discard log data, or which use external processes to transfer it and reclaim space, `keep_logs` can be employed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_retention_max_log_file_action

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nist | AU-5(b), AU-5(2), AU-5(1), AU-5(4), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.7
os-srg | SRG-OS-000047-GPOS-00023
cis | 6.2.2.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

    var_auditd_max_log_file_action='keep_logs'

    AUDITCONFIG=/etc/audit/auditd.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' <<< "^max_log_file_action")

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

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

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

#### Rule Configure auditd space_left Action on Low Disk Space [ref]

The `auditd` service can be configured to take an action when disk space starts to run low. Edit the file `/etc/audit/auditd.conf`. Modify the following line, substituting ACTION appropriately:

    space_left_action = ACTION

Possible values for ACTION are described in the `auditd.conf` man page. These include:

- `syslog`
- `email`
- `exec`
- `suspend`
- `single`
- `halt`

Set this to `email` (instead of the default, which is `suspend`) as it is more likely to get prompt attention. Acceptable values also include `suspend`, `single`, and `halt`.

Rationale: | Notifying administrators of an impending disk space problem may allow them to take corrective action prior to any disruption.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_data_retention_space_left_action

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO11.04, APO12.06, APO13.01, BAI03.05, BAI04.04, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, MEA02.01
cui | 3.3.1
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.2.3.10, 4.3.3.3.9, 4.3.3.5.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 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, 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.16.1.4, A.16.1.5, A.16.1.7, A.17.2.1
nist | AU-5(b), AU-5(2), AU-5(1), AU-5(4), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, PR.DS-4, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.7
os-srg | SRG-OS-000343-GPOS-00134
cis | 6.2.2.4
pcidss4 | 10.5.1, 10.5

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

    var_auditd_space_left_action='email'

    var_auditd_space_left_action="$(echo $var_auditd_space_left_action | cut -d \| -f 1)"
    #
    # If space_left_action present in /etc/audit/auditd.conf, change value
    # to var_auditd_space_left_action, else
    # add "space_left_action = $var_auditd_space_left_action" to /etc/audit/auditd.conf
    #

    AUDITCONFIG=/etc/audit/auditd.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' <<< "^space_left_action")

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

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

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

Group System Accounting with auditd Group contains 6 rules
[ref] The audit service provides substantial capabilities for recording system activities. This section deals with permissions of auditd related files.

#### Rule Verify that audit tools are owned by group root [ref]

The Debian 12 operating system audit tools must have the proper ownership configured to protected against unauthorized access. Verify it by running the following command:

    $ stat -c "%n %G" /sbin/auditctl /sbin/aureport /sbin/ausearch /sbin/autrace /sbin/auditd /sbin/audispd /sbin/augenrules

    /sbin/auditctl root

    /sbin/aureport root

    /sbin/ausearch root

    /sbin/autrace root

    /sbin/auditd root

    /sbin/audispd root

    /sbin/augenrules root

Audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators

Rationale:

Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operation on audit information. Operating systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools and the corresponding rights the user enjoys to make access decisions regarding the access to audit tools.

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

References:

os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098
cis | 6.2.4.10

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" "/sbin/auditctl" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/auditctl
    fi
    if ! stat -c "%g %G" "/sbin/aureport" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/aureport
    fi
    if ! stat -c "%g %G" "/sbin/ausearch" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/ausearch
    fi
    if ! stat -c "%g %G" "/sbin/autrace" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/autrace
    fi
    if ! stat -c "%g %G" "/sbin/auditd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/auditd
    fi
    if ! stat -c "%g %G" "/sbin/audispd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/audispd
    fi
    if ! stat -c "%g %G" "/sbin/augenrules" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/augenrules
    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_groupownership_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#### Rule Verify that audit tools are owned by root [ref]

The Debian 12 operating system audit tools must have the proper ownership configured to protected against unauthorized access. Verify it by running the following command:

    $ stat -c "%n %U" /sbin/auditctl /sbin/aureport /sbin/ausearch /sbin/autrace /sbin/auditd /sbin/audispd /sbin/augenrules

    /sbin/auditctl root

    /sbin/aureport root

    /sbin/ausearch root

    /sbin/autrace root

    /sbin/auditd root

    /sbin/audispd root

    /sbin/augenrules root

Audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators

Rationale:

Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operation on audit information. Operating systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools and the corresponding rights the user enjoys to make access decisions regarding the access to audit tools.

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

References:

os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098
cis | 6.2.4.9

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" "/sbin/auditctl" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/auditctl
    fi
    if ! stat -c "%u %U" "/sbin/aureport" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/aureport
    fi
    if ! stat -c "%u %U" "/sbin/ausearch" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/ausearch
    fi
    if ! stat -c "%u %U" "/sbin/autrace" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/autrace
    fi
    if ! stat -c "%u %U" "/sbin/auditd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/auditd
    fi
    if ! stat -c "%u %U" "/sbin/audispd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/audispd
    fi
    if ! stat -c "%u %U" "/sbin/augenrules" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/augenrules
    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_ownership_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#### Rule Verify that audit tools Have Mode 0755 or less [ref]

The Debian 12 operating system audit tools must have the proper permissions configured to protected against unauthorized access. Verify it by running the following command:

    $ stat -c "%n %a" /sbin/auditctl /sbin/aureport /sbin/ausearch /sbin/autrace /sbin/auditd /sbin/audispd /sbin/augenrules

    /sbin/auditctl 755

    /sbin/aureport 755

    /sbin/ausearch 755

    /sbin/autrace 755

    /sbin/auditd 755

    /sbin/audispd 755

    /sbin/augenrules 755

Audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators

Rationale:

Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operation on audit information. Operating systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools and the corresponding rights the user enjoys to make access decisions regarding the access to audit tools.

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

References:

os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098
cis | 6.2.4.8

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-s,g-ws,o-wt /sbin/auditctl

    chmod u-s,g-ws,o-wt /sbin/aureport

    chmod u-s,g-ws,o-wt /sbin/ausearch

    chmod u-s,g-ws,o-wt /sbin/autrace

    chmod u-s,g-ws,o-wt /sbin/auditd

    chmod u-s,g-ws,o-wt /sbin/audispd

    chmod u-s,g-ws,o-wt /sbin/augenrules

    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_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/auditctl
      ansible.builtin.file:
        path: /sbin/auditctl
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/aureport
      ansible.builtin.file:
        path: /sbin/aureport
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/ausearch
      ansible.builtin.file:
        path: /sbin/ausearch
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/autrace
      ansible.builtin.file:
        path: /sbin/autrace
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/auditd
      ansible.builtin.file:
        path: /sbin/auditd
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/audispd
      ansible.builtin.file:
        path: /sbin/audispd
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/augenrules
      ansible.builtin.file:
        path: /sbin/augenrules
        mode: u-s,g-ws,o-wt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_audit_binaries
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/audit/auditd.conf [ref]

To properly set the permissions of `/etc/audit/auditd.conf`, run the command:

    $ sudo chmod 0640 /etc/audit/auditd.conf

Rationale:

Without the capability to restrict the roles and individuals that can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one.

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

References:

nist | AU-12(b)
os-srg | SRG-OS-000063-GPOS-00032
cis | 6.2.4.5

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/audit/auditd.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:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_auditd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/audit/auditd.conf
      ansible.builtin.stat:
        path: /etc/audit/auditd.conf
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_auditd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/audit/auditd.conf
      ansible.builtin.file:
        path: /etc/audit/auditd.conf
        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:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_auditd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/audit/audit.rules [ref]

To properly set the permissions of `/etc/audit/audit.rules`, run the command:

    $ sudo chmod 0640 /etc/audit/audit.rules

Rationale:

Without the capability to restrict the roles and individuals that can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one.

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

References:

cis | 6.2.4.5

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/audit/audit.rules

    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_audit_rules
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/audit/audit.rules
      ansible.builtin.file:
        path: /etc/audit/audit.rules
        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_audit_rules
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/audit/rules.d/*.rules [ref]

To properly set the permissions of `/etc/audit/rules.d/*.rules`, run the command:

    $ sudo chmod 0600 /etc/audit/rules.d/*.rules

Rationale:

Without the capability to restrict the roles and individuals that can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one.

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

References:

nist | AU-12(b)
os-srg | SRG-OS-000063-GPOS-00032
cis | 6.2.4.5

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/audit/rules.d/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type f -regextype posix-extended -regex '^.*rules$' -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:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_rulesd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/audit/rules.d/ file(s)
      ansible.builtin.command: find -P /etc/audit/rules.d/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type
        f -regextype posix-extended -regex "^.*rules$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_rulesd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/audit/rules.d/ 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:
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_rulesd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure the default plugins for the audit dispatcher are Installed [ref]

The audit-audispd-plugins package should be installed.
Rationale: | Information stored in one location is vulnerable to accidental or incidental deletion or alteration. Off-loading is a common process in information systems with limited audit storage capacity.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_audit-audispd-plugins_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)
pcidss | Req-10.5.3
os-srg | SRG-OS-000342-GPOS-00133
cis | 6.2.1.1
pcidss4 | 10.3.3, 10.3

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 "audispd-plugins"

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

Remediation Puppet snippet ⇲

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

    include install_audispd-plugins

    class install_audispd-plugins {
      package { 'audispd-plugins':
        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.5.3
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_audit-audispd-plugins_installed

    - name: Ensure audispd-plugins is installed
      ansible.builtin.package:
        name: audispd-plugins
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.5.3
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_audit-audispd-plugins_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "audispd-plugins"
    version = "*"

#### 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
cis | 6.2.1.1
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
cis | 6.2.1.2
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"]

#### Rule Enable Auditing for Processes Which Start Prior to the Audit Daemon [ref]

To ensure all processes can be audited, even those which start prior to the audit daemon, add the argument `audit=1` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain audit=1 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) audit=1"

Rationale: | Each process on the system carries an "auditable" flag which indicates whether its activities can be audited. Although `auditd` takes care of enabling this for all processes which launch after it does, adding the kernel argument ensures it is set for every process during boot.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_audit_argument

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 3, 4, 5, 6, 7, 8
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.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.02, DSS05.03, DSS05.04, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.3.1
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 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.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 | AC-17(1), AU-14(1), AU-10, CM-6(a), IR-5(1)
nist-csf | DE.AE-3, DE.AE-5, 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.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-000254-GPOS-00095
cis | 6.2.1.3
pcidss4 | 10.7.2, 10.7

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 "audit" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"audit=[^\"]*\"(.*]\s*)/\1\"audit=1\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"audit=1\"]" >> "$KARGS_DIR/10-audit.toml"
        fi
    else

        # Correct the form of default kernel command line in GRUB
        if grep -q '^\s*GRUB_CMDLINE_LINUX=.*audit=.*"'  '/etc/default/grub' ; then
               # modify the GRUB command-line if an audit= arg already exists
               sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)audit=[^[:space:]]\+\(.*\"\)/\1audit=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 audit=arg is present, append it
               sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)\"/\1 audit=1\"/"  '/etc/default/grub'
        # Add GRUB_CMDLINE_LINUX parameters line
        else
               echo "GRUB_CMDLINE_LINUX=\"audit=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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check audit argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*audit=' /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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check audit 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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add audit argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="audit=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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing audit argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: audit=[a-zA-Z0-9,]+
        replace: audit=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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add audit argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 audit=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:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_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:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-14(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IR-5(1)
      - PCI-DSS-Req-10.3
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

#### Rule Extend Audit Backlog Limit for the Audit Daemon [ref]

To improve the kernel capacity to queue all log events, even those which occurred prior to the audit daemon, add the argument `audit_backlog_limit=8192` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain audit_backlog_limit=8192 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) audit_backlog_limit=8192"

Rationale: | audit_backlog_limit sets the queue length for audit events awaiting transfer to the audit daemon. Until the audit daemon is up and running, all log messages are stored in this queue. If the queue is overrun during boot process, the action defined by audit failure flag is taken.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_audit_backlog_limit_argument

References:

nist | CM-6(a)
ospp | FAU_STG.1, FAU_STG.3
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000254-GPOS-00095, SRG-OS-000341-GPOS-00132, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
cis | 6.2.1.4
pcidss4 | 10.7.2, 10.7

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_audit_backlog_limit='8192'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "audit_backlog_limit" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"audit_backlog_limit=[^\"]*\"(.*]\s*)/\1\"audit_backlog_limit=$var_audit_backlog_limit\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"audit_backlog_limit=$var_audit_backlog_limit\"]" >> "$KARGS_DIR/10-audit_backlog_limit.toml"
        fi
    else

        # Correct the form of default kernel command line in GRUB
        if grep -q '^\s*GRUB_CMDLINE_LINUX=.*audit_backlog_limit=.*"'  '/etc/default/grub' ; then
               # modify the GRUB command-line if an audit_backlog_limit= arg already exists
               sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)audit_backlog_limit=[^[:space:]]\+\(.*\"\)/\1audit_backlog_limit=$var_audit_backlog_limit\2/"  '/etc/default/grub'
        # Add to already existing GRUB_CMDLINE_LINUX parameters
        elif grep -q '^\s*GRUB_CMDLINE_LINUX='  '/etc/default/grub' ; then
               # no audit_backlog_limit=arg is present, append it
               sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)\"/\1 audit_backlog_limit=$var_audit_backlog_limit\"/"  '/etc/default/grub'
        # Add GRUB_CMDLINE_LINUX parameters line
        else
               echo "GRUB_CMDLINE_LINUX=\"audit_backlog_limit=$var_audit_backlog_limit\"" >> '/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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_audit_backlog_limit # promote to variable
      set_fact:
        var_audit_backlog_limit: !!str 8192
      tags:
        - always

    - name: Check audit_backlog_limit argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*audit_backlog_limit=' /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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check audit_backlog_limit 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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add audit_backlog_limit argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="audit_backlog_limit={{ var_audit_backlog_limit }} "
        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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing audit_backlog_limit argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: audit_backlog_limit=[a-zA-Z0-9,]+
        replace: audit_backlog_limit={{ var_audit_backlog_limit }}
      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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add audit_backlog_limit argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 audit_backlog_limit={{ var_audit_backlog_limit }}"
      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)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_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:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-10.7
      - PCI-DSSv4-10.7.2
      - grub2_audit_backlog_limit_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

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.