## Guide to the Secure Configuration of Red Hat Enterprise Linux 9

> with profile DISA STIG for Red Hat Enterprise Linux 9
> This profile contains configuration checks that align to the DISA STIG for Red Hat Enterprise Linux 9 V2R5. In addition to being applicable to Red Hat Enterprise Linux 9, this configuration baseline is applicable to the operating system tier of Red Hat technologies that are based on Red Hat Enterprise Linux 9, such as: - Red Hat Enterprise Linux Server - Red Hat Enterprise Linux Workstation and Desktop - Red Hat Enterprise Linux for HPC - Red Hat Storage - Red Hat Containers with a Red Hat Enterprise Linux 9 image

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 Red Hat Enterprise Linux 9. 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.

This benchmark is a direct port of a SCAP Security Guide benchmark developed for Red Hat Enterprise Linux. It has been modified through an automated process to remove specific dependencies on Red Hat Enterprise Linux and to function with CentOS. The result is a generally useful SCAP Security Guide benchmark with the following caveats:

- CentOS is not an exact copy of Red Hat Enterprise Linux. There may be configuration differences that produce false positives and/or false negatives. If this occurs please file a bug report.
- CentOS has its own build system, compiler options, patchsets, and is a community supported, non-commercial operating system. CentOS does not inherit certifications or evaluations from Red Hat Enterprise Linux. As such, some configuration rules (such as those requiring FIPS 140-2 encryption) will continue to fail on CentOS.

Members of the CentOS community are invited to participate in OpenSCAP and SCAP Security Guide development. Bug reports and patches can be sent to GitHub: https://github.com/ComplianceAsCode/content. The mailing list is at https://fedorahosted.org/mailman/listinfo/scap-security-guide.

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 | DISA STIG for Red Hat Enterprise Linux 9
Profile ID | xccdf_org.ssgproject.content_profile_stig

#### CPE Platforms

- cpe:/o:redhat:enterprise_linux:9
- cpe:/o:centos:centos:9

## 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. GRUB2 bootloader configuration
   4. Configure Syslog
   5. Network Configuration and Firewalls
   6. File Permissions and Masks
   7. SELinux
2. Services
   1. Base Services
   2. Cron and At Daemons
   3. Application Whitelisting Daemon
   4. FTP Server
   5. Mail Server Software
   6. NFS and RPC
   7. Network Time Protocol
   8. Obsolete Services
   9. SSH Server
   10. System Security Services Daemon
   11. USBGuard daemon
   12. 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 Red Hat Enterprise Linux 9 Group contains 107 groups and 492 rules
Group System Settings Group contains 68 groups and 295 rules
[ref] Contains rules that check correct system settings.
Group Installing and Maintaining Software Group contains 15 groups and 65 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 5 groups and 25 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 10 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 10 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:

    $ sudo dnf install aide

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

References:

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

Remediation script ⇲

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

    dnf install aide

Remediation script ⇲

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

    package install aide

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

    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 Anaconda snippet ⇲

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

    package --add=aide

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
      - DISA-STIG-RHEL-09-651010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - DISA-STIG-RHEL-09-651010
      - 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 /usr/sbin/aide --init

By default, the database will be written to the file `/var/lib/aide/aide.db.new.gz`. 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.gz /var/lib/aide/aide.db.gz

To initiate a manual check, run the following command:

    $ sudo /usr/sbin/aide --check

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

    $ sudo /usr/sbin/aide --init

Then replace the existing database:

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

    /usr/sbin/aide --init
    /bin/cp -p /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

    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
      - DISA-STIG-RHEL-09-651010
      - 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.package:
        name: '{{ item }}'
        state: present
      with_items:
      - aide
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - DISA-STIG-RHEL-09-651010
      - 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 Whether the Stock AIDE Database Exists
      ansible.builtin.stat:
        path: /var/lib/aide/aide.db.new.gz
      register: aide_database_stat
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - DISA-STIG-RHEL-09-651010
      - 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/aide --init
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - not (aide_database_stat.stat.exists is defined and aide_database_stat.stat.exists)
      register: aide_database_init
      tags:
      - CJIS-5.10.1.3
      - DISA-STIG-RHEL-09-651010
      - 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 - Stage AIDE Database
      ansible.builtin.copy:
        src: /var/lib/aide/aide.db.new.gz
        dest: /var/lib/aide/aide.db.gz
        backup: true
        remote_src: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - aide_database_init is changed
      - not ansible_check_mode
      tags:
      - CJIS-5.10.1.3
      - DISA-STIG-RHEL-09-651010
      - 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.1.3
stigref | SV-258137r1102081_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

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

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

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

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

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

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

    if grep -i -E '^.*(/usr)?/sbin/rsyslogd.*$' /etc/aide.conf; then
    sed -i -r "s#.*(/usr)?/sbin/rsyslogd.*#/usr/sbin/rsyslogd p+i+n+u+g+s+b+acl+xattrs+sha512#" /etc/aide.conf
    else
    echo "/usr/sbin/rsyslogd p+i+n+u+g+s+b+acl+xattrs+sha512" >> /etc/aide.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:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure AIDE to Verify the Audit Tools - Gather List of Packages
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      ansible.builtin.package_facts:
        manager: auto
      when: '"kernel-core" in ansible_facts.packages'

    - name: Ensure aide is installed
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      with_items:
      - aide
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure AIDE to Verify the Audit Tools - Gather the package facts
      ansible.builtin.package_facts:
        manager: auto
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set audit_tools fact
      ansible.builtin.set_fact:
        audit_tools:
        - /usr/sbin/auditctl
        - /usr/sbin/auditd
        - /usr/sbin/augenrules
        - /usr/sbin/aureport
        - /usr/sbin/ausearch
        - /usr/sbin/autrace
        - /usr/sbin/rsyslogd
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure existing AIDE configuration for audit tools are correct
      ansible.builtin.lineinfile:
        path: /etc/aide.conf
        regexp: ^{{ item }}\s
        line: '{{ item }} p+i+n+u+g+s+b+acl+xattrs+sha512'
        create: true
      with_items: '{{ audit_tools }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"aide" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure AIDE to properly protect audit tools
      ansible.builtin.lineinfile:
        path: /etc/aide.conf
        line: '{{ item }} p+i+n+u+g+s+b+acl+xattrs+sha512'
        create: true
      with_items: '{{ audit_tools }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"aide" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651025
      - NIST-800-53-AU-9(3)
      - NIST-800-53-AU-9(3).1
      - aide_check_audit_tools
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

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

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

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi
    var_aide_scan_notification_email='root@localhost'

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

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

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

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

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

Remediation Ansible snippet ⇲

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

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

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

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

#### Rule Configure AIDE to Use FIPS 140-2 for Validating Hashes [ref]

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

    NORMAL = FIPSR+sha512

AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | File integrity tools use cryptographic hashes for verifying file contents and directories have not been altered. These hashes must be FIPS 140-2 approved cryptographic hashes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_aide_use_fips_hashes

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

    aide_conf="/etc/aide.conf"
    forbidden_hashes=(sha1 rmd160 sha256 whirlpool tiger haval gost crc32)

    groups=$(LC_ALL=C grep "^[A-Z][A-Za-z_]*" $aide_conf | cut -f1 -d ' ' | tr -d ' ' | sort -u)

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

    	if ! [[ $config = *sha512* ]]
    	then
    		config=$config"+sha512"
    	fi

    	for hash in "${forbidden_hashes[@]}"
    	do
    		config=$(echo $config | sed "s/$hash//")
    	done

    	config=$(echo $config | sed "s/^\+*//")
    	config=$(echo $config | sed "s/\+\++/+/")
    	config=$(echo $config | sed "s/\+$//")

    	sed -i "s/^$group\s*=.*/$group = $config/g" $aide_conf
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure AIDE to Use FIPS 140-2 for Validating Hashes - Ensure aide is installed
      ansible.builtin.package:
        name: aide
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure AIDE to Use FIPS 140-2 for Validating Hashes - Set-fact aide config
        file and forbidden hashes
      ansible.builtin.set_fact:
        aide_conf: /etc/aide.conf
        forbidden_hashes:
        - sha1
        - rmd160
        - sha256
        - whirlpool
        - tiger
        - haval
        - gost
        - crc32
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure AIDE to Use FIPS 140-2 for Validating Hashes - Gather the package
        facts
      ansible.builtin.package_facts:
        manager: auto
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure AIDE to Use FIPS 140-2 for Validating Hashes - Remove forbidden
        hashes
      ansible.builtin.replace:
        path: '{{ aide_conf }}'
        regexp: (^\s*[A-Z][A-Za-z_]*\s*=.*?)({{ item }}\+|\+?{{ item }})(.*)
        replace: \1\3
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"aide" in ansible_facts.packages'
      loop: '{{ forbidden_hashes }}'
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure AIDE to Use FIPS 140-2 for Validating Hashes - Set sha512
      ansible.builtin.replace:
        path: '{{ aide_conf }}'
        regexp: (^\s*[A-Z][A-Za-z_]*\s*=)((?:(?!\+?sha512).)*)\s*$
        replace: \1\2+sha512
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"aide" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-651020
      - NIST-800-171-3.13.11
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_use_fips_hashes
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

    aide_conf="/etc/aide.conf"

    groups=$(LC_ALL=C grep "^[A-Z][A-Za-z_]*" $aide_conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u)

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

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

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

Remediation Ansible snippet ⇲

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

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

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

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

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

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

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

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "aide" ; then
        dnf install -y "aide"
    fi

    aide_conf="/etc/aide.conf"

    groups=$(LC_ALL=C grep "^[A-Z][A-Za-z_]*" $aide_conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u)

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

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

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

Remediation Ansible snippet ⇲

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

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

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

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

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

#### Rule Audit Tools Must Be Group-owned by Root [ref]

Red Hat Enterprise Linux 9 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. 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. Audit tools must have the correct group owner.

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 operations on audit information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_audit_tools_group_ownership

References:

nist | AU-9
os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098, SRG-OS-000258-GPOS-00099
stigref | SV-257925r991557_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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/rsyslogd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /sbin/rsyslogd
    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:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_audit_tools_group_ownership_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_audit_tools_group_ownership_newgroup: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /sbin/rsyslogd
      ansible.builtin.stat:
        path: /sbin/rsyslogd
      register: file_exists
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /sbin/rsyslogd
      ansible.builtin.file:
        path: /sbin/rsyslogd
        follow: false
        group: '{{ file_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - 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_audit_tools_group_ownership_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232225
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Audit Tools Must Be Owned by Root [ref]

Red Hat Enterprise Linux 9 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. 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. Audit tools must have the correct owner.

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 operations on audit information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_audit_tools_ownership

References:

nist | AU-9
os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098, SRG-OS-000258-GPOS-00099
stigref | SV-257924r991557_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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/rsyslogd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /sbin/rsyslogd
    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:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_audit_tools_ownership_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_audit_tools_ownership_newown: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /sbin/rsyslogd
      ansible.builtin.stat:
        path: /sbin/rsyslogd
      register: file_exists
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /sbin/rsyslogd
      ansible.builtin.file:
        path: /sbin/rsyslogd
        follow: false
        owner: '{{ file_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - 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_audit_tools_ownership_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232220
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Audit Tools Must Have a Mode of 0755 or Less Permissive [ref]

Red Hat Enterprise Linux 9 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. 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. Audit tools must have a mode of 0755 or less permissive.

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 operations on audit information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_audit_tools_permissions

References:

nist | AU-9
os-srg | SRG-OS-000256-GPOS-00097, SRG-OS-000257-GPOS-00098, SRG-OS-000258-GPOS-00099
stigref | SV-257887r991557_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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/rsyslogd

    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:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /sbin/rsyslogd
      ansible.builtin.stat:
        path: /sbin/rsyslogd
      register: file_exists
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-s,g-ws,o-wt on /sbin/rsyslogd
      ansible.builtin.file:
        path: /sbin/rsyslogd
        mode: u-s,g-ws,o-wt
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232035
      - NIST-800-53-AU-9
      - configure_strategy
      - file_audit_tools_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Federal Information Processing Standard (FIPS) Group contains 5 rules

[ref] The Federal Information Processing Standard (FIPS) is a computer security standard which is developed by the U.S. Government and industry working groups to validate the quality of cryptographic modules. The FIPS standard provides four security levels to ensure adequate coverage of different industries, implementation of cryptographic modules, and organizational sizes and requirements.
FIPS 140-2 is the current standard for validating that mechanisms used to access cryptographic modules utilize authentication that meets industry and government requirements. For government systems, this allows Security Levels 1, 2, 3, or 4 for use on Red Hat Enterprise Linux 9.
See http://csrc.nist.gov/publications/PubsFIPS.html for more information.

#### Rule Enable Dracut FIPS Module [ref]

Red Hat Enterprise Linux 9 has an installation-time kernel flag that can enable FIPS mode. The installer must be booted with `fips=1` for the system to have FIPS mode enabled. Enabling FIPS mode on a preexisting system is not supported. If this rule fails on an installed system, then this is a permanent finding and cannot be fixed. To enable FIPS, the system requires that the `fips` module is added in `dracut` configuration. Check if `/etc/dracut.conf.d/40-fips.conf` contain `add_dracutmodules+=" fips "`
Warning: To configure the operating system to run in FIPS 140 mode, the kernel parameter "fips=1" needs to be added during its installation. Enabling FIPS mode on a preexisting system involves a number of modifications to it and therefore is not supported.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Use of weak or untested encryption algorithms undermines the purposes of utilizing encryption to protect data. The operating system must implement cryptographic modules adhering to the higher standards approved by the federal government since this provides assurance they have been tested and validated.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_enable_dracut_fips_module

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | SC-12(2), SC-12(3), IA-7, SC-13, CM-6(a), SC-12
ospp | FCS_RBG_EXT.1
os-srg | SRG-OS-000478-GPOS-00223
ism | 1446
stigref | SV-258230r958408_rule

#### Rule Enable FIPS Mode [ref]

Red Hat Enterprise Linux 9 has an installation-time kernel flag that can enable FIPS mode. The installer must be booted with `fips=1` for the system to have FIPS mode enabled. Enabling FIPS mode on a preexisting system is not supported. If this rule fails on an installed system, then this is a permanent finding and cannot be fixed.
To enable FIPS mode at bootable container build time configure `fips=1` kernel argument in `/usr/lib/bootc/kargs.d/01-fips.toml`:

    kargs = ["fips=1"]

Then set the cryptographic policy to `FIPS:STIG`:

    update-crypto-policies --no-reload --set FIPS:STIG

Warning: To configure Red Hat Enterprise Linux 9 to run in FIPS 140 mode, the kernel parameter "fips=1" needs to be added during its installation. Only enabling FIPS 140 mode during the Red Hat Enterprise Linux 9 installation ensures that the system generates all keys with FIPS-approved algorithms and continuous monitoring tests in place. Enabling FIPS mode on a preexisting system involves a number of modifications to it and therefore is not supported.
Warning: This rule DOES NOT CHECK if the components of the operating system are FIPS certified. You can find the list of FIPS certified modules at https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules/search. This rule checks if the system is running in FIPS mode.

Rationale: | Use of weak or untested encryption algorithms undermines the purposes of utilizing encryption to protect data. The operating system must implement cryptographic modules adhering to the higher standards approved by the federal government since this provides assurance they have been tested and validated.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_enable_fips_mode

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | CM-3(6), SC-12(2), SC-12(3), IA-7, SC-13, CM-6(a), SC-12
ospp | FCS_COP.1(1), FCS_COP.1(2), FCS_COP.1(3), FCS_COP.1(4), FCS_CKM.1, FCS_CKM.2, FCS_TLSC_EXT.1, FCS_RBG_EXT.1
os-srg | SRG-OS-000478-GPOS-00223, SRG-OS-000396-GPOS-00176
ism | 1446
stigref | SV-258230r958408_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( ! ( [ "${container:-}" == "bwrap-osbuild" ] ) && rpm --quiet -q kernel-core ); then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; }; then
    	cat > /usr/lib/bootc/kargs.d/01-fips.toml << EOF
    kargs = ["fips=1"]
    EOF
    fi

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

Remediation OSBuild Blueprint snippet ⇲

    [customizations]
    fips = true

#### Rule FIPS Must Use a Supported Subpolicy [ref]

Sub-policies can be used to modify existing crypto policies. Some sub-policies such as `NO-ENFORCE-EMS` reduce the security of the system and should not be used. Other such as `AD-SUPPORT` should only be enabled if operationally required. The `OSPP`, `NO-SHA1`, `NO-CAMELLIA`, and `ECDHE-ONLY` are allowed by this rule. Warning: This rule does not have a remediation.
Rationale: | Sub-policies can cause insecure ciphers to be used.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_fips_crypto_subpolicy

References:

os-srg | SRG-OS-000033-GPOS-00014
stigref | SV-258241r1106302_rule

#### Rule Implement STIG Sub Crypto Policy [ref]

Create a custom cryptographic policy to follow the guidance from DISA.
Rationale: | To follow STIG policy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_fips_custom_stig_sub_policy

References:

os-srg | SRG-OS-000396-GPOS-00176, SRG-OS-000393-GPOS-00173, SRG-OS-000394-GPOS-00174
stigref | SV-258241r1106302_rule

Remediation Shell script ⇲

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

    cat << 'EOF' > /etc/crypto-policies/policies/modules/STIG.pmod
    cipher@SSH=AES-256-GCM AES-256-CTR AES-128-GCM AES-128-CTR
    mac@SSH=HMAC-SHA2-512 HMAC-SHA2-256
    EOF

    sudo update-crypto-policies --set FIPS:STIG

Remediation Ansible snippet ⇲

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

    - name: Implement STIG Sub Crypto Policy - Create custom crypto policy - cipher
      ansible.builtin.lineinfile:
        path: /etc/crypto-policies/policies/modules/STIG.pmod
        owner: root
        group: root
        mode: '0644'
        line: cipher@SSH=AES-256-GCM AES-256-CTR AES-128-GCM AES-128-CTR
        create: true
        regexp: cipher@SSH
      tags:
      - DISA-STIG-RHEL-09-215105
      - configure_strategy
      - fips_custom_stig_sub_policy
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required

    - name: Implement STIG Sub Crypto Policy - Create custom crypto policy - mac
      ansible.builtin.lineinfile:
        path: /etc/crypto-policies/policies/modules/STIG.pmod
        owner: root
        group: root
        mode: '0644'
        line: mac@SSH=HMAC-SHA2-512 HMAC-SHA2-256
        create: true
        regexp: ^mac@SSH=
      tags:
      - DISA-STIG-RHEL-09-215105
      - configure_strategy
      - fips_custom_stig_sub_policy
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required

    - name: Implement STIG Sub Crypto Policy - Check current crypto policy
      ansible.builtin.command: update-crypto-policies --show
      register: current_crypto_policy
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-215105
      - configure_strategy
      - fips_custom_stig_sub_policy
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required

    - name: Implement STIG Sub Crypto Policy - Update crypto-policies
      ansible.builtin.command: update-crypto-policies --set FIPS:STIG
      when: current_crypto_policy.stdout.strip() != "FIPS:STIG"
      tags:
      - DISA-STIG-RHEL-09-215105
      - configure_strategy
      - fips_custom_stig_sub_policy
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required

#### Rule Set kernel parameter 'crypto.fips_enabled' to 1 [ref]

System running in FIPS mode is indicated by kernel parameter `'crypto.fips_enabled'`. This parameter should be set to `1` in FIPS mode. Red Hat Enterprise Linux 9 has an installation-time kernel flag that can enable FIPS mode. The installer must be booted with `fips=1` for the system to have FIPS mode enabled. Enabling FIPS mode on a preexisting system is not supported. If this rule fails on an installed system, then this is a permanent finding and cannot be fixed. To enable strict FIPS compliance, the fips=1 kernel option needs to be added to the kernel boot parameters during system installation so key generation is done with FIPS-approved algorithms and continuous monitoring tests in place.
Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Use of weak or untested encryption algorithms undermines the purposes of utilizing encryption to protect data. The operating system must implement cryptographic modules adhering to the higher standards approved by the federal government since this provides assurance they have been tested and validated.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_crypto_fips_enabled

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | SC-12(2), SC-12(3), IA-7, SC-13, CM-6(a), SC-12
os-srg | SRG-OS-000033-GPOS-00014, SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093, SRG-OS-000393-GPOS-00173, SRG-OS-000394-GPOS-00174, SRG-OS-000396-GPOS-00176, SRG-OS-000423-GPOS-00187, SRG-OS-000478-GPOS-00223
stigref | SV-258230r958408_rule

Group System Cryptographic Policies Group contains 9 rules

[ref] Linux has the capability to centrally configure cryptographic polices. The command `update-crypto-policies` is used to set the policy applicable for the various cryptographic back-ends, such as SSL/TLS libraries. The configured cryptographic policies will be the default policy used by these backends unless the application user configures them otherwise. When the system has been configured to use the centralized cryptographic policies, the administrator is assured that any application that utilizes the supported backends will follow a policy that adheres to the configured profile. Currently the supported backends are:

- GnuTLS library
- OpenSSL library
- NSS library
- OpenJDK
- Libkrb5
- BIND
- OpenSSH

Applications and languages which rely on any of these backends will follow the system policies as well. Examples are apache httpd, nginx, php, and others.

#### Rule Install crypto-policies package [ref]

The `crypto-policies` package can be installed with the following command:

    $ sudo dnf install crypto-policies

Rationale: | Centralized cryptographic policies simplify applying secure ciphers across an operating system and the applications that run on that operating system. Use of weak or untested encryption algorithms undermines the purposes of utilizing encryption to protect data.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_crypto-policies_installed

References:

ospp | FCS_COP.1(1), FCS_COP.1(2), FCS_COP.1(3), FCS_COP.1(4), FCS_CKM.1, FCS_CKM.2, FCS_TLSC_EXT.1
os-srg | SRG-OS-000396-GPOS-00176, SRG-OS-000393-GPOS-00173, SRG-OS-000394-GPOS-00174
stigref | SV-258234r1051250_rule

Remediation script ⇲

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

    dnf install crypto-policies

Remediation script ⇲

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

    package install crypto-policies

Remediation Shell script ⇲

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

    if ! rpm -q --quiet "crypto-policies" ; then
        dnf install -y "crypto-policies"
    fi

Remediation Puppet snippet ⇲

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

    include install_crypto-policies

    class install_crypto-policies {
      package { 'crypto-policies':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=crypto-policies

Remediation Ansible snippet ⇲

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

    - name: Ensure crypto-policies is installed
      ansible.builtin.package:
        name: crypto-policies
        state: present
      tags:
      - DISA-STIG-RHEL-09-215100
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_crypto-policies_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "crypto-policies"
    version = "*"

#### Rule Configure BIND to use System Crypto Policy [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. BIND is supported by crypto policy, but the BIND configuration may be set up to ignore it. To check that Crypto Policies settings are configured correctly, ensure that the `/etc/named.conf` includes the appropriate configuration: In the `options` section of `/etc/named.conf`, make sure that the following line is not commented out or superseded by later includes: `include "/etc/crypto-policies/back-ends/bind.config";`

Rationale: | Overriding the system crypto policy makes the behavior of the BIND service violate expectations, and makes system configuration more fragmented.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_configure_bind_crypto_policy

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | SC-13, SC-12(2), SC-12(3)
os-srg | SRG-OS-000423-GPOS-00187, SRG-OS-000426-GPOS-00190
stigref | SV-258242r958908_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q bind; then

    function remediate_bind_crypto_policy() {
    	CONFIG_FILE="/etc/named.conf"
    	if test -f "$CONFIG_FILE"; then
    		sed -i 's|options {|&\n\tinclude "/etc/crypto-policies/back-ends/bind.config";|' "$CONFIG_FILE"
    		return 0
    	else
    		echo "Aborting remediation as '$CONFIG_FILE' was not even found." >&2
    		return 1
    	fi
    }

    remediate_bind_crypto_policy

    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:
      - DISA-STIG-RHEL-09-672050
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - configure_bind_crypto_policy
      - configure_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

    - name: Configure BIND to use System Crypto Policy - Check BIND configuration file
        exists
      ansible.builtin.stat:
        path: /etc/named.conf
      register: bind_config_file
      when: '"bind" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-672050
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - configure_bind_crypto_policy
      - configure_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

    - name: Configure BIND to use System Crypto Policy - Aborting remediation, file not
        found
      ansible.builtin.debug:
        msg: Aborting remediation as '/etc/named.conf' was not found.
      when:
      - '"bind" in ansible_facts.packages'
      - not bind_config_file.stat.exists
      tags:
      - DISA-STIG-RHEL-09-672050
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - configure_bind_crypto_policy
      - configure_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

    - name: Configure BIND to use System Crypto Policy - Insert crypto-policy into BIND
        config
      ansible.builtin.lineinfile:
        path: /etc/named.conf
        insertafter: ^\s*options\s*{
        line: ' include "/etc/crypto-policies/back-ends/bind.config";'
        state: present
      when:
      - '"bind" in ansible_facts.packages'
      - bind_config_file.stat.exists
      tags:
      - DISA-STIG-RHEL-09-672050
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - configure_bind_crypto_policy
      - configure_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

#### Rule Configure System Cryptography Policy [ref]

To configure the system cryptography policy to use ciphers only from the `FIPS:STIG` policy, run the following command:

    $ sudo update-crypto-policies --set FIPS:STIG

The rule checks if settings for selected crypto policy are configured as expected. Configuration files in the `/etc/crypto-policies/back-ends` are either symlinks to correct files provided by Crypto-policies package or they are regular files in case crypto policy customizations are applied. Crypto policies may be customized by crypto policy modules, in which case it is delimited from the base policy using a colon.
Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Centralized cryptographic policies simplify applying secure ciphers across an operating system and the applications that run on that operating system. Use of weak or untested encryption algorithms undermines the purposes of utilizing encryption to protect data.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_configure_crypto_policy

References:

hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.312(e)(1), 164.312(e)(2)(ii)
nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1, CIP-007-3 R7.1
nist | AC-17(a), AC-17(2), CM-6(a), MA-4(6), SC-13, SC-12(2), SC-12(3)
ospp | FCS_COP.1(1), FCS_COP.1(2), FCS_COP.1(3), FCS_COP.1(4), FCS_CKM.1, FCS_CKM.2, FCS_TLSC_EXT.1
os-srg | SRG-OS-000396-GPOS-00176, SRG-OS-000393-GPOS-00173, SRG-OS-000394-GPOS-00174
ism | 1446
pcidss4 | 2.2.7, 2.2
stigref | SV-258241r1106302_rule

Remediation Shell script ⇲

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

    var_system_crypto_policy='FIPS:STIG'

    stderr_of_call=$(update-crypto-policies --set ${var_system_crypto_policy} 2>&1 > /dev/null)
    rc=$?

    if test "$rc" = 127; then
    	echo "$stderr_of_call" >&2
    	echo "Make sure that the script is installed on the remediated system." >&2
    	echo "See output of the 'dnf provides update-crypto-policies' command" >&2
    	echo "to see what package to (re)install" >&2

    	false  # end with an error code
    elif test "$rc" != 0; then
    	echo "Error invoking the update-crypto-policies script: $stderr_of_call" >&2
    	false  # end with an error code
    fi

Remediation Ansible snippet ⇲

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

    - name: XCCDF Value var_system_crypto_policy # promote to variable
      set_fact:
        var_system_crypto_policy: !!str FIPS:STIG
      tags:
        - always

    - name: Configure System Cryptography Policy - Check current crypto policy (runtime)
      ansible.builtin.command: /usr/bin/update-crypto-policies --show
      register: current_crypto_policy
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-215105
      - DISA-STIG-RHEL-09-672030
      - NIST-800-53-AC-17(2)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - configure_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Configure System Cryptography Policy - Get mtime of /etc/crypto-policies/config
      ansible.builtin.stat:
        path: /etc/crypto-policies/config
      register: config_file_stat
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-215105
      - DISA-STIG-RHEL-09-672030
      - NIST-800-53-AC-17(2)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - configure_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Configure System Cryptography Policy - Get mtime of /etc/crypto-policies/state/current
      ansible.builtin.stat:
        path: /etc/crypto-policies/state/current
      register: current_file_stat
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-215105
      - DISA-STIG-RHEL-09-672030
      - NIST-800-53-AC-17(2)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - configure_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Configure System Cryptography Policy - Check existence of /etc/crypto-policies/back-ends/nss.config
      ansible.builtin.stat:
        path: /etc/crypto-policies/back-ends/nss.config
      register: nss_config_stat
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-215105
      - DISA-STIG-RHEL-09-672030
      - NIST-800-53-AC-17(2)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - configure_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Configure System Cryptography Policy - Verify that Crypto Policy is Set (runtime)
      ansible.builtin.command: /usr/bin/update-crypto-policies --set {{ var_system_crypto_policy
        }}
      when: (current_crypto_policy.stdout.strip() != var_system_crypto_policy) or (config_file_stat.stat.exists
        and current_file_stat.stat.exists and config_file_stat.stat.mtime > current_file_stat.stat.mtime)
        or (not nss_config_stat.stat.exists)
      tags:
      - DISA-STIG-RHEL-09-215105
      - DISA-STIG-RHEL-09-672030
      - NIST-800-53-AC-17(2)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.7
      - configure_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

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

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
            - name: configure-crypto-policy.service
              enabled: true
              contents: |
                [Unit]
                Before=kubelet.service
                [Service]
                Type=oneshot
                ExecStart=update-crypto-policies --set {{.var_system_crypto_policy}}
                RemainAfterExit=yes
                [Install]
                WantedBy=multi-user.target

#### Rule Configure Kerberos to use System Crypto Policy [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. Kerberos is supported by crypto policy, but it's configuration may be set up to ignore it. To check that Crypto Policies settings for Kerberos are configured correctly, examine that there is a symlink at /etc/krb5.conf.d/crypto-policies targeting /etc/cypto-policies/back-ends/krb5.config. If the symlink exists, Kerberos is configured to use the system-wide crypto policy settings.

Rationale: | Overriding the system crypto policy makes the behavior of Kerberos violate expectations, and makes system configuration more fragmented.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_configure_kerberos_crypto_policy

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | SC-13, SC-12(2), SC-12(3)
os-srg | SRG-OS-000120-GPOS-00061
ism | 0418, 1055, 1402

Remediation Shell script ⇲

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

    rm -f /etc/krb5.conf.d/crypto-policies
    ln -s /etc/crypto-policies/back-ends/krb5.config /etc/krb5.conf.d/crypto-policies

Remediation Ansible snippet ⇲

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

    - name: Configure Kerberos to use System Crypto Policy
      ansible.builtin.file:
        src: /etc/crypto-policies/back-ends/krb5.config
        path: /etc/krb5.conf.d/crypto-policies
        state: link
      tags:
      - DISA-STIG-RHEL-09-672025
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - configure_kerberos_crypto_policy
      - configure_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - reboot_required

#### Rule Configure Libreswan to use System Crypto Policy [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. Libreswan is supported by system crypto policy, but the Libreswan configuration may be set up to ignore it. To check that Crypto Policies settings are configured correctly, ensure that the `/etc/ipsec.conf` includes the appropriate configuration file. In `/etc/ipsec.conf`, make sure that the following line is not commented out or superseded by later includes: `include /etc/crypto-policies/back-ends/libreswan.config`

Rationale: | Overriding the system crypto policy makes the behavior of the Libreswan service violate expectations, and makes system configuration more fragmented.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_configure_libreswan_crypto_policy

References:

nerc-cip | CIP-003-8 R4.2, CIP-007-3 R5.1
nist | CM-6(a), MA-4(6), SC-13, SC-12(2), SC-12(3)
pcidss | Req-2.2
os-srg | SRG-OS-000033-GPOS-00014
stigref | SV-258232r1045440_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    function remediate_libreswan_crypto_policy() {
        CONFIG_FILE="/etc/ipsec.conf"
        if ! grep -qP "^\s*include\s+/etc/crypto-policies/back-ends/libreswan.config\s*(?:#.*)?$" "$CONFIG_FILE" ; then
            # the file might not end with a new line
            echo -e '\ninclude /etc/crypto-policies/back-ends/libreswan.config' >> "$CONFIG_FILE"
        fi
        return 0
    }

    remediate_libreswan_crypto_policy

    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:
      - DISA-STIG-RHEL-09-671020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSS-Req-2.2
      - configure_libreswan_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Libreswan to use System Crypto Policy
      ansible.builtin.lineinfile:
        path: /etc/ipsec.conf
        line: include /etc/crypto-policies/back-ends/libreswan.config
        create: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-671020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(6)
      - NIST-800-53-SC-12(2)
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SC-13
      - PCI-DSS-Req-2.2
      - configure_libreswan_crypto_policy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure SSH Client to Use FIPS 140 Validated Ciphers: openssh.config [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. OpenSSH is supported by system crypto policy, but the OpenSSH configuration may be set up incorrectly. To check that Crypto Policies settings for ciphers are configured correctly, ensure that `/etc/crypto-policies/back-ends/openssh.config` contains the following line and is not commented out:

    Ciphers aes256-gcm@openssh.com,aes256-ctr,aes128-gcm@openssh.com,aes128-ctr

Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Overriding the system crypto policy makes the behavior of the OpenSSH client violate expectations, and makes system configuration more fragmented. By specifying a cipher list with the order of ciphers being in a “strongest to weakest” orientation, the system will automatically attempt to use the strongest cipher for securing SSH connections.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_harden_sshd_ciphers_openssh_conf_crypto_policy

References:

nist | AC-17(2)
os-srg | SRG-OS-000033-GPOS-00014, SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093, SRG-OS-000393-GPOS-00173, SRG-OS-000394-GPOS-00174, SRG-OS-000423-GPOS-00187
stigref | SV-270177r1051237_rule

#### Rule Configure SSH Server to Use FIPS 140-2 Validated Ciphers: opensshserver.config [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. OpenSSH is supported by system crypto policy, but the OpenSSH configuration may be set up incorrectly. To check that Crypto Policies settings for ciphers are configured correctly, ensure that `/etc/crypto-policies/back-ends/opensshserver.config` contains the following text and is not commented out:

    -oCiphers=aes256-gcm@openssh.com,aes256-ctr,aes128-gcm@openssh.com,aes128-ctr

Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Overriding the system crypto policy makes the behavior of the OpenSSH server violate expectations, and makes system configuration more fragmented. By specifying a cipher list with the order of ciphers being in a “strongest to weakest” orientation, the system will automatically attempt to use the strongest cipher for securing SSH connections.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_harden_sshd_ciphers_opensshserver_conf_crypto_policy

References:

nist | AC-17(2)
os-srg | SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093
stigref | SV-257989r1051240_rule

#### Rule Configure SSH Client to Use FIPS 140-2 Validated MACs: openssh.config [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. OpenSSH is supported by system crypto policy, but the OpenSSH configuration may be set up incorrectly. To check that Crypto Policies settings are configured correctly, ensure that `/etc/crypto-policies/back-ends/openssh.config` contains the following line and is not commented out: `MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha2-512`
Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Overriding the system crypto policy makes the behavior of the OpenSSH client violate expectations, and makes system configuration more fragmented.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_harden_sshd_macs_openssh_conf_crypto_policy

References:

nist | AC-17(2)
os-srg | SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093
stigref | SV-270178r1051243_rule

#### Rule Configure SSH Server to Use FIPS 140-2 Validated MACs: opensshserver.config [ref]

Crypto Policies provide a centralized control over crypto algorithms usage of many packages. OpenSSH is supported by system crypto policy, but the OpenSSH configuration may be set up incorrectly. To check that Crypto Policies settings are configured correctly, ensure that `/etc/crypto-policies/back-ends/opensshserver.config` contains the following text and is not commented out: `-oMACS=hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha2-512`
Warning: The system needs to be rebooted for these changes to take effect.
Warning: System Crypto Modules must be provided by a vendor that undergoes FIPS-140 certifications. FIPS-140 is applicable to all Federal agencies that use cryptographic-based security systems to protect sensitive information in computer and telecommunication systems (including voice systems) as defined in Section 5131 of the Information Technology Management Reform Act of 1996, Public Law 104-106. This standard shall be used in designing and implementing cryptographic modules that Federal departments and agencies operate or are operated for them under contract. See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.140-2.pdf To meet this, the system has to have cryptographic software provided by a vendor that has undergone this certification. This means providing documentation, test results, design information, and independent third party review by an accredited lab. While open source software is capable of meeting this, it does not meet FIPS-140 unless the vendor submits to this process.

Rationale: | Overriding the system crypto policy makes the behavior of the OpenSSH server violate expectations, and makes system configuration more fragmented.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_harden_sshd_macs_opensshserver_conf_crypto_policy

References:

nist | AC-17(2)
os-srg | SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093
stigref | SV-257991r1051246_rule

Group Operating System Vendor Support and Certification Group contains 1 rule

[ref] The assurance of a vendor to provide operating system support and maintenance for their product is an important criterion to ensure product stability and security over the life of the product. A certified product that follows the necessary standards and government certification requirements guarantees that known software vulnerabilities will be remediated, and proper guidance for protecting and securing the operating system will be given.

#### Rule The Installed Operating System Is Vendor Supported [ref]

The installed operating system must be maintained by a vendor. Red Hat Enterprise Linux is supported by Red Hat, Inc. As the Red Hat Enterprise Linux vendor, Red Hat, Inc. is responsible for providing security patches. Warning: There is no remediation besides switching to a different operating system.
Rationale: | An operating system is considered "supported" if the vendor continues to provide security patches for the product. With an unsupported release, it will not be possible to resolve any security issue discovered in the system software.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_installed_OS_is_vendor_supported

References:

cis-csc | 18, 20, 4
cobit5 | APO12.01, APO12.02, APO12.03, APO12.04, BAI03.10, DSS05.01, DSS05.02
isa-62443-2009 | 4.2.3, 4.2.3.12, 4.2.3.7, 4.2.3.9
iso27001-2013 | A.12.6.1, A.14.2.3, A.16.1.3, A.18.2.2, A.18.2.3
nist | CM-6(a), MA-6, SA-13(a)
nist-csf | ID.RA-1, PR.IP-12
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257777r991589_rule

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 Encrypt Partitions [ref]

Red Hat Enterprise Linux 9 natively supports partition encryption through the Linux Unified Key Setup-on-disk-format (LUKS) technology. The easiest way to encrypt a partition is during installation time.
For manual installations, select the `Encrypt` checkbox during partition creation to encrypt the partition. When this option is selected the system will prompt for a passphrase to use in decrypting the partition. The passphrase will subsequently need to be entered manually every time the system boots.
For automated/unattended installations, it is possible to use Kickstart by adding the `--encrypted` and `--passphrase=` options to the definition of each partition to be encrypted. For example, the following line would encrypt the root partition:

    part / --fstype=ext4 --size=100 --onpart=hda1 --encrypted --passphrase=PASSPHRASE

Any PASSPHRASE is stored in the Kickstart in plaintext, and the Kickstart must then be protected accordingly. Omitting the `--passphrase=` option from the partition definition will cause the installer to pause and interactively ask for the passphrase during installation.
By default, the `Anaconda` installer uses `aes-xts-plain64` cipher with a minimum `512` bit key size which should be compatible with FIPS enabled.
Detailed information on encrypting partitions using LUKS or LUKS ciphers can be found on the Red Hat Enterprise Linux 9 Documentation web site:
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/security_hardening/encrypting-block-devices-using-luks_security-hardening .

Rationale: | The risk of a system's physical compromise, particularly mobile systems such as laptops, places its data at risk of compromise. Encrypting this data mitigates the risk of its loss if the system is lost.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_encrypt_partitions

References:

cis-csc | 13, 14
cobit5 | APO01.06, BAI02.01, BAI06.01, DSS04.07, DSS05.03, DSS05.04, DSS05.07, DSS06.02, DSS06.06
cui | 3.13.16
hipaa | 164.308(a)(1)(ii)(D), 164.308(b)(1), 164.310(d), 164.312(a)(1), 164.312(a)(2)(iii), 164.312(a)(2)(iv), 164.312(b), 164.312(c), 164.314(b)(2)(i), 164.312(d)
isa-62443-2013 | SR 3.4, SR 4.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 R4.2, CIP-007-3 R5.1
nist | CM-6(a), SC-28, SC-28(1), SC-13, AU-9(3)
nist-csf | PR.DS-1, PR.DS-5
os-srg | SRG-OS-000405-GPOS-00184, SRG-OS-000185-GPOS-00079, SRG-OS-000404-GPOS-00183
bsi | SYS.1.1.A34
stigref | SV-257879r1045454_rule

#### 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
bsi | SYS.1.1.A6
cis | 1.1.2.3.1
stigref | SV-257843r991589_rule

Remediation script ⇲

    logvol /home 1024

Remediation Anaconda snippet ⇲

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

    part /home

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/home"
    size = 1073741824

#### 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
bsi | SYS.1.1.A6
cis | 1.1.2.1.1
stigref | SV-257844r1044918_rule

Remediation script ⇲

    logvol /tmp 1024

Remediation Anaconda snippet ⇲

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

    part /tmp

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/tmp"
    size = 1073741824

#### 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
bsi | SYS.1.1.A6
cis | 1.1.2.4.1
stigref | SV-257845r1044920_rule

Remediation script ⇲

    logvol /var 3072

Remediation Anaconda snippet ⇲

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

    part /var

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/var"
    size = 3221225472

#### 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
bsi | SYS.1.1.A6
cis | 1.1.2.6.1
stigref | SV-257846r1044922_rule

Remediation script ⇲

    logvol /var/log 1024

Remediation Anaconda snippet ⇲

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

    part /var/log

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/var/log"
    size = 1073741824

#### 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
stigref | SV-257847r1044924_rule

Remediation script ⇲

    logvol /var/log/audit 10240

Remediation Anaconda snippet ⇲

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

    part /var/log/audit

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/var/log/audit"
    size = 10737418240

#### 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
bsi | SYS.1.1.A6
cis | 1.1.2.5.1
stigref | SV-257848r1044926_rule

Remediation script ⇲

    logvol /var/tmp 1024

Remediation Anaconda snippet ⇲

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

    part /var/tmp

Remediation OSBuild Blueprint snippet ⇲

    [[customizations.filesystem]]
    mountpoint = "/var/tmp"
    size = 1073741824

Group GNOME Desktop Environment Group contains 4 groups and 14 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 4 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 Restart and Shutdown Buttons [ref]

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

    [org/gnome/login-screen]
    disable-restart-buttons=true

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

    /org/gnome/login-screen/disable-restart-buttons

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

Rationale: | A user who is at the console can reboot the system at the login screen. If restart or shutdown buttons are pressed at the login screen, this can create the risk of short-term loss of availability of systems due to reboot.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_restart_shutdown

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.2
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), CM-7(b)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258029r1045109_rule, SV-258030r1045112_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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\|distro.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/distro.d/00-security-settings"
    DBDIR="/etc/dconf/db/distro.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-restart-buttons\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)disable-restart-buttons(\s*=)/#\1disable-restart-buttons\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-restart-buttons\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*disable-restart-buttons\\s*=\\s*.*/disable-restart-buttons=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/login-screen\\]|a\\disable-restart-buttons=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/login-screen/disable-restart-buttons$" "/etc/dconf/db/" \
                | grep -v 'distro\|ibus\|distro.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/distro.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-restart-buttons$|#&|" "${LOCKFILES[@]}"
    fi

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

    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:
      - DISA-STIG-RHEL-09-271095
      - DISA-STIG-RHEL-09-271100
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_restart_shutdown
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Disable the GNOME3 Login Restart and Shutdown Buttons
      community.general.ini_file:
        dest: /etc/dconf/db/distro.d/00-security-settings
        section: org/gnome/login-screen
        option: disable-restart-buttons
        value: 'true'
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271095
      - DISA-STIG-RHEL-09-271100
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_restart_shutdown
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME disablement of Login Restart and Shutdown
        Buttons
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/distro.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/login-screen/disable-restart-buttons
        line: /org/gnome/login-screen/disable-restart-buttons
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271095
      - DISA-STIG-RHEL-09-271100
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_restart_shutdown
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271095
      - DISA-STIG-RHEL-09-271100
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_restart_shutdown
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

#### 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/distro.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/distro.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.8.3
stigref | SV-258033r1045120_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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\|distro.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/distro.d/00-security-settings"
    DBDIR="/etc/dconf/db/distro.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\|distro.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/distro.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/distro.d/
    then
        echo "/org/gnome/login-screen/disable-user-list" >> "/etc/dconf/db/distro.d/locks/00-security-settings-lock"
    fi
    dconf update

    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:
      - DISA-STIG-RHEL-09-271115
      - NIST-800-53-AC-23
      - NIST-800-53-CM-6(a)
      - dconf_gnome_disable_user_list
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Disable the GNOME3 Login User List
      community.general.ini_file:
        dest: /etc/dconf/db/distro.d/00-security-settings
        section: org/gnome/login-screen
        option: disable-user-list
        value: 'true'
        no_extra_spaces: true
        create: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271115
      - NIST-800-53-AC-23
      - NIST-800-53-CM-6(a)
      - dconf_gnome_disable_user_list
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME3 disablement of Login User List
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/distro.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/login-screen/disable-user-list$
        line: /org/gnome/login-screen/disable-user-list
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271115
      - NIST-800-53-AC-23
      - NIST-800-53-CM-6(a)
      - dconf_gnome_disable_user_list
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271115
      - NIST-800-53-AC-23
      - NIST-800-53-CM-6(a)
      - dconf_gnome_disable_user_list
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Enable the GNOME3 Screen Locking On Smartcard Removal [ref]

In the default graphical environment, screen locking on smartcard removal can be enabled by setting `removal-action` to `'lock-screen'`.
To enable, add or edit `removal-action` to `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/settings-daemon/peripherals/smartcard]
    removal-action='lock-screen'

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

    /org/gnome/settings-daemon/peripherals/smartcard/removal-action

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

Rationale: | Locking the screen automatically when removing the smartcard can prevent undesired access to system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_lock_screen_on_smartcard_removal

References:

os-srg | SRG-OS-000028-GPOS-00009, SRG-OS-000030-GPOS-00011
stigref | SV-258019r1045092_rule, SV-258020r1045094_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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/settings-daemon/peripherals/smartcard\\]" "/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*removal-action\\s*=" "${SETTINGSFILES[@]}"
        then

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

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "'lock-screen'")"
    if grep -q "^\\s*removal-action\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*removal-action\\s*=\\s*.*/removal-action=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/settings-daemon/peripherals/smartcard\\]|a\\removal-action=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/settings-daemon/peripherals/smartcard/removal-action$" "/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/settings-daemon/peripherals/smartcard/removal-action$|#&|" "${LOCKFILES[@]}"
    fi

    if ! grep -qr "^/org/gnome/settings-daemon/peripherals/smartcard/removal-action$" /etc/dconf/db/local.d/
    then
        echo "/org/gnome/settings-daemon/peripherals/smartcard/removal-action" >> "/etc/dconf/db/local.d/locks/00-security-settings-lock"
    fi
    dconf update

    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:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Detect if removal-action can be found on /etc/dconf/db/local.d/
      ansible.builtin.find:
        path: /etc/dconf/db/local.d/
        contains: ^\s*removal-action
      register: dconf_gnome_lock_screen_on_smartcard_removal_config_files
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Configure removal-action - default file
      community.general.ini_file:
        dest: /etc/dconf/db/local.d//00-security-settings
        section: org/gnome/settings-daemon/peripherals/smartcard
        option: removal-action
        value: '''lock-screen'''
        create: true
      when:
      - '"gdm" in ansible_facts.packages'
      - dconf_gnome_lock_screen_on_smartcard_removal_config_files is defined and dconf_gnome_lock_screen_on_smartcard_removal_config_files.matched
        == 0
      register: default_file
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Configure removal-action - existing files
      community.general.ini_file:
        dest: '{{ item.path }}'
        section: org/gnome/settings-daemon/peripherals/smartcard
        option: removal-action
        value: '''lock-screen'''
        create: true
      with_items: '{{ dconf_gnome_lock_screen_on_smartcard_removal_config_files.files
        }}'
      when:
      - '"gdm" in ansible_facts.packages'
      - dconf_gnome_lock_screen_on_smartcard_removal_config_files is defined and dconf_gnome_lock_screen_on_smartcard_removal_config_files.matched
        > 0
      register: existing_files
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Detect if lock for removal-action can be found on /etc/dconf/db/local.d/
      ansible.builtin.find:
        path: /etc/dconf/db/local.d/locks
        contains: ^\s*removal-action
      register: dconf_gnome_lock_screen_on_smartcard_removal_lock_files
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification removal-action - default file
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/settings-daemon/peripherals/smartcard/removal-action$
        line: /org/gnome/settings-daemon/peripherals/smartcard/removal-action
        create: true
      when:
      - '"gdm" in ansible_facts.packages'
      - dconf_gnome_lock_screen_on_smartcard_removal_lock_files is defined and dconf_gnome_lock_screen_on_smartcard_removal_lock_files.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification removal-action - existing files
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^/org/gnome/settings-daemon/peripherals/smartcard/removal-action$
        line: /org/gnome/settings-daemon/peripherals/smartcard/removal-action
        create: true
      with_items: '{{ dconf_gnome_lock_screen_on_smartcard_removal_lock_files.files }}'
      when:
      - '"gdm" in ansible_facts.packages'
      - dconf_gnome_lock_screen_on_smartcard_removal_lock_files is defined and dconf_gnome_lock_screen_on_smartcard_removal_lock_files.matched
        > 0
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update - removal-action
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - default_file is changed or existing_files is changed
      tags:
      - DISA-STIG-RHEL-09-271045
      - DISA-STIG-RHEL-09-271050
      - dconf_gnome_lock_screen_on_smartcard_removal
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Disable GDM Automatic Login [ref]

The GNOME Display Manager (GDM) can allow users to automatically login without user interaction or credentials. User should always be required to authenticate themselves to the system that they are authorized to use. To disable user ability to automatically login to the system, set the `AutomaticLoginEnable` to `false` in the `[daemon]` section in `/etc/gdm/custom.conf`. For example:

    [daemon]
    AutomaticLoginEnable=false

Rationale: | Failure to restrict system access to authenticated users negatively impacts operating system security.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_gnome_gdm_disable_automatic_login

References:

cis-csc | 11, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.1.1
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), AC-6(1), CM-7(b)
nist-csf | PR.IP-1
os-srg | SRG-OS-000480-GPOS-00229
pcidss4 | 8.3.1, 8.3
stigref | SV-258018r1045090_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; then

    if rpm --quiet -q gdm
    then
    	if ! grep -q "^AutomaticLoginEnable=" /etc/gdm/custom.conf
    	then
    		sed -i "/^\[daemon\]/a \
    		AutomaticLoginEnable=False" /etc/gdm/custom.conf
    	else
    		sed -i "s/^AutomaticLoginEnable=.*/AutomaticLoginEnable=False/g" /etc/gdm/custom.conf
    	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:
      - DISA-STIG-RHEL-09-271040
      - NIST-800-171-3.1.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - gnome_gdm_disable_automatic_login
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Disable GDM Automatic Login
      community.general.ini_file:
        dest: /etc/gdm/custom.conf
        section: daemon
        option: AutomaticLoginEnable
        value: 'false'
        no_extra_spaces: true
        create: true
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271040
      - NIST-800-171-3.1.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - gnome_gdm_disable_automatic_login
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

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

#### 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
pcidss4 | 3.4.2, 3.4
cis | 1.8.6, 1.8.7
stigref | SV-258014r1045084_rule, SV-258015r1045086_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-271020
      - DISA-STIG-RHEL-09-271025
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - dconf_gnome_disable_automount_open
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Disable GNOME3 Automounting - automount-open
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/media-handling
        option: automount-open
        value: 'false'
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271020
      - DISA-STIG-RHEL-09-271025
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - dconf_gnome_disable_automount_open
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME3 Automounting - automount-open
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/media-handling/automount-open$
        line: /org/gnome/desktop/media-handling/automount-open
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271020
      - DISA-STIG-RHEL-09-271025
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - dconf_gnome_disable_automount_open
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271020
      - DISA-STIG-RHEL-09-271025
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - dconf_gnome_disable_automount_open
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### 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.8.8, 1.8.9
stigref | SV-258016r958804_rule, SV-258017r1045088_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-271030
      - DISA-STIG-RHEL-09-271035
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_autorun
      - low_complexity
      - low_severity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Disable GNOME3 Automounting - autorun-never
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/media-handling
        option: autorun-never
        value: 'true'
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271030
      - DISA-STIG-RHEL-09-271035
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_autorun
      - low_complexity
      - low_severity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME3 Automounting - autorun-never
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/media-handling/autorun-never$
        line: /org/gnome/desktop/media-handling/autorun-never
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271030
      - DISA-STIG-RHEL-09-271035
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_autorun
      - low_complexity
      - low_severity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271030
      - DISA-STIG-RHEL-09-271035
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_autorun
      - low_complexity
      - low_severity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

Group Configure GNOME Screen Locking Group contains 6 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
pcidss4 | 8.2.8, 8.2
cis | 1.8.4
stigref | SV-258023r958402_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271065
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_idle_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
    - name: XCCDF Value inactivity_timeout_value # promote to variable
      set_fact:
        inactivity_timeout_value: !!str 900
      tags:
        - always

    - name: Set GNOME3 Screensaver Inactivity Timeout
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/session
        option: idle-delay
        value: uint32 {{ inactivity_timeout_value }}
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271065
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_idle_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271065
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_idle_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### 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 0` in `/etc/dconf/db/local.d/00-security-settings`. For example:

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

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
pcidss4 | 8.2.8, 8.2
cis | 1.8.4
stigref | SV-258025r958402_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; then

    var_screensaver_lock_delay='0'

    # 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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-271075
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
    - name: XCCDF Value var_screensaver_lock_delay # promote to variable
      set_fact:
        var_screensaver_lock_delay: !!str 0
      tags:
        - always

    - name: Set GNOME3 Screensaver Lock Delay After Activation Period
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/screensaver
        option: lock-delay
        value: uint32 {{ var_screensaver_lock_delay }}
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271075
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed
      tags:
      - DISA-STIG-RHEL-09-271075
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_delay
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### 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
pcidss4 | 8.2.8, 8.2
stigref | SV-258021r1015088_rule, SV-258022r1045097_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Enable GNOME3 Screensaver
        Lock After Idle Period
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/screensaver
        option: lock-enabled
        value: 'true'
        create: true
        no_extra_spaces: true
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution != 'SLES'
      register: screensaver_config
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Prevent user modification
        of GNOME lock-enabled
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/screensaver/lock-enabled$
        line: /org/gnome/desktop/screensaver/lock-enabled
        create: true
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution != 'SLES'
      register: screensaver_lock
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Enable GNOME3 Screensaver
        Lock After Idle Period
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/lockdown
        option: disable-lock-screen
        value: 'false'
        create: true
        no_extra_spaces: true
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution == 'SLES'
      register: lockdown_config
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Prevent user modification
        of GNOME disable-lock-screen
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/lockdown/disable-lock-screen$
        line: /org/gnome/desktop/lockdown/disable-lock-screen
        create: true
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution == 'SLES'
      register: lockdown_lock
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Check GNOME3 screenserver
        disable-lock-screen false
      ansible.builtin.command: gsettings get org.gnome.desktop.lockdown disable-lock-screen
      register: cmd_out
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution == 'SLES'
      changed_when: false
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Update GNOME3 screenserver
        disable-lock-screen false
      ansible.builtin.command: gsettings set org.gnome.desktop.lockdown disable-lock-screen
        false
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution == 'SLES'
      - cmd_out.stdout != 'false'
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Update dconf database for
        non-SLES systems
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution != 'SLES'
      - (screensaver_config is changed or screensaver_lock is changed)
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Screensaver Lock After Idle Period - Update dconf database for
        SLES systems
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - ansible_distribution == 'SLES'
      - (lockdown_config is changed or lockdown_lock is changed)
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271055
      - DISA-STIG-RHEL-09-271060
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_lock_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Implement Blank Screensaver [ref]

To set the screensaver mode in the GNOME3 desktop to a blank screen, add or set `picture-uri` to `string ''` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/desktop/screensaver]
    picture-uri=string ''

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/picture-uri

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

Rationale: | Setting the screensaver mode to blank-only conceals the contents of the display from passersby.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_screensaver_mode_blank

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(1), CM-6(a), AC-11(1).1
nist-csf | PR.AC-7
pcidss | Req-8.1.8
os-srg | SRG-OS-000031-GPOS-00012
pcidss4 | 8.2.8, 8.2
stigref | SV-258027r1045106_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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*picture-uri\\s*=" "${SETTINGSFILES[@]}"
        then

            sed -Ei "s/(^\s*)picture-uri(\s*=)/#\1picture-uri\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' <<< "string ''")"
    if grep -q "^\\s*picture-uri\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*picture-uri\\s*=\\s*.*/picture-uri=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/desktop/screensaver\\]|a\\picture-uri=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/screensaver/picture-uri$" "/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/picture-uri$|#&|" "${LOCKFILES[@]}"
    fi

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

    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:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271085
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(1)
      - NIST-800-53-AC-11(1).1
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_mode_blank
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Implement Blank Screensaver
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/desktop/screensaver
        option: picture-uri
        value: string ''
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271085
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(1)
      - NIST-800-53-AC-11(1).1
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_mode_blank
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME picture-uri
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/screensaver/picture-uri$
        line: /org/gnome/desktop/screensaver/picture-uri
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271085
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(1)
      - NIST-800-53-AC-11(1).1
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_mode_blank
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - CJIS-5.5.5
      - DISA-STIG-RHEL-09-271085
      - NIST-800-171-3.1.10
      - NIST-800-53-AC-11(1)
      - NIST-800-53-AC-11(1).1
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_screensaver_mode_blank
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Ensure Users Cannot Change GNOME3 Screensaver Settings [ref]

If not already configured, ensure that users cannot change GNOME3 screensaver lock settings by adding `/org/gnome/desktop/screensaver/lock-delay` to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/screensaver/lock-delay

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

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, GNOME desktops can be configured to identify when a user's session has idled and take action to initiate the session lock. As such, users should not be allowed to change session settings.

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

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 | CM-6(a)
nist-csf | PR.AC-7
os-srg | SRG-OS-000029-GPOS-00010, SRG-OS-000031-GPOS-00012
cis | 1.8.5
stigref | SV-258026r1045103_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; then

    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/screensaver/lock-delay$" "/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-delay$|#&|" "${LOCKFILES[@]}"
    fi

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

    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:
      - DISA-STIG-RHEL-09-271080
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - dconf_gnome_screensaver_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME lock-delay
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/screensaver/lock-delay$
        line: /org/gnome/desktop/screensaver/lock-delay
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271080
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - dconf_gnome_screensaver_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271080
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - dconf_gnome_screensaver_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Ensure Users Cannot Change GNOME3 Session Idle Settings [ref]

If not already configured, ensure that users cannot change GNOME3 session idle settings by adding `/org/gnome/desktop/session/idle-delay` to `/etc/dconf/db/local.d/locks/00-security-settings-lock` to prevent user modification. For example:

    /org/gnome/desktop/session/idle-delay

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

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, GNOME desktops can be configured to identify when a user's session has idled and take action to initiate the session lock. As such, users should not be allowed to change session settings.

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

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 | 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
pcidss4 | 8.2.8, 8.2
cis | 1.8.5
stigref | SV-258024r1045100_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; then

    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/desktop/session/idle-delay$" "/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/session/idle-delay$|#&|" "${LOCKFILES[@]}"
    fi

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

    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:
      - DISA-STIG-RHEL-09-271070
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_session_idle_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME Session idle-delay
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/desktop/session/idle-delay$
        line: /org/gnome/desktop/session/idle-delay
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271070
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_session_idle_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271070
      - NIST-800-171-3.1.10
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.8
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_gnome_session_idle_user_locks
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

Group GNOME System Settings Group contains 1 rule

[ref] GNOME provides configuration and functionality to a graphical desktop environment that changes graphical configurations or allow a user to perform actions that users normally would not be able to do in non-graphical mode such as remote access configuration, power policies, Geo-location, etc. Configuring such settings in GNOME will prevent accidental graphical configuration changes by users from taking place.

#### Rule Disable Ctrl-Alt-Del Reboot Key Sequence in GNOME3 [ref]

By default, `GNOME` will reboot the system if the `Ctrl-Alt-Del` key sequence is pressed.
To configure the system to ignore the `Ctrl-Alt-Del` key sequence from the Graphical User Interface (GUI) instead of rebooting the system, add or set `logout` to `['']` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/settings-daemon/plugins/media-keys]
    logout=['']

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/settings-daemon/plugins/media-keys/logout

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

Rationale: | A locally logged-in user who presses Ctrl-Alt-Del, when at the console, can reboot the system. If accidentally pressed, as could happen in the case of mixed OS environment, this can create the risk of short-term loss of availability of systems due to unintentional reboot.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_gnome_disable_ctrlaltdel_reboot

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.2
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), CM-7(b)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258031r1045114_rule, SV-258032r1045117_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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/settings-daemon/plugins/media-keys\\]" "/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*logout\\s*=" "${SETTINGSFILES[@]}"
        then

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

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

    escaped_value="$(sed -e 's/\\/\\\\/g' <<< "['']")"
    if grep -q "^\\s*logout\\s*=" "${DCONFFILE}"
    then
            sed -i "s/\\s*logout\\s*=\\s*.*/logout=${escaped_value}/g" "${DCONFFILE}"
        else
            sed -i "\\|\\[org/gnome/settings-daemon/plugins/media-keys\\]|a\\logout=${escaped_value}" "${DCONFFILE}"
    fi
    dconf update
    # Check for setting in any of the DConf db directories
    LOCKFILES=$(grep -r "^/org/gnome/settings-daemon/plugins/media-keys/logout$" "/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/settings-daemon/plugins/media-keys/logout$|#&|" "${LOCKFILES[@]}"
    fi

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

    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:
      - DISA-STIG-RHEL-09-271105
      - DISA-STIG-RHEL-09-271110
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_ctrlaltdel_reboot
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Disable Ctrl-Alt-Del Reboot Key Sequence in GNOME3
      community.general.ini_file:
        dest: /etc/dconf/db/local.d/00-security-settings
        section: org/gnome/settings-daemon/plugins/media-keys
        option: logout
        value: '['''']'
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271105
      - DISA-STIG-RHEL-09-271110
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_ctrlaltdel_reboot
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME disablement of Ctrl-Alt-Del
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/local.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/settings-daemon/plugins/media-keys/logout$
        line: /org/gnome/settings-daemon/plugins/media-keys/logout
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271105
      - DISA-STIG-RHEL-09-271110
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_ctrlaltdel_reboot
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271105
      - DISA-STIG-RHEL-09-271110
      - NIST-800-171-3.1.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - dconf_gnome_disable_ctrlaltdel_reboot
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

#### Rule Make sure that the dconf databases are up-to-date with regards to respective keyfiles [ref]

By default, DConf uses a binary database as a data backend. The system-level database is compiled from keyfiles in the /etc/dconf/db/ directory by the

    dconf update

command. More specifically, content present in the following directories:

    /etc/dconf/db/distro.d

    /etc/dconf/db/local.d

Rationale: | Unlike text-based keyfiles, the binary database is impossible to check by OVAL. Therefore, in order to evaluate dconf configuration, both have to be true at the same time - configuration files have to be compliant, and the database needs to be more recent than those keyfiles, which gives confidence that it reflects them.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_dconf_db_up_to_date

References:

hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(5)(ii)(A)
pcidss | Req-6.2
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 8.2.8, 8.2
ccn | reload_dconf_db
cis | reload_dconf_db
stigref | SV-258028r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm && { rpm --quiet -q kernel-core; }; then

    dconf update

    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:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Get database modification time for distro
      ansible.builtin.stat:
        path: /etc/dconf/db/distro
      register: distro_db
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Get keyfiles for distro
      ansible.builtin.find:
        paths: /etc/dconf/db/distro.d/
      register: distro_keyfiles
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Run dconf update for distro
      ansible.builtin.command:
        cmd: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not distro_db.stat.exists or distro_keyfiles.files | length > 0 and distro_keyfiles.files
        | map(attribute='mtime') | max > distro_db.stat.mtime
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Get database modification time for local
      ansible.builtin.stat:
        path: /etc/dconf/db/local
      register: local_db
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Get keyfiles for local
      ansible.builtin.find:
        paths: /etc/dconf/db/local.d/
      register: local_keyfiles
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Make sure that the dconf databases are up-to-date with regards to respective
        keyfiles - Run dconf update for local
      ansible.builtin.command:
        cmd: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not local_db.stat.exists or local_keyfiles.files | length > 0 and local_keyfiles.files
        | map(attribute='mtime') | max > local_db.stat.mtime
      tags:
      - DISA-STIG-RHEL-09-271090
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-8.2
      - PCI-DSSv4-8.2.8
      - dconf_db_up_to_date
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

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:

    $ sudo dnf install sudo

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

References:

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

Remediation script ⇲

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

    dnf install sudo

Remediation script ⇲

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

    package install sudo

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "sudo" ; then
        dnf install -y "sudo"
    fi

    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 Anaconda snippet ⇲

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

    package --add=sudo

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-432010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432010
      - 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 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
ism | 1546
stigref | SV-258086r1102063_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-432025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432025
      - 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 NOPASSWD [ref]

The sudo `NOPASSWD` tag, when specified, allows a user to execute commands using sudo without having to authenticate. This should be disabled by making sure that the `NOPASSWD` tag 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_nopasswd

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
ism | 1546
stigref | SV-258106r1102061_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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

    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:
      - DISA-STIG-RHEL-09-611085
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_nopasswd

    - name: Find /etc/sudoers.d/ files
      ansible.builtin.find:
        paths:
        - /etc/sudoers.d/
      register: sudoers
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611085
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_nopasswd

    - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611085
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-11
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_remove_nopasswd

#### 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
pcidss4 | 2.2.6, 2.2
cis | 5.2.5, 5.2.6
stigref | SV-258084r1050789_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q sudo; }; then

    var_sudo_timestamp_timeout='0'

    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:
      - DISA-STIG-RHEL-09-432015
      - 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 0
      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:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432015
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432015
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432015
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-432015
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432015
      - 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

#### Rule The operating system must restrict privilege elevation to authorized personnel [ref]

The sudo command allows a user to execute programs with elevated (administrator) privileges. It prompts the user for their password and confirms your request to execute a command by checking a file, called sudoers. Restrict privileged actions by removing the following entries from the sudoers file: `ALL ALL=(ALL) ALL` `ALL ALL=(ALL:ALL) ALL`
Warning: This rule doesn't come with a remediation, as the exact requirement allows exceptions, and removing lines from the sudoers file can make the system non-administrable.

Rationale: | If the "sudoers" file is not configured correctly, any user defined on the system can initiate privileged actions on the target system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_restrict_privilege_elevation_to_authorized

References:

nist | CM-6(b), CM-6(iv)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258087r1102071_rule

#### Rule Ensure invoking users password for privilege escalation when using sudo [ref]

The sudoers security policy requires that users authenticate themselves before they can use sudo. When sudoers requires authentication, it validates the invoking user's credentials. The expected output for:

     sudo cvtsudoers -f sudoers /etc/sudoers | grep -E '^Defaults !?(rootpw|targetpw|runaspw)$'

     Defaults !targetpw
          Defaults !rootpw
          Defaults !runaspw

or if cvtsudoers not supported:

     sudo find /etc/sudoers /etc/sudoers.d \( \! -name '*~' -a \! -name '*.*' \) -exec grep -E --with-filename '^[[:blank:]]*Defaults[[:blank:]](.*[[:blank:]])?!?\b(rootpw|targetpw|runaspw)' -- {} \;

     /etc/sudoers:Defaults !targetpw
          /etc/sudoers:Defaults !rootpw
          /etc/sudoers:Defaults !runaspw

Rationale: | If the rootpw, targetpw, or runaspw flags are defined and not disabled, by default the operating system will prompt the invoking user for the "root" user password.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudoers_validate_passwd

References:

nist | CM-6(b), CM-6.1(iv)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258085r1045173_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q sudo; }; then

    if grep -x '^Defaults targetpw$' /etc/sudoers; then
        sed -i "/Defaults targetpw/d" /etc/sudoers \;
    fi
    if grep -x '^Defaults targetpw$' /etc/sudoers.d/*; then
        find /etc/sudoers.d/ -type f -exec sed -i "/Defaults targetpw/d" {} \;
    fi
    if grep -x '^Defaults rootpw$' /etc/sudoers; then
        sed -i "/Defaults rootpw/d" /etc/sudoers \;
    fi
    if grep -x '^Defaults rootpw$' /etc/sudoers.d/*; then
        find /etc/sudoers.d/ -type f -exec sed -i "/Defaults rootpw/d" {} \;
    fi
    if grep -x '^Defaults runaspw$' /etc/sudoers; then
        sed -i "/Defaults runaspw/d" /etc/sudoers \;
    fi
    if grep -x '^Defaults runaspw$' /etc/sudoers.d/*; then
        find /etc/sudoers.d/ -type f -exec sed -i "/Defaults runaspw/d" {} \;
    fi

    if [ -e "/etc/sudoers" ] ; then

        LC_ALL=C sed -i "/Defaults !targetpw/d" "/etc/sudoers"
    else
        touch "/etc/sudoers"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/sudoers"

    cp "/etc/sudoers" "/etc/sudoers.bak"
    # Insert at the end of the file
    printf '%s\n' "Defaults !targetpw" >> "/etc/sudoers"
    # Clean up after ourselves.
    rm "/etc/sudoers.bak"
    if [ -e "/etc/sudoers" ] ; then

        LC_ALL=C sed -i "/Defaults !rootpw/d" "/etc/sudoers"
    else
        touch "/etc/sudoers"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/sudoers"

    cp "/etc/sudoers" "/etc/sudoers.bak"
    # Insert at the end of the file
    printf '%s\n' "Defaults !rootpw" >> "/etc/sudoers"
    # Clean up after ourselves.
    rm "/etc/sudoers.bak"
    if [ -e "/etc/sudoers" ] ; then

        LC_ALL=C sed -i "/Defaults !runaspw/d" "/etc/sudoers"
    else
        touch "/etc/sudoers"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/sudoers"

    cp "/etc/sudoers" "/etc/sudoers.bak"
    # Insert at the end of the file
    printf '%s\n' "Defaults !runaspw" >> "/etc/sudoers"
    # Clean up after ourselves.
    rm "/etc/sudoers.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:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Find out if /etc/sudoers.d/* files contain Defaults targetpw to be deduplicated
      ansible.builtin.find:
        path: /etc/sudoers.d
        patterns: '*'
        contains: ^Defaults targetpw$
      register: sudoers_d_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove found occurrences of Defaults targetpw from /etc/sudoers.d/* files
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^Defaults targetpw$
        state: absent
      with_items: '{{ sudoers_d_defaults.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Find out if /etc/sudoers.d/* files contain Defaults rootpw to be deduplicated
      ansible.builtin.find:
        path: /etc/sudoers.d
        patterns: '*'
        contains: ^Defaults rootpw$
      register: sudoers_d_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove found occurrences of Defaults rootpw from /etc/sudoers.d/* files
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^Defaults rootpw$
        state: absent
      with_items: '{{ sudoers_d_defaults.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Find out if /etc/sudoers.d/* files contain Defaults runaspw to be deduplicated
      ansible.builtin.find:
        path: /etc/sudoers.d
        patterns: '*'
        contains: ^Defaults runaspw$
      register: sudoers_d_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove found occurrences of Defaults runaspw from /etc/sudoers.d/* files
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^Defaults runaspw$
        state: absent
      with_items: '{{ sudoers_d_defaults.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove any occurrences of Defaults targetpw in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^Defaults targetpw$
        validate: /usr/sbin/visudo -cf %s
        state: absent
      register: sudoers_file_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove any occurrences of Defaults rootpw in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^Defaults rootpw$
        validate: /usr/sbin/visudo -cf %s
        state: absent
      register: sudoers_file_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Remove any occurrences of Defaults runaspw in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^Defaults runaspw$
        validate: /usr/sbin/visudo -cf %s
        state: absent
      register: sudoers_file_defaults
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Check for duplicate values
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !targetpw$
        state: absent
      check_mode: true
      changed_when: false
      register: dupes
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Deduplicate values from /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !targetpw$
        state: absent
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - dupes.found is defined and dupes.found > 1
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Insert correct line into /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !targetpw$
        line: Defaults !targetpw
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Check for duplicate values
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !rootpw$
        state: absent
      check_mode: true
      changed_when: false
      register: dupes
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Deduplicate values from /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !rootpw$
        state: absent
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - dupes.found is defined and dupes.found > 1
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Insert correct line into /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !rootpw$
        line: Defaults !rootpw
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Check for duplicate values
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !runaspw$
        state: absent
      check_mode: true
      changed_when: false
      register: dupes
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Deduplicate values from /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !runaspw$
        state: absent
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - dupes.found is defined and dupes.found > 1
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

    - name: Insert correct line into /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        create: false
        regexp: ^Defaults !runaspw$
        line: Defaults !runaspw
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432020
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudoers_validate_passwd

Group System Tooling / Utilities Group contains 7 rules
[ref] The following checks evaluate the system for recommended base packages -- both for installation and removal.

#### Rule Ensure gnutls-utils is installed [ref]

The `gnutls-utils` package can be installed with the following command:

    $ sudo dnf install gnutls-utils

Rationale:

GnuTLS is a secure communications library implementing the SSL, TLS and DTLS protocols and technologies around them. It provides a simple C language application programming interface (API) to access the secure communications protocols as well as APIs to parse and write X.509, PKCS #12, OpenPGP and other required structures. This package contains command line TLS client and server and certificate manipulation tools.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_gnutls-utils_installed

References:

ospp | FIA_X509_EXT.1, FIA_X509_EXT.1.1, FIA_X509_EXT.2
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257839r991589_rule

Remediation script ⇲

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

    dnf install gnutls-utils

Remediation script ⇲

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

    package install gnutls-utils

Remediation Shell script ⇲

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

    if ! rpm -q --quiet "gnutls-utils" ; then
        dnf install -y "gnutls-utils"
    fi

Remediation Puppet snippet ⇲

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

    include install_gnutls-utils

    class install_gnutls-utils {
      package { 'gnutls-utils':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=gnutls-utils

Remediation Ansible snippet ⇲

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

    - name: Ensure gnutls-utils is installed
      ansible.builtin.package:
        name: gnutls-utils
        state: present
      tags:
      - DISA-STIG-RHEL-09-215080
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_gnutls-utils_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Ensure nss-tools is installed [ref]

The `nss-tools` package can be installed with the following command:

    $ sudo dnf install nss-tools

Rationale: | Network Security Services (NSS) is a set of libraries designed to support cross-platform development of security-enabled client and server applications. Install the `nss-tools` package to install command-line tools to manipulate the NSS certificate and key database.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_nss-tools_installed

References:

ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257840r991589_rule

Remediation script ⇲

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

    dnf install nss-tools

Remediation script ⇲

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

    package install nss-tools

Remediation Shell script ⇲

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

    if ! rpm -q --quiet "nss-tools" ; then
        dnf install -y "nss-tools"
    fi

Remediation Puppet snippet ⇲

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

    include install_nss-tools

    class install_nss-tools {
      package { 'nss-tools':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=nss-tools

Remediation Ansible snippet ⇲

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

    - name: Ensure nss-tools is installed
      ansible.builtin.package:
        name: nss-tools
        state: present
      tags:
      - DISA-STIG-RHEL-09-215085
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_nss-tools_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "nss-tools"
    version = "*"

#### Rule Install rng-tools Package [ref]

The `rng-tools` package can be installed with the following command:

    $ sudo dnf install rng-tools

Rationale: | `rng-tools` provides hardware random number generator tools, such as those used in the formation of x509/PKI certificates.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_rng-tools_installed

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257841r1044914_rule

Remediation script ⇲

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

    dnf install rng-tools

Remediation script ⇲

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

    package install rng-tools

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if ( ! ( [ "$(sysctl -a | grep -c 'fips_enabled.*1')" -eq 1 ] ) && rpm --quiet -q kernel-core ); then

    if ! rpm -q --quiet "rng-tools" ; then
        dnf install -y "rng-tools"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_rng-tools

    class install_rng-tools {
      package { 'rng-tools':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=rng-tools

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-215090
      - enable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_rng-tools_installed

    - name: Ensure rng-tools is installed
      ansible.builtin.package:
        name: rng-tools
        state: present
      when: ( "kernel-core" in ansible_facts.packages )
      tags:
      - DISA-STIG-RHEL-09-215090
      - enable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_rng-tools_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "rng-tools"
    version = "*"

#### Rule Install subscription-manager Package [ref]

The `subscription-manager` package can be installed with the following command:

    $ sudo dnf install subscription-manager

Rationale:

Red Hat Subscription Manager is a local service which tracks installed products and subscriptions on a local system to help manage subscription assignments. It communicates with the backend subscription service (the Customer Portal or an on-premise server such as Subscription Asset Manager) and works with content management tools such as . The package provides, among other things, plugins to interact with repositories and subscriptions from the Red Hat entitlement platform - the subscription-manager and product-id plugins.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_subscription-manager_installed

References:

ospp | FPT_TUD_EXT.1, FPT_TUD_EXT.2
os-srg | SRG-OS-000366-GPOS-00153
ism | 1467, 1483, 1493
stigref | SV-257825r1044888_rule

Remediation script ⇲

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

    dnf install subscription-manager

Remediation script ⇲

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

    package install subscription-manager

Remediation Shell script ⇲

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

    if ! rpm -q --quiet "subscription-manager" ; then
        dnf install -y "subscription-manager"
    fi

Remediation Puppet snippet ⇲

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

    include install_subscription-manager

    class install_subscription-manager {
      package { 'subscription-manager':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=subscription-manager

Remediation Ansible snippet ⇲

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

    - name: Ensure subscription-manager is installed
      ansible.builtin.package:
        name: subscription-manager
        state: present
      tags:
      - DISA-STIG-RHEL-09-215010
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_subscription-manager_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "subscription-manager"
    version = "*"

#### Rule Uninstall gssproxy Package [ref]

The `gssproxy` package can be removed with the following command:

    $ sudo dnf remove gssproxy

Rationale: | `gssproxy` is a proxy for GSS API credential handling. Kerberos relies on some key derivation functions that may not be compatible with some site policies such as FIPS 140.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_gssproxy_removed

References:

os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
stigref | SV-257832r1044900_rule

Remediation script ⇲

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

    dnf remove gssproxy

Remediation script ⇲

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

    package remove gssproxy

Remediation Shell script ⇲

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

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

    if rpm -q --quiet "gssproxy" ; then
    dnf remove -y --noautoremove "gssproxy"
    fi

Remediation Puppet snippet ⇲

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

    include remove_gssproxy

    class remove_gssproxy {
      package { 'gssproxy':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall gssproxy Package: Ensure gssproxy is removed'
      ansible.builtin.package:
        name: gssproxy
        state: absent
      tags:
      - DISA-STIG-RHEL-09-215045
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_gssproxy_removed

#### Rule Uninstall iprutils Package [ref]

The `iprutils` package can be removed with the following command:

    $ sudo dnf remove iprutils

Rationale: | `iprutils` provides a suite of utlilities to manage and configure SCSI devices supported by the ipr SCSI storage device driver.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_iprutils_removed

References:

os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
stigref | SV-257833r1044902_rule

Remediation script ⇲

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

    dnf remove iprutils

Remediation script ⇲

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

    package remove iprutils

Remediation Shell script ⇲

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

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

    if rpm -q --quiet "iprutils" ; then
    dnf remove -y --noautoremove "iprutils"
    fi

Remediation Puppet snippet ⇲

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

    include remove_iprutils

    class remove_iprutils {
      package { 'iprutils':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=iprutils

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall iprutils Package: Ensure iprutils is removed'
      ansible.builtin.package:
        name: iprutils
        state: absent
      tags:
      - DISA-STIG-RHEL-09-215050
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_iprutils_removed

#### Rule Uninstall tuned Package [ref]

The `tuned` package can be removed with the following command:

    $ sudo dnf remove tuned

Rationale: | `tuned` contains a daemon that tunes the system settings dynamically. It does so by monitoring the usage of several system components periodically. Based on that information, components will then be put into lower or higher power savings modes to adapt to the current usage.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_tuned_removed

References:

os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
stigref | SV-257834r1044904_rule

Remediation script ⇲

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

    dnf remove tuned

Remediation script ⇲

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

    package remove tuned

Remediation Shell script ⇲

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

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

    if rpm -q --quiet "tuned" ; then
    dnf remove -y --noautoremove "tuned"
    fi

Remediation Puppet snippet ⇲

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

    include remove_tuned

    class remove_tuned {
      package { 'tuned':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=tuned

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall tuned Package: Ensure tuned is removed'
      ansible.builtin.package:
        name: tuned
        state: absent
      tags:
      - DISA-STIG-RHEL-09-215055
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_tuned_removed

Group Updating Software Group contains 6 rules

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

#### Rule Ensure dnf Removes Previous Package Versions [ref]

`dnf` should be configured to remove previous software components after new versions have been installed. To configure `dnf` to remove the previous software components after updating, set the `clean_requirements_on_remove` to `1` in `/etc/dnf/dnf.conf`.
Rationale: | Previous versions of software components that are not removed from the information system after updates have been installed may be exploited by some adversaries.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_clean_components_post_updating

References:

cis-csc | 18, 20, 4
cobit5 | APO12.01, APO12.02, APO12.03, APO12.04, BAI03.10, DSS05.01, DSS05.02
cui | 3.4.8
isa-62443-2009 | 4.2.3, 4.2.3.12, 4.2.3.7, 4.2.3.9
iso27001-2013 | A.12.6.1, A.14.2.3, A.16.1.3, A.18.2.2, A.18.2.3
nist | SI-2(6), CM-11(a), CM-11(b), CM-6(a)
nist-csf | ID.RA-1, PR.IP-12
os-srg | SRG-OS-000437-GPOS-00194
stigref | SV-257824r1044886_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && rpm --quiet -q dnf ); then

    if grep --silent ^clean_requirements_on_remove /etc/dnf/dnf.conf ; then
            sed -i "s/^clean_requirements_on_remove.*/clean_requirements_on_remove=1/g" /etc/dnf/dnf.conf
    else
            echo -e "\n# Set clean_requirements_on_remove to 1 per security requirements" >> /etc/dnf/dnf.conf
            echo "clean_requirements_on_remove=1" >> /etc/dnf/dnf.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:
      - DISA-STIG-RHEL-09-214035
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-2(6)
      - clean_components_post_updating
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure dnf Removes Previous Package Versions - Ensure DNF Removes Previous
        Package Versions
      ansible.builtin.lineinfile:
        dest: /etc/dnf/dnf.conf
        regexp: ^#?clean_requirements_on_remove
        line: clean_requirements_on_remove=1
        insertafter: \[main\]
        create: true
      when: ( not ( "kernel-core" 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 "dnf" in ansible_facts.packages )
      tags:
      - DISA-STIG-RHEL-09-214035
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-2(6)
      - clean_components_post_updating
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure gpgcheck Enabled In Main dnf Configuration [ref]

The `gpgcheck` option controls whether RPM packages' signatures are always checked prior to installation. To configure dnf to check package signatures before installing them, ensure the following line appears in `/etc/dnf/dnf.conf` in the `[main]` section:

    gpgcheck=1

Rationale:

Changes to any software components can have significant effects on the overall security of the operating system. This requirement ensures the software has not been tampered with and that it has been provided by a trusted vendor.
Accordingly, patches, service packs, device drivers, or operating system components must be signed with a certificate recognized and approved by the organization.
Verifying the authenticity of the software prior to installation validates the integrity of the patch or upgrade received from a vendor. This ensures the software has not been tampered with and that it has been provided by a trusted vendor. Self-signed certificates are disallowed by this requirement. Certificates used to verify the software must be from an approved Certificate Authority (CA).

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_gpgcheck_globally_activated

References:

cis-csc | 11, 2, 3, 9
cjis | 5.10.4.1
cobit5 | APO01.06, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS06.02
cui | 3.4.8
hipaa | 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i)
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 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.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
nist | CM-5(3), SI-7, SC-12, SC-12(3), CM-6(a), SA-12, SA-12(10), CM-11(a), CM-11(b)
nist-csf | PR.DS-6, PR.DS-8, PR.IP-1
ospp | FPT_TUD_EXT.1, FPT_TUD_EXT.2
pcidss | Req-6.2
os-srg | SRG-OS-000366-GPOS-00153
anssi | R59
ism | 1493
pcidss4 | 6.3.3, 6.3
cis | 1.2.1.2
stigref | SV-257820r1044878_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q dnf; then

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214015
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - configure_strategy
      - ensure_gpgcheck_globally_activated
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed

    - name: Ensure GPG check is globally activated
      community.general.ini_file:
        dest: /etc/dnf/dnf.conf
        section: main
        option: gpgcheck
        value: 1
        no_extra_spaces: true
        create: false
      when: '"dnf" in ansible_facts.packages'
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214015
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - configure_strategy
      - ensure_gpgcheck_globally_activated
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed

#### Rule Ensure gpgcheck Enabled for Local Packages [ref]

`dnf` should be configured to verify the signature(s) of local packages prior to installation. To configure `dnf` to verify signatures of local packages, set the `localpkg_gpgcheck` to `1` in `/etc/dnf/dnf.conf`.
Rationale: | Changes to any software components can have significant effects to the overall security of the operating system. This requirement ensures the software has not been tampered and has been provided by a trusted vendor. Accordingly, patches, service packs, device drivers, or operating system components must be signed with a certificate recognized and approved by the organization.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_gpgcheck_local_packages

References:

cis-csc | 11, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.4.8
hipaa | 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i)
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-11(a), CM-11(b), CM-6(a), CM-5(3), SA-12, SA-12(10)
nist-csf | PR.IP-1
ospp | FPT_TUD_EXT.1, FPT_TUD_EXT.2
os-srg | SRG-OS-000366-GPOS-00153
anssi | R59
ism | 1493
stigref | SV-257821r1015077_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q dnf; then

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

    # 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 "^localpkg_gpgcheck\\>" "/etc/dnf/dnf.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^localpkg_gpgcheck\\>.*/$escaped_formatted_output/gi" "/etc/dnf/dnf.conf"
    else
        if [[ -s "/etc/dnf/dnf.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/dnf/dnf.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/dnf/dnf.conf"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/dnf/dnf.conf" >> "/etc/dnf/dnf.conf"
        printf '%s\n' "$formatted_output" >> "/etc/dnf/dnf.conf"
    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:
      - DISA-STIG-RHEL-09-214020
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - ensure_gpgcheck_local_packages
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

    - name: Ensure GPG check Enabled for Local Packages (dnf)
      block:

      - name: Check stats of dnf
        ansible.builtin.stat:
          path: /etc/dnf/dnf.conf
        register: pkg

      - name: Check if config file of dnf is a symlink
        ansible.builtin.set_fact:
          pkg_config_file_symlink: '{{ pkg.stat.lnk_target if pkg.stat.lnk_target is match("^/.*")
            else "/etc/dnf/dnf.conf" | dirname ~ "/" ~ pkg.stat.lnk_target }}'
        when: pkg.stat.lnk_target is defined

      - name: Ensure GPG check Enabled for Local Packages (dnf)
        community.general.ini_file:
          dest: '{{ pkg_config_file_symlink |  default("/etc/dnf/dnf.conf") }}'
          section: main
          option: localpkg_gpgcheck
          value: 1
          no_extra_spaces: true
          create: true
      when: '"dnf" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-214020
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - ensure_gpgcheck_local_packages
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed
      - unknown_strategy

#### Rule Ensure gpgcheck Enabled for All dnf Package Repositories [ref]

To ensure signature checking is not disabled for any repos, remove any lines from files in `/etc/yum.repos.d` of the form:

    gpgcheck=0

Rationale:

Verifying the authenticity of the software prior to installation validates the integrity of the patch or upgrade received from a vendor. This ensures the software has not been tampered with and that it has been provided by a trusted vendor. Self-signed certificates are disallowed by this requirement. Certificates used to verify the software must be from an approved Certificate Authority (CA)."

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_gpgcheck_never_disabled

References:

cis-csc | 11, 2, 3, 9
cjis | 5.10.4.1
cobit5 | APO01.06, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS06.02
cui | 3.4.8
hipaa | 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i)
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 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.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
nist | CM-5(3), SI-7, SC-12, SC-12(3), CM-6(a), SA-12, SA-12(10), CM-11(a), CM-11(b)
nist-csf | PR.DS-6, PR.DS-8, PR.IP-1
ospp | FPT_TUD_EXT.1, FPT_TUD_EXT.2
pcidss | Req-6.2
os-srg | SRG-OS-000366-GPOS-00153
anssi | R59
ism | 1493
pcidss4 | 6.3.3, 6.3
cis | 1.2.1.2
stigref | SV-257822r1044880_rule

Remediation Shell script ⇲

    sed -i 's/gpgcheck\s*=.*/gpgcheck=1/g' /etc/yum.repos.d/*

Remediation Ansible snippet ⇲

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

    - name: Grep for dnf repo section names
      ansible.builtin.shell: |
        set -o pipefail
        grep -HEr '^\[.+\]' -r /etc/yum.repos.d/
      register: repo_grep_results
      failed_when: repo_grep_results.rc not in [0, 1]
      changed_when: false
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214025
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - enable_strategy
      - ensure_gpgcheck_never_disabled
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed

    - name: Set gpgcheck=1 for each dnf repo
      community.general.ini_file:
        path: '{{ item[0] }}'
        section: '{{ item[1] }}'
        option: gpgcheck
        value: '1'
        no_extra_spaces: true
      loop: '{{ repo_grep_results.stdout |regex_findall( ''(.+\.repo):\[(.+)\]\n?'' )
        if repo_grep_results is not skipped else [] }}'
      when: repo_grep_results is not skipped
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214025
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-11(a)
      - NIST-800-53-CM-11(b)
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SA-12
      - NIST-800-53-SA-12(10)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - enable_strategy
      - ensure_gpgcheck_never_disabled
      - high_severity
      - low_complexity
      - medium_disruption
      - no_reboot_needed

#### Rule Ensure Red Hat GPG Key Installed [ref]

To ensure the system can cryptographically verify base software packages come from Red Hat (and to connect to the Red Hat Network to receive them), the Red Hat GPG key must properly be installed. To install the Red Hat GPG key, run:

    $ sudo subscription-manager register

If the system is not connected to the Internet or an RHN Satellite, then install the Red Hat GPG key from trusted media such as the Red Hat installation CD-ROM or DVD. Assuming the disc is mounted in `/media/cdrom`, use the following command as the root user to import it into the keyring:

    $ sudo rpm --import /media/cdrom/RPM-GPG-KEY

Alternatively, the key may be pre-loaded during the RHEL installation. In such cases, the key can be installed by running the following command:

    sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

Rationale: | Changes to software components can have significant effects on the overall security of the operating system. This requirement ensures the software has not been tampered with and that it has been provided by a trusted vendor. The Red Hat GPG key is necessary to cryptographically verify packages are from Red Hat.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_redhat_gpgkey_installed

References:

cis-csc | 11, 2, 3, 9
cjis | 5.10.4.1
cobit5 | APO01.06, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS06.02
cui | 3.4.8
hipaa | 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i)
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 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.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
nerc-cip | CIP-003-8 R4.2, CIP-003-8 R6, CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-5(3), SI-7, SC-12, SC-12(3), CM-6(a)
nist-csf | PR.DS-6, PR.DS-8, PR.IP-1
ospp | FPT_TUD_EXT.1, FPT_TUD_EXT.2
pcidss | Req-6.2
os-srg | SRG-OS-000366-GPOS-00153
anssi | R59
ism | 1493
pcidss4 | 6.3.3, 6.3
stigref | SV-257819r1015075_rule

Remediation Shell script ⇲

    # The two fingerprints below are retrieved from https://access.redhat.com/security/team/key
    readonly REDHAT_RELEASE_FINGERPRINT="567E347AD0044ADE55BA8A5F199E2F91FD431D51"
    readonly REDHAT_AUXILIARY_FINGERPRINT="7E4624258C406535D56D6F135054E4A45A6340B3"

    # Location of the key we would like to import (once it's integrity verified)
    readonly REDHAT_RELEASE_KEY="/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release"

    RPM_GPG_DIR_PERMS=$(stat -c %a "$(dirname "$REDHAT_RELEASE_KEY")")

    # Verify /etc/pki/rpm-gpg directory permissions are safe
    if [ "${RPM_GPG_DIR_PERMS}" -le "755" ]
    then
      # If they are safe, try to obtain fingerprints from the key file
      # (to ensure there won't be e.g. CRC error).
      readarray -t GPG_OUT < <(gpg --show-keys --with-fingerprint --with-colons "$REDHAT_RELEASE_KEY" | grep -A1 "^pub" | grep "^fpr" | cut -d ":" -f 10)
      GPG_RESULT=$?
      # No CRC error, safe to proceed
      if [ "${GPG_RESULT}" -eq "0" ]
      then
        echo "${GPG_OUT[*]}" | grep -vE "${REDHAT_RELEASE_FINGERPRINT}|${REDHAT_AUXILIARY_FINGERPRINT}" || {
          # If $REDHAT_RELEASE_KEY file doesn't contain any keys with unknown fingerprint, import it
          rpm --import "${REDHAT_RELEASE_KEY}"
        }
      fi
    fi

Remediation Ansible snippet ⇲

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

    - name: Read permission of GPG key directory
      ansible.builtin.stat:
        path: /etc/pki/rpm-gpg/
      register: gpg_key_directory_permission
      check_mode: false
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214010
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - ensure_redhat_gpgkey_installed
      - high_severity
      - medium_complexity
      - medium_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Read signatures in GPG key
      ansible.builtin.command: gpg --show-keys --with-fingerprint --with-colons "/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release"
      changed_when: false
      register: gpg_fingerprints
      failed_when: false
      check_mode: false
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214010
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - ensure_redhat_gpgkey_installed
      - high_severity
      - medium_complexity
      - medium_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Set Fact - Installed GPG Fingerprints
      ansible.builtin.set_fact:
        gpg_installed_fingerprints: |-
          {{ gpg_fingerprints.stdout | regex_findall('^pub.*
          (?:^fpr[:]*)([0-9A-Fa-f]*)', '\1') | list }}
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214010
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - ensure_redhat_gpgkey_installed
      - high_severity
      - medium_complexity
      - medium_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Set Fact - Valid fingerprints
      ansible.builtin.set_fact:
        gpg_valid_fingerprints:
        - 567E347AD0044ADE55BA8A5F199E2F91FD431D51
        - 7E4624258C406535D56D6F135054E4A45A6340B3
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214010
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - ensure_redhat_gpgkey_installed
      - high_severity
      - medium_complexity
      - medium_disruption
      - no_reboot_needed
      - restrict_strategy

    - name: Import RedHat GPG key
      ansible.builtin.rpm_key:
        state: present
        key: /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
      when:
      - gpg_key_directory_permission.stat.mode <= '0755'
      - (gpg_installed_fingerprints | difference(gpg_valid_fingerprints)) | length ==
        0
      - gpg_installed_fingerprints | length > 0
      - ansible_distribution == "RedHat"
      tags:
      - CJIS-5.10.4.1
      - DISA-STIG-RHEL-09-214010
      - NIST-800-171-3.4.8
      - NIST-800-53-CM-5(3)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-12
      - NIST-800-53-SC-12(3)
      - NIST-800-53-SI-7
      - PCI-DSS-Req-6.2
      - PCI-DSSv4-6.3
      - PCI-DSSv4-6.3.3
      - ensure_redhat_gpgkey_installed
      - high_severity
      - medium_complexity
      - medium_disruption
      - no_reboot_needed
      - restrict_strategy

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

If the system is joined to the Red Hat Network, a Red Hat Satellite Server, or a yum server, run the following command to install updates:

    $ sudo yum update

If the system is not configured to use one of these sources, updates (in the form of RPM packages) can be manually downloaded from the Red Hat Network and installed using `rpm`.
NOTE: U.S. Defense systems are required to be patched within 30 days or sooner as local policy dictates.
Warning: Red Hat Enterprise Linux 9 does not have a corresponding OVAL CVE Feed. Therefore, this will result in a "not checked" result during a scan.

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

References:

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

Group Account and Access Control Group contains 17 groups and 78 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 Red Hat Enterprise Linux 9.

Group Warning Banners for System Accesses Group contains 1 group and 3 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/distro.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/distro.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.8.2
stigref | SV-258012r1014855_rule, SV-258013r1045082_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; 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\|distro.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/distro.d/00-security-settings"
    DBDIR="/etc/dconf/db/distro.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\|distro.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/distro.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/distro.d/
    then
        echo "/org/gnome/login-screen/banner-message-enable" >> "/etc/dconf/db/distro.d/locks/00-security-settings-lock"
    fi
    dconf update

    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:
      - DISA-STIG-RHEL-09-271010
      - DISA-STIG-RHEL-09-271015
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(b)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_banner_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Enable GNOME3 Login Warning Banner
      community.general.ini_file:
        dest: /etc/dconf/db/distro.d/00-security-settings
        section: org/gnome/login-screen
        option: banner-message-enable
        value: 'true'
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271010
      - DISA-STIG-RHEL-09-271015
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(b)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_banner_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of GNOME banner-message-enabled
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/distro.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/login-screen/banner-message-enable$
        line: /org/gnome/login-screen/banner-message-enable
        create: true
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-271010
      - DISA-STIG-RHEL-09-271015
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(b)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_banner_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-271010
      - DISA-STIG-RHEL-09-271015
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(b)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_banner_enabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### 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/distro.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/distro.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.8.2
stigref | SV-270174r1044831_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q gdm; then

    login_banner_text='^(You[\s\n]+are[\s\n]+accessing[\s\n]+a[\s\n]+U\.S\.[\s\n]+Government[\s\n]+\(USG\)[\s\n]+Information[\s\n]+System[\s\n]+\(IS\)[\s\n]+that[\s\n]+is[\s\n]+provided[\s\n]+for[\s\n]+USG\-authorized[\s\n]+use[\s\n]+only\.[\s\n]+By[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+\(which[\s\n]+includes[\s\n]+any[\s\n]+device[\s\n]+attached[\s\n]+to[\s\n]+this[\s\n]+IS\),[\s\n]+you[\s\n]+consent[\s\n]+to[\s\n]+the[\s\n]+following[\s\n]+conditions\:(?:[\n]+|(?:\\n)+)\-The[\s\n]+USG[\s\n]+routinely[\s\n]+intercepts[\s\n]+and[\s\n]+monitors[\s\n]+communications[\s\n]+on[\s\n]+this[\s\n]+IS[\s\n]+for[\s\n]+purposes[\s\n]+including,[\s\n]+but[\s\n]+not[\s\n]+limited[\s\n]+to,[\s\n]+penetration[\s\n]+testing,[\s\n]+COMSEC[\s\n]+monitoring,[\s\n]+network[\s\n]+operations[\s\n]+and[\s\n]+defense,[\s\n]+personnel[\s\n]+misconduct[\s\n]+\(PM\),[\s\n]+law[\s\n]+enforcement[\s\n]+\(LE\),[\s\n]+and[\s\n]+counterintelligence[\s\n]+\(CI\)[\s\n]+investigations\.(?:[\n]+|(?:\\n)+)\-At[\s\n]+any[\s\n]+time,[\s\n]+the[\s\n]+USG[\s\n]+may[\s\n]+inspect[\s\n]+and[\s\n]+seize[\s\n]+data[\s\n]+stored[\s\n]+on[\s\n]+this[\s\n]+IS\.(?:[\n]+|(?:\\n)+)\-Communications[\s\n]+using,[\s\n]+or[\s\n]+data[\s\n]+stored[\s\n]+on,[\s\n]+this[\s\n]+IS[\s\n]+are[\s\n]+not[\s\n]+private,[\s\n]+are[\s\n]+subject[\s\n]+to[\s\n]+routine[\s\n]+monitoring,[\s\n]+interception,[\s\n]+and[\s\n]+search,[\s\n]+and[\s\n]+may[\s\n]+be[\s\n]+disclosed[\s\n]+or[\s\n]+used[\s\n]+for[\s\n]+any[\s\n]+USG\-authorized[\s\n]+purpose\.(?:[\n]+|(?:\\n)+)\-This[\s\n]+IS[\s\n]+includes[\s\n]+security[\s\n]+measures[\s\n]+\(e\.g\.,[\s\n]+authentication[\s\n]+and[\s\n]+access[\s\n]+controls\)[\s\n]+to[\s\n]+protect[\s\n]+USG[\s\n]+interests\-\-not[\s\n]+for[\s\n]+your[\s\n]+personal[\s\n]+benefit[\s\n]+or[\s\n]+privacy\.(?:[\n]+|(?:\\n)+)\-Notwithstanding[\s\n]+the[\s\n]+above,[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+does[\s\n]+not[\s\n]+constitute[\s\n]+consent[\s\n]+to[\s\n]+PM,[\s\n]+LE[\s\n]+or[\s\n]+CI[\s\n]+investigative[\s\n]+searching[\s\n]+or[\s\n]+monitoring[\s\n]+of[\s\n]+the[\s\n]+content[\s\n]+of[\s\n]+privileged[\s\n]+communications,[\s\n]+or[\s\n]+work[\s\n]+product,[\s\n]+related[\s\n]+to[\s\n]+personal[\s\n]+representation[\s\n]+or[\s\n]+services[\s\n]+by[\s\n]+attorneys,[\s\n]+psychotherapists,[\s\n]+or[\s\n]+clergy,[\s\n]+and[\s\n]+their[\s\n]+assistants\.[\s\n]+Such[\s\n]+communications[\s\n]+and[\s\n]+work[\s\n]+product[\s\n]+are[\s\n]+private[\s\n]+and[\s\n]+confidential\.[\s\n]+See[\s\n]+User[\s\n]+Agreement[\s\n]+for[\s\n]+details\.|I've[\s\n]+read[\s\n]+\&[\s\n]+consent[\s\n]+to[\s\n]+terms[\s\n]+in[\s\n]+IS[\s\n]+user[\s\n]+agreem't\.)$'

    # 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\|distro.d' | cut -d":" -f1)
    DCONFFILE="/etc/dconf/db/distro.d/00-security-settings"
    DBDIR="/etc/dconf/db/distro.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\|distro.d' | grep ":" | cut -d":" -f1)
    LOCKSFOLDER="/etc/dconf/db/distro.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/distro.d/
    then
        echo "/org/gnome/login-screen/banner-message-text" >> "/etc/dconf/db/distro.d/locks/00-security-settings-lock"
    fi
    dconf update

    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:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
    - name: XCCDF Value login_banner_text # promote to variable
      set_fact:
        login_banner_text: !!str ^(You[\s\n]+are[\s\n]+accessing[\s\n]+a[\s\n]+U\.S\.[\s\n]+Government[\s\n]+\(USG\)[\s\n]+Information[\s\n]+System[\s\n]+\(IS\)[\s\n]+that[\s\n]+is[\s\n]+provided[\s\n]+for[\s\n]+USG\-authorized[\s\n]+use[\s\n]+only\.[\s\n]+By[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+\(which[\s\n]+includes[\s\n]+any[\s\n]+device[\s\n]+attached[\s\n]+to[\s\n]+this[\s\n]+IS\),[\s\n]+you[\s\n]+consent[\s\n]+to[\s\n]+the[\s\n]+following[\s\n]+conditions\:(?:[\n]+|(?:\\n)+)\-The[\s\n]+USG[\s\n]+routinely[\s\n]+intercepts[\s\n]+and[\s\n]+monitors[\s\n]+communications[\s\n]+on[\s\n]+this[\s\n]+IS[\s\n]+for[\s\n]+purposes[\s\n]+including,[\s\n]+but[\s\n]+not[\s\n]+limited[\s\n]+to,[\s\n]+penetration[\s\n]+testing,[\s\n]+COMSEC[\s\n]+monitoring,[\s\n]+network[\s\n]+operations[\s\n]+and[\s\n]+defense,[\s\n]+personnel[\s\n]+misconduct[\s\n]+\(PM\),[\s\n]+law[\s\n]+enforcement[\s\n]+\(LE\),[\s\n]+and[\s\n]+counterintelligence[\s\n]+\(CI\)[\s\n]+investigations\.(?:[\n]+|(?:\\n)+)\-At[\s\n]+any[\s\n]+time,[\s\n]+the[\s\n]+USG[\s\n]+may[\s\n]+inspect[\s\n]+and[\s\n]+seize[\s\n]+data[\s\n]+stored[\s\n]+on[\s\n]+this[\s\n]+IS\.(?:[\n]+|(?:\\n)+)\-Communications[\s\n]+using,[\s\n]+or[\s\n]+data[\s\n]+stored[\s\n]+on,[\s\n]+this[\s\n]+IS[\s\n]+are[\s\n]+not[\s\n]+private,[\s\n]+are[\s\n]+subject[\s\n]+to[\s\n]+routine[\s\n]+monitoring,[\s\n]+interception,[\s\n]+and[\s\n]+search,[\s\n]+and[\s\n]+may[\s\n]+be[\s\n]+disclosed[\s\n]+or[\s\n]+used[\s\n]+for[\s\n]+any[\s\n]+USG\-authorized[\s\n]+purpose\.(?:[\n]+|(?:\\n)+)\-This[\s\n]+IS[\s\n]+includes[\s\n]+security[\s\n]+measures[\s\n]+\(e\.g\.,[\s\n]+authentication[\s\n]+and[\s\n]+access[\s\n]+controls\)[\s\n]+to[\s\n]+protect[\s\n]+USG[\s\n]+interests\-\-not[\s\n]+for[\s\n]+your[\s\n]+personal[\s\n]+benefit[\s\n]+or[\s\n]+privacy\.(?:[\n]+|(?:\\n)+)\-Notwithstanding[\s\n]+the[\s\n]+above,[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+does[\s\n]+not[\s\n]+constitute[\s\n]+consent[\s\n]+to[\s\n]+PM,[\s\n]+LE[\s\n]+or[\s\n]+CI[\s\n]+investigative[\s\n]+searching[\s\n]+or[\s\n]+monitoring[\s\n]+of[\s\n]+the[\s\n]+content[\s\n]+of[\s\n]+privileged[\s\n]+communications,[\s\n]+or[\s\n]+work[\s\n]+product,[\s\n]+related[\s\n]+to[\s\n]+personal[\s\n]+representation[\s\n]+or[\s\n]+services[\s\n]+by[\s\n]+attorneys,[\s\n]+psychotherapists,[\s\n]+or[\s\n]+clergy,[\s\n]+and[\s\n]+their[\s\n]+assistants\.[\s\n]+Such[\s\n]+communications[\s\n]+and[\s\n]+work[\s\n]+product[\s\n]+are[\s\n]+private[\s\n]+and[\s\n]+confidential\.[\s\n]+See[\s\n]+User[\s\n]+Agreement[\s\n]+for[\s\n]+details\.|I've[\s\n]+read[\s\n]+\&[\s\n]+consent[\s\n]+to[\s\n]+terms[\s\n]+in[\s\n]+IS[\s\n]+user[\s\n]+agreem't\.)$
      tags:
        - always

    - name: Set the GNOME3 Login Warning Banner Text
      ansible.builtin.file:
        path: /etc/dconf/db/{{ item }}
        owner: root
        group: root
        mode: 493
        state: directory
      with_items:
      - distro.d
      - distro.d/locks
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Set the GNOME3 Login Warning Banner Text
      ansible.builtin.file:
        path: /etc/dconf/db/distro.d/{{ item }}
        owner: root
        group: root
        mode: 420
        state: touch
      with_items:
      - 00-security-settings
      - locks/00-security-settings-lock
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Set the GNOME3 Login Warning Banner Text
      community.general.ini_file:
        dest: /etc/dconf/db/distro.d/00-security-settings
        section: org/gnome/login-screen
        option: banner-message-text
        value: '''{{ login_banner_text | regex_replace("^\^(.*)\$$", "\1") | regex_replace("^\((.*\.)\|.*\)$",
          "\1") | regex_replace("\[\\s\\n\]\+"," ") | regex_replace("\(\?:\[\\n\]\+\|\(\?:\\\\n\)\+\)",
          "(n)*") | regex_replace("\\", "") | regex_replace("\(n\)\*", "\\n") }}'''
        create: true
        no_extra_spaces: true
      register: result_ini
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Prevent user modification of the GNOME3 Login Warning Banner Text
      ansible.builtin.lineinfile:
        path: /etc/dconf/db/distro.d/locks/00-security-settings-lock
        regexp: ^/org/gnome/login-screen/banner-message-text$
        line: /org/gnome/login-screen/banner-message-text
        create: true
        state: present
      register: result_lineinfile
      when: '"gdm" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

    - name: Dconf Update
      ansible.builtin.command: dconf update
      when:
      - '"gdm" in ansible_facts.packages'
      - result_ini is changed or result_lineinfile is changed
      tags:
      - DISA-STIG-RHEL-09-171011
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - dconf_gnome_login_banner_text
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

#### Rule Modify the System Login Banner [ref]

To configure the system login banner edit `/etc/issue`. Replace the default text with a message compliant with the local site policy or a legal disclaimer. The DoD required text is either:
`You are accessing a U.S. Government (USG) Information System (IS) that is provided for USG-authorized use only. By using this IS (which includes any device attached to this IS), you consent to the following conditions:
-The USG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations.
-At any time, the USG may inspect and seize data stored on this IS.
-Communications using, or data stored on, this IS are not private, are subject to routine monitoring, interception, and search, and may be disclosed or used for any USG-authorized purpose.
-This IS includes security measures (e.g., authentication and access controls) to protect USG interests -- not for your personal benefit or privacy.
-Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching or monitoring of the content of privileged communications, or work product, related to personal representation or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work product are private and confidential. See User Agreement for details.`
OR:
`I've read & consent to terms in IS user agreem't.`

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.
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_banner_etc_issue

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
stigref | SV-257779r958390_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    login_banner_text='^(You[\s\n]+are[\s\n]+accessing[\s\n]+a[\s\n]+U\.S\.[\s\n]+Government[\s\n]+\(USG\)[\s\n]+Information[\s\n]+System[\s\n]+\(IS\)[\s\n]+that[\s\n]+is[\s\n]+provided[\s\n]+for[\s\n]+USG\-authorized[\s\n]+use[\s\n]+only\.[\s\n]+By[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+\(which[\s\n]+includes[\s\n]+any[\s\n]+device[\s\n]+attached[\s\n]+to[\s\n]+this[\s\n]+IS\),[\s\n]+you[\s\n]+consent[\s\n]+to[\s\n]+the[\s\n]+following[\s\n]+conditions\:(?:[\n]+|(?:\\n)+)\-The[\s\n]+USG[\s\n]+routinely[\s\n]+intercepts[\s\n]+and[\s\n]+monitors[\s\n]+communications[\s\n]+on[\s\n]+this[\s\n]+IS[\s\n]+for[\s\n]+purposes[\s\n]+including,[\s\n]+but[\s\n]+not[\s\n]+limited[\s\n]+to,[\s\n]+penetration[\s\n]+testing,[\s\n]+COMSEC[\s\n]+monitoring,[\s\n]+network[\s\n]+operations[\s\n]+and[\s\n]+defense,[\s\n]+personnel[\s\n]+misconduct[\s\n]+\(PM\),[\s\n]+law[\s\n]+enforcement[\s\n]+\(LE\),[\s\n]+and[\s\n]+counterintelligence[\s\n]+\(CI\)[\s\n]+investigations\.(?:[\n]+|(?:\\n)+)\-At[\s\n]+any[\s\n]+time,[\s\n]+the[\s\n]+USG[\s\n]+may[\s\n]+inspect[\s\n]+and[\s\n]+seize[\s\n]+data[\s\n]+stored[\s\n]+on[\s\n]+this[\s\n]+IS\.(?:[\n]+|(?:\\n)+)\-Communications[\s\n]+using,[\s\n]+or[\s\n]+data[\s\n]+stored[\s\n]+on,[\s\n]+this[\s\n]+IS[\s\n]+are[\s\n]+not[\s\n]+private,[\s\n]+are[\s\n]+subject[\s\n]+to[\s\n]+routine[\s\n]+monitoring,[\s\n]+interception,[\s\n]+and[\s\n]+search,[\s\n]+and[\s\n]+may[\s\n]+be[\s\n]+disclosed[\s\n]+or[\s\n]+used[\s\n]+for[\s\n]+any[\s\n]+USG\-authorized[\s\n]+purpose\.(?:[\n]+|(?:\\n)+)\-This[\s\n]+IS[\s\n]+includes[\s\n]+security[\s\n]+measures[\s\n]+\(e\.g\.,[\s\n]+authentication[\s\n]+and[\s\n]+access[\s\n]+controls\)[\s\n]+to[\s\n]+protect[\s\n]+USG[\s\n]+interests\-\-not[\s\n]+for[\s\n]+your[\s\n]+personal[\s\n]+benefit[\s\n]+or[\s\n]+privacy\.(?:[\n]+|(?:\\n)+)\-Notwithstanding[\s\n]+the[\s\n]+above,[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+does[\s\n]+not[\s\n]+constitute[\s\n]+consent[\s\n]+to[\s\n]+PM,[\s\n]+LE[\s\n]+or[\s\n]+CI[\s\n]+investigative[\s\n]+searching[\s\n]+or[\s\n]+monitoring[\s\n]+of[\s\n]+the[\s\n]+content[\s\n]+of[\s\n]+privileged[\s\n]+communications,[\s\n]+or[\s\n]+work[\s\n]+product,[\s\n]+related[\s\n]+to[\s\n]+personal[\s\n]+representation[\s\n]+or[\s\n]+services[\s\n]+by[\s\n]+attorneys,[\s\n]+psychotherapists,[\s\n]+or[\s\n]+clergy,[\s\n]+and[\s\n]+their[\s\n]+assistants\.[\s\n]+Such[\s\n]+communications[\s\n]+and[\s\n]+work[\s\n]+product[\s\n]+are[\s\n]+private[\s\n]+and[\s\n]+confidential\.[\s\n]+See[\s\n]+User[\s\n]+Agreement[\s\n]+for[\s\n]+details\.|I've[\s\n]+read[\s\n]+\&[\s\n]+consent[\s\n]+to[\s\n]+terms[\s\n]+in[\s\n]+IS[\s\n]+user[\s\n]+agreem't\.)$'

    # 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 newlines. (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')
    formatted=$(echo "$login_banner_text" | fold -sw 80)
    cat <<EOF >/etc/issue
    $formatted
    EOF

    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:
      - DISA-STIG-RHEL-09-211020
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - banner_etc_issue
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy
    - name: XCCDF Value login_banner_text # promote to variable
      set_fact:
        login_banner_text: !!str ^(You[\s\n]+are[\s\n]+accessing[\s\n]+a[\s\n]+U\.S\.[\s\n]+Government[\s\n]+\(USG\)[\s\n]+Information[\s\n]+System[\s\n]+\(IS\)[\s\n]+that[\s\n]+is[\s\n]+provided[\s\n]+for[\s\n]+USG\-authorized[\s\n]+use[\s\n]+only\.[\s\n]+By[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+\(which[\s\n]+includes[\s\n]+any[\s\n]+device[\s\n]+attached[\s\n]+to[\s\n]+this[\s\n]+IS\),[\s\n]+you[\s\n]+consent[\s\n]+to[\s\n]+the[\s\n]+following[\s\n]+conditions\:(?:[\n]+|(?:\\n)+)\-The[\s\n]+USG[\s\n]+routinely[\s\n]+intercepts[\s\n]+and[\s\n]+monitors[\s\n]+communications[\s\n]+on[\s\n]+this[\s\n]+IS[\s\n]+for[\s\n]+purposes[\s\n]+including,[\s\n]+but[\s\n]+not[\s\n]+limited[\s\n]+to,[\s\n]+penetration[\s\n]+testing,[\s\n]+COMSEC[\s\n]+monitoring,[\s\n]+network[\s\n]+operations[\s\n]+and[\s\n]+defense,[\s\n]+personnel[\s\n]+misconduct[\s\n]+\(PM\),[\s\n]+law[\s\n]+enforcement[\s\n]+\(LE\),[\s\n]+and[\s\n]+counterintelligence[\s\n]+\(CI\)[\s\n]+investigations\.(?:[\n]+|(?:\\n)+)\-At[\s\n]+any[\s\n]+time,[\s\n]+the[\s\n]+USG[\s\n]+may[\s\n]+inspect[\s\n]+and[\s\n]+seize[\s\n]+data[\s\n]+stored[\s\n]+on[\s\n]+this[\s\n]+IS\.(?:[\n]+|(?:\\n)+)\-Communications[\s\n]+using,[\s\n]+or[\s\n]+data[\s\n]+stored[\s\n]+on,[\s\n]+this[\s\n]+IS[\s\n]+are[\s\n]+not[\s\n]+private,[\s\n]+are[\s\n]+subject[\s\n]+to[\s\n]+routine[\s\n]+monitoring,[\s\n]+interception,[\s\n]+and[\s\n]+search,[\s\n]+and[\s\n]+may[\s\n]+be[\s\n]+disclosed[\s\n]+or[\s\n]+used[\s\n]+for[\s\n]+any[\s\n]+USG\-authorized[\s\n]+purpose\.(?:[\n]+|(?:\\n)+)\-This[\s\n]+IS[\s\n]+includes[\s\n]+security[\s\n]+measures[\s\n]+\(e\.g\.,[\s\n]+authentication[\s\n]+and[\s\n]+access[\s\n]+controls\)[\s\n]+to[\s\n]+protect[\s\n]+USG[\s\n]+interests\-\-not[\s\n]+for[\s\n]+your[\s\n]+personal[\s\n]+benefit[\s\n]+or[\s\n]+privacy\.(?:[\n]+|(?:\\n)+)\-Notwithstanding[\s\n]+the[\s\n]+above,[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+does[\s\n]+not[\s\n]+constitute[\s\n]+consent[\s\n]+to[\s\n]+PM,[\s\n]+LE[\s\n]+or[\s\n]+CI[\s\n]+investigative[\s\n]+searching[\s\n]+or[\s\n]+monitoring[\s\n]+of[\s\n]+the[\s\n]+content[\s\n]+of[\s\n]+privileged[\s\n]+communications,[\s\n]+or[\s\n]+work[\s\n]+product,[\s\n]+related[\s\n]+to[\s\n]+personal[\s\n]+representation[\s\n]+or[\s\n]+services[\s\n]+by[\s\n]+attorneys,[\s\n]+psychotherapists,[\s\n]+or[\s\n]+clergy,[\s\n]+and[\s\n]+their[\s\n]+assistants\.[\s\n]+Such[\s\n]+communications[\s\n]+and[\s\n]+work[\s\n]+product[\s\n]+are[\s\n]+private[\s\n]+and[\s\n]+confidential\.[\s\n]+See[\s\n]+User[\s\n]+Agreement[\s\n]+for[\s\n]+details\.|I've[\s\n]+read[\s\n]+\&[\s\n]+consent[\s\n]+to[\s\n]+terms[\s\n]+in[\s\n]+IS[\s\n]+user[\s\n]+agreem't\.)$
      tags:
        - always

    - name: Modify the System Login Banner - Ensure Correct Banner
      ansible.builtin.copy:
        dest: /etc/issue
        content: '{{ login_banner_text | regex_replace("^\^(.*)\$$", "\1") | regex_replace("^\((.*\.)\|.*\)$",
          "\1") | regex_replace("\[\\s\\n\]\+"," ") | regex_replace("\(\?:\[\\n\]\+\|\(\?:\\\\n\)\+\)",
          "\n") | regex_replace("\\", "") | wordwrap() }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-211020
      - NIST-800-171-3.1.9
      - NIST-800-53-AC-8(a)
      - NIST-800-53-AC-8(c)
      - banner_etc_issue
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - unknown_strategy

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    metadata:
      labels:
        machineconfiguration.openshift.io/role: master
        machineconfiguration.openshift.io/role: worker
      name: 75-banner-etc-issue
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,You%20are%20accessing%20a%20U.S.%20Government%20%28USG%29%20Information%20System%20%28IS%29%20that%20is%20%0Aprovided%20for%20USG-authorized%20use%20only.%20By%20using%20this%20IS%20%28which%20includes%20any%20%0Adevice%20attached%20to%20this%20IS%29%2C%20you%20consent%20to%20the%20following%20conditions%3A%0A%0A-The%20USG%20routinely%20intercepts%20and%20monitors%20communications%20on%20this%20IS%20for%20%0Apurposes%20including%2C%20but%20not%20limited%20to%2C%20penetration%20testing%2C%20COMSEC%20monitoring%2C%20%0Anetwork%20operations%20and%20defense%2C%20personnel%20misconduct%20%28PM%29%2C%20law%20enforcement%20%0A%28LE%29%2C%20and%20counterintelligence%20%28CI%29%20investigations.%0A%0A-At%20any%20time%2C%20the%20USG%20may%20inspect%20and%20seize%20data%20stored%20on%20this%20IS.%0A%0A-Communications%20using%2C%20or%20data%20stored%20on%2C%20this%20IS%20are%20not%20private%2C%20are%20subject%20%0Ato%20routine%20monitoring%2C%20interception%2C%20and%20search%2C%20and%20may%20be%20disclosed%20or%20used%20%0Afor%20any%20USG-authorized%20purpose.%0A%0A-This%20IS%20includes%20security%20measures%20%28e.g.%2C%20authentication%20and%20access%20controls%29%20%0Ato%20protect%20USG%20interests--not%20for%20your%20personal%20benefit%20or%20privacy.%0A%0A-Notwithstanding%20the%20above%2C%20using%20this%20IS%20does%20not%20constitute%20consent%20to%20PM%2C%20LE%20%0Aor%20CI%20investigative%20searching%20or%20monitoring%20of%20the%20content%20of%20privileged%20%0Acommunications%2C%20or%20work%20product%2C%20related%20to%20personal%20representation%20or%20services%20%0Aby%20attorneys%2C%20psychotherapists%2C%20or%20clergy%2C%20and%20their%20assistants.%20Such%20%0Acommunications%20and%20work%20product%20are%20private%20and%20confidential.%20See%20User%20%0AAgreement%20for%20details.
            mode: 0644
            path: /etc/issue.d/legal-notice
            overwrite: true

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 Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth File. [ref]

The pam_faillock.so module must be loaded in preauth in /etc/pam.d/password-auth.
Rationale: | If the pam_faillock.so module is not loaded the system will not correctly lockout accounts to prevent password guessing attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_password_pam_faillock_password_auth

References:

nist | AC-7 (a)
os-srg | SRG-OS-000021-GPOS-00005
cis | 5.3.2.2
stigref | SV-258096r1045191_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611035
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_password_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
        File. - Check if system relies on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611035
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_password_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
        File. - Remediation where authselect tool is present
      block:

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - 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: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - 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: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Get authselect current features
        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_check_cmd is success

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Ensure "with-faillock" feature is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611035
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_password_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
        File. - Remediation where authselect tool is not present
      block:

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Check if pam_faillock.so is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Enable pam_faillock.so preauth editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Enable pam_faillock.so authfail editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/password-auth
          File. - Enable pam_faillock.so account section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611035
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_password_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth File. [ref]

The pam_faillock.so module must be loaded in preauth in /etc/pam.d/system-auth.
Rationale: | If the pam_faillock.so module is not loaded the system will not correctly lockout accounts to prevent password guessing attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_password_pam_faillock_system_auth

References:

nist | AC-7 (a)
os-srg | SRG-OS-000021-GPOS-00005
cis | 5.3.2.2
stigref | SV-258095r1045189_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611030
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_system_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
        File. - Check if system relies on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611030
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_system_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
        File. - Remediation where authselect tool is present
      block:

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - 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: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - 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: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Get authselect current features
        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_check_cmd is success

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Ensure "with-faillock" feature is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611030
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_system_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
        File. - Remediation where authselect tool is not present
      block:

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Check if pam_faillock.so is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Enable pam_faillock.so preauth editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Enable pam_faillock.so authfail editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the Use of the pam_faillock.so Module in the /etc/pam.d/system-auth
          File. - Enable pam_faillock.so account section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611030
      - NIST-800-53-AC-7 (a)
      - account_password_pam_faillock_system_auth
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule An SELinux Context must be configured for the pam_faillock.so records directory [ref]

The `dir` configuration option in PAM pam_faillock.so module defines where the lockout records is stored. The configured directory must have the correct SELinux context.
Rationale: | Not having the correct SELinux context on the pam_faillock.so records directory may lead to unauthorized access to the directory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_password_selinux_faillock_dir

References:

nist | AC-7 (a)
os-srg | SRG-OS-000021-GPOS-00005
stigref | SV-258080r1045162_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    FAILLOCK_CONF_FILES="/etc/security/faillock.conf /etc/pam.d/system-auth /etc/pam.d/password-auth"

    faillock_dirs=$(grep -oP "^\s*(?:auth.*pam_faillock.so.*)?dir\s*=\s*(\S+)" $FAILLOCK_CONF_FILES \
                   | sed -r 's/.*=\s*(\S+)/\1/')

    # Workaround for https://github.com/OpenSCAP/openscap/issues/2242: Use full
    # path to semanage and restorecon commands to avoid the issue with the command
    # not being found.
    if [ -n "$faillock_dirs" ]; then
        for dir in $faillock_dirs; do
            if ! /usr/sbin/semanage fcontext -a -t faillog_t "$dir(/.*)?"; then
                /usr/sbin/semanage fcontext -m -t faillog_t "$dir(/.*)?"
            fi
            if [ ! -e $dir ]; then
                mkdir -p $dir
            fi
            /usr/sbin/restorecon -R -v $dir
        done
    else
    echo "
    The pam_faillock.so dir option is not set in the system.
    If this is not expected, make sure pam_faillock.so is properly configured."
    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:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Get directories from faillock
      ansible.builtin.shell: grep -oP '^\s*(?:auth.*pam_faillock.so.*)?dir\s*=\s*(\S+)'
        "{{ item }}" | sed -r 's/.*=\s*(\S+)/\1/'
      register: faillock_output
      changed_when: false
      check_mode: false
      with_items:
      - /etc/security/faillock.conf
      - /etc/pam.d/system-auth
      - /etc/pam.d/password-auth
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Create a list directories from faillock
      ansible.builtin.set_fact:
        list_faillock_dir: '{{ faillock_output.results | map(attribute=''stdout_lines'')
          | flatten }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Create directories for faillock
      ansible.builtin.file:
        path: '{{ item }}'
        state: directory
      with_items: '{{ list_faillock_dir }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item != ""
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Get SELinux context for faillock directories
      ansible.builtin.command: ls -dZ "{{ item }}"
      register: faillock_selinux_context
      changed_when: false
      check_mode: false
      with_items: '{{ list_faillock_dir }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item != ""
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Set up SELinux context for faillock
      ansible.builtin.shell: |-
        if ! semanage fcontext -a -t faillog_t "{{ item.item }}(/.*)?"; then
          semanage fcontext -m -t faillog_t "{{ item.item }}(/.*)?"
        fi
      with_items: '{{ faillock_selinux_context.results }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.item != ""
      - item.stdout is defined
      - '"faillog_t" not in item.stdout'
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Restore SELinux context
      ansible.builtin.command: restorecon -R -v "{{ item.item }}"
      with_items: '{{ faillock_selinux_context.results }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.item != ""
      - item.stdout is defined
      - '"faillog_t" not in item.stdout'
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: An SELinux Context must be configured for the pam_faillock.so records directory
        - Verify pam_faillock.so configuration
      ansible.builtin.debug:
        msg: |-
          "The pam_faillock.so dir option is not set in the system.
          If this is not expected, make sure pam_faillock.so is properly configured."
      when:
      - '"kernel-core" in ansible_facts.packages'
      - list_faillock_dir | length == 0
      tags:
      - DISA-STIG-RHEL-09-431020
      - NIST-800-53-AC-7 (a)
      - account_password_selinux_faillock_dir
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Account Lockouts Must Be Logged [ref]

PAM faillock locks an account due to excessive password failures, this event must be logged.
Rationale: | Without auditing of these events it may be harder or impossible to identify what an attacker did after an attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_audit

References:

nist | AC-7 (a)
os-srg | SRG-OS-000021-GPOS-00005
stigref | SV-258070r1045153_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

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

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

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

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

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

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

                    authselect apply-changes -b
                fi

            if grep -qP "^\s*auth\s.*\bpam_faillock.so\s.*\baudit\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\baudit\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).*audit' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ audit/' "$pam_file"
            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:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Check if system relies on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Remediation where authselect tool is present
      block:

      - name: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - Get authselect current features
        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_check_cmd is success

      - name: Account Lockouts Must Be Logged - Ensure "with-faillock" feature is enabled
          using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Account Lockouts Must Be Logged - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Remediation where authselect tool is not
        present
      block:

      - name: Account Lockouts Must Be Logged - Check if pam_faillock.so is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Account Lockouts Must Be Logged - Enable pam_faillock.so preauth editing
          PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Account Lockouts Must Be Logged - Enable pam_faillock.so authfail editing
          PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Account Lockouts Must Be Logged - Enable pam_faillock.so account section
          editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Check the presence of /etc/security/faillock.conf
        file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Ensure the pam_faillock.so audit parameter
        in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*audit
        line: audit
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Ensure the pam_faillock.so audit parameter
        not in PAM files
      block:

      - name: Account Lockouts Must Be Logged - Check if /etc/pam.d/system-auth file is
          present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Account Lockouts Must Be Logged - Check the proper remediation for the system
        block:

        - name: Account Lockouts Must Be Logged - Define the PAM file to be edited as
            a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/system-auth

        - name: Account Lockouts Must Be Logged - Check if system relies on authselect
            tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Account Lockouts Must Be Logged - Ensure authselect custom profile is
            used if authselect is present
          block:

          - name: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - Define a fact for control already filtered
            in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Account Lockouts Must Be Logged - Check if {{ pam_file_path }} file is
            present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Account Lockouts Must Be Logged - Ensure the "audit" option from "pam_faillock.so"
            is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\baudit\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Account Lockouts Must Be Logged - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Account Lockouts Must Be Logged - Check if /etc/pam.d/password-auth file
          is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Account Lockouts Must Be Logged - Check the proper remediation for the system
        block:

        - name: Account Lockouts Must Be Logged - Define the PAM file to be edited as
            a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Account Lockouts Must Be Logged - Check if system relies on authselect
            tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Account Lockouts Must Be Logged - Ensure authselect custom profile is
            used if authselect is present
          block:

          - name: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - 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: Account Lockouts Must Be Logged - Define a fact for control already filtered
            in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Account Lockouts Must Be Logged - Check if {{ pam_file_path }} file is
            present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Account Lockouts Must Be Logged - Ensure the "audit" option from "pam_faillock.so"
            is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\baudit\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Account Lockouts Must Be Logged - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Account Lockouts Must Be Logged - Ensure the pam_faillock.so audit parameter
        in PAM files
      block:

      - name: Account Lockouts Must Be Logged - Check if pam_faillock.so audit parameter
          is already enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*audit
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_audit_parameter_is_present

      - name: Account Lockouts Must Be Logged - Ensure the inclusion of pam_faillock.so
          preauth audit parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 audit
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_audit_parameter_is_present.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-412045
      - NIST-800-53-AC-7 (a)
      - accounts_passwords_pam_faillock_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    var_accounts_passwords_pam_faillock_deny='3'

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

    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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Check if system relies on authselect
        tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Remediation where authselect
        tool is present
      block:

      - name: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - Get authselect current features
        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_check_cmd is success

      - name: Lock Accounts After Failed Password Attempts - Ensure "with-faillock" feature
          is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Lock Accounts After Failed Password Attempts - Ensure authselect changes
          are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Remediation where authselect
        tool is not present
      block:

      - name: Lock Accounts After Failed Password Attempts - Check if pam_faillock.so
          is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Lock Accounts After Failed Password Attempts - Enable pam_faillock.so preauth
          editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Lock Accounts After Failed Password Attempts - Enable pam_faillock.so authfail
          editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Lock Accounts After Failed Password Attempts - Enable pam_faillock.so account
          section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_passwords_pam_faillock_deny # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_deny: !!str 3
      tags:
        - always

    - name: Lock Accounts After Failed Password Attempts - Check the presence of /etc/security/faillock.conf
        file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Ensure the pam_faillock.so
        deny parameter in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*deny\s*=
        line: deny = {{ var_accounts_passwords_pam_faillock_deny }}
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Ensure the pam_faillock.so
        deny parameter not in PAM files
      block:

      - name: Lock Accounts After Failed Password Attempts - Check if /etc/pam.d/system-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Lock Accounts After Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Lock Accounts After Failed Password Attempts - Define the PAM file to
            be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/system-auth

        - name: Lock Accounts After Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Lock Accounts After Failed Password Attempts - Ensure authselect custom
            profile is used if authselect is present
          block:

          - name: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - Define a fact for control
            already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Lock Accounts After Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Lock Accounts After Failed Password Attempts - Ensure the "deny" option
            from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bdeny\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Lock Accounts After Failed Password Attempts - Ensure authselect changes
            are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Lock Accounts After Failed Password Attempts - Check if /etc/pam.d/password-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Lock Accounts After Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Lock Accounts After Failed Password Attempts - Define the PAM file to
            be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Lock Accounts After Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Lock Accounts After Failed Password Attempts - Ensure authselect custom
            profile is used if authselect is present
          block:

          - name: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - 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: Lock Accounts After Failed Password Attempts - Define a fact for control
            already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Lock Accounts After Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Lock Accounts After Failed Password Attempts - Ensure the "deny" option
            from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bdeny\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Lock Accounts After Failed Password Attempts - Ensure authselect changes
            are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Lock Accounts After Failed Password Attempts - Ensure the pam_faillock.so
        deny parameter in PAM files
      block:

      - name: Lock Accounts After Failed Password Attempts - Check if pam_faillock.so
          deny parameter is already enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*deny
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_deny_parameter_is_present

      - name: Lock Accounts After Failed Password Attempts - Ensure the inclusion of pam_faillock.so
          preauth deny parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 deny={{ var_accounts_passwords_pam_faillock_deny }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_deny_parameter_is_present.found == 0

      - name: Lock Accounts After Failed Password Attempts - Ensure the inclusion of pam_faillock.so
          authfail deny parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
          line: \1required\3 deny={{ var_accounts_passwords_pam_faillock_deny }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_deny_parameter_is_present.found == 0

      - name: Lock Accounts After Failed Password Attempts - Ensure the desired value
          for pam_faillock.so preauth deny parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)(deny)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_deny }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_deny_parameter_is_present.found > 0

      - name: Lock Accounts After Failed Password Attempts - Ensure the desired value
          for pam_faillock.so authfail deny parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)(deny)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_deny }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_deny_parameter_is_present.found > 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411075
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.6
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

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

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

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

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

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

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

                    authselect apply-changes -b
                fi

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

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Check if system
        relies on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Remediation where
        authselect tool is present
      block:

      - name: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - Get authselect
          current features
        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_check_cmd is success

      - name: Configure the root Account for Failed Password Attempts - Ensure "with-faillock"
          feature is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Configure the root Account for Failed Password Attempts - Ensure authselect
          changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Remediation where
        authselect tool is not present
      block:

      - name: Configure the root Account for Failed Password Attempts - Check if pam_faillock.so
          is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Configure the root Account for Failed Password Attempts - Enable pam_faillock.so
          preauth editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the root Account for Failed Password Attempts - Enable pam_faillock.so
          authfail editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Configure the root Account for Failed Password Attempts - Enable pam_faillock.so
          account section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Check the presence
        of /etc/security/faillock.conf file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Ensure the pam_faillock.so
        even_deny_root parameter in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*even_deny_root
        line: even_deny_root
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Ensure the pam_faillock.so
        even_deny_root parameter not in PAM files
      block:

      - name: Configure the root Account for Failed Password Attempts - Check if /etc/pam.d/system-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Configure the root Account for Failed Password Attempts - Check the proper
          remediation for the system
        block:

        - name: Configure the root Account for Failed Password Attempts - Define the PAM
            file to be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/system-auth

        - name: Configure the root Account for Failed Password Attempts - Check if system
            relies on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Configure the root Account for Failed Password Attempts - Ensure authselect
            custom profile is used if authselect is present
          block:

          - name: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - Define a fact
            for control already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Configure the root Account for Failed Password Attempts - Check if {{
            pam_file_path }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Configure the root Account for Failed Password Attempts - Ensure the "even_deny_root"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\beven_deny_root\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Configure the root Account for Failed Password Attempts - Ensure authselect
            changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Configure the root Account for Failed Password Attempts - Check if /etc/pam.d/password-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Configure the root Account for Failed Password Attempts - Check the proper
          remediation for the system
        block:

        - name: Configure the root Account for Failed Password Attempts - Define the PAM
            file to be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Configure the root Account for Failed Password Attempts - Check if system
            relies on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Configure the root Account for Failed Password Attempts - Ensure authselect
            custom profile is used if authselect is present
          block:

          - name: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - 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: Configure the root Account for Failed Password Attempts - Define a fact
            for control already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Configure the root Account for Failed Password Attempts - Check if {{
            pam_file_path }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Configure the root Account for Failed Password Attempts - Ensure the "even_deny_root"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\beven_deny_root\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Configure the root Account for Failed Password Attempts - Ensure authselect
            changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure the root Account for Failed Password Attempts - Ensure the pam_faillock.so
        even_deny_root parameter in PAM files
      block:

      - name: Configure the root Account for Failed Password Attempts - Check if pam_faillock.so
          even_deny_root parameter is already enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*even_deny_root
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_even_deny_root_parameter_is_present

      - name: Configure the root Account for Failed Password Attempts - Ensure the inclusion
          of pam_faillock.so preauth even_deny_root parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 even_deny_root
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_even_deny_root_parameter_is_present.found == 0

      - name: Configure the root Account for Failed Password Attempts - Ensure the inclusion
          of pam_faillock.so authfail even_deny_root parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
          line: \1required\3 even_deny_root
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_even_deny_root_parameter_is_present.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411080
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(c)
      - accounts_passwords_pam_faillock_deny_root
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Lock Accounts Must Persist [ref]

This rule ensures that the system lock out accounts using `pam_faillock.so` persist after system reboot. From "pam_faillock" man pages:

    Note that the default directory that "pam_faillock" uses is usually cleared on system
    boot so the access will be re-enabled after system reboot. If that is undesirable, a different
    tally directory must be set with the "dir" option.

pam_faillock.so module requires multiple entries in pam files. These entries must be carefully defined to work as expected. In order to avoid errors when manually editing these files, it is recommended to use the appropriate tools, such as `authselect` or `authconfig`, depending on the OS version. The chosen profile expects the directory to be `/var/log/faillock`. To configure the tally directory, add the following line to `/etc/security/faillock.conf`:

    dir = /var/log/faillock

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: | Locking out user accounts after a number of incorrect attempts prevents direct password guessing attacks. In combination with the `silent` option, user enumeration attacks are also mitigated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_dir

References:

nist | AC-7(b), AC-7(a), AC-7.1(ii)
os-srg | SRG-OS-000021-GPOS-00005, SRG-OS-000329-GPOS-00128
stigref | SV-258060r1045150_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    var_accounts_passwords_pam_faillock_dir='/var/log/faillock'

    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

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

    FAILLOCK_CONF="/etc/security/faillock.conf"
    if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
        regex="^\s*dir\s*="
        line="dir = $var_accounts_passwords_pam_faillock_dir"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        else
            sed -i --follow-symlinks 's|^\s*\(dir\s*=\s*\)\(\S\+\)|\1'"$var_accounts_passwords_pam_faillock_dir"'|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.*\bdir\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\bdir\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).*dir' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ dir='"$var_accounts_passwords_pam_faillock_dir"'/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ dir='"$var_accounts_passwords_pam_faillock_dir"'/' "$pam_file"
            else
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"dir"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_dir"'\3/' "$pam_file"
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"dir"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_dir"'\3/' "$pam_file"
            fi
        done
    fi

    if ! rpm -q --quiet "python3-libselinux" ; then
        dnf install -y "python3-libselinux"
    fi
    if ! rpm -q --quiet "python3-policycoreutils" ; then
        dnf install -y "python3-policycoreutils"
    fi
    if ! rpm -q --quiet "policycoreutils-python-utils" ; then
        dnf install -y "policycoreutils-python-utils"
    fi

    mkdir -p "$var_accounts_passwords_pam_faillock_dir"
    # Workaround for https://github.com/OpenSCAP/openscap/issues/2242: Use full
    # path to semanage and restorecon commands to avoid the issue with the command
    # not being found.
    /usr/sbin/semanage fcontext -a -t faillog_t "$var_accounts_passwords_pam_faillock_dir(/.*)?"
    /usr/sbin/restorecon -R -v "$var_accounts_passwords_pam_faillock_dir"

    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:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Check if system relies on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Remediation where authselect tool is present
      block:

      - name: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - Get authselect current features
        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_check_cmd is success

      - name: Lock Accounts Must Persist - Ensure "with-faillock" feature is enabled using
          authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Lock Accounts Must Persist - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Remediation where authselect tool is not present
      block:

      - name: Lock Accounts Must Persist - Check if pam_faillock.so is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Lock Accounts Must Persist - Enable pam_faillock.so preauth editing PAM
          files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Lock Accounts Must Persist - Enable pam_faillock.so authfail editing PAM
          files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Lock Accounts Must Persist - Enable pam_faillock.so account section editing
          PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_accounts_passwords_pam_faillock_dir # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_dir: !!str /var/log/faillock
      tags:
        - always

    - name: Lock Accounts Must Persist - Check the presence of /etc/security/faillock.conf
        file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure the pam_faillock.so dir parameter in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*dir\s*=
        line: dir = {{ var_accounts_passwords_pam_faillock_dir }}
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure the pam_faillock.so dir parameter not
        in PAM files
      block:

      - name: Lock Accounts Must Persist - Check if /etc/pam.d/system-auth file is present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Lock Accounts Must Persist - Check the proper remediation for the system
        block:

        - name: Lock Accounts Must Persist - Define the PAM file to be edited as a local
            fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/system-auth

        - name: Lock Accounts Must Persist - Check if system relies on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Lock Accounts Must Persist - Ensure authselect custom profile is used
            if authselect is present
          block:

          - name: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - Define a fact for control already filtered
            in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Lock Accounts Must Persist - Check if {{ pam_file_path }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Lock Accounts Must Persist - Ensure the "dir" option from "pam_faillock.so"
            is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bdir\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Lock Accounts Must Persist - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Lock Accounts Must Persist - Check if /etc/pam.d/password-auth file is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Lock Accounts Must Persist - Check the proper remediation for the system
        block:

        - name: Lock Accounts Must Persist - Define the PAM file to be edited as a local
            fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Lock Accounts Must Persist - Check if system relies on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Lock Accounts Must Persist - Ensure authselect custom profile is used
            if authselect is present
          block:

          - name: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - 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: Lock Accounts Must Persist - Define a fact for control already filtered
            in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Lock Accounts Must Persist - Check if {{ pam_file_path }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Lock Accounts Must Persist - Ensure the "dir" option from "pam_faillock.so"
            is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bdir\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Lock Accounts Must Persist - Ensure authselect changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure the pam_faillock.so dir parameter in PAM
        files
      block:

      - name: Lock Accounts Must Persist - Check if pam_faillock.so dir parameter is already
          enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*dir
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_dir_parameter_is_present

      - name: Lock Accounts Must Persist - Ensure the inclusion of pam_faillock.so preauth
          dir parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 dir={{ var_accounts_passwords_pam_faillock_dir }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_dir_parameter_is_present.found == 0

      - name: Lock Accounts Must Persist - Ensure the inclusion of pam_faillock.so authfail
          dir parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
          line: \1required\3 dir={{ var_accounts_passwords_pam_faillock_dir }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_dir_parameter_is_present.found == 0

      - name: Lock Accounts Must Persist - Ensure the desired value for pam_faillock.so
          preauth dir parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)(dir)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_dir }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_dir_parameter_is_present.found > 0

      - name: Lock Accounts Must Persist - Ensure the desired value for pam_faillock.so
          authfail dir parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)(dir)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_dir }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_dir_parameter_is_present.found > 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure necessary SELinux packages are installed
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      with_items:
      - python3-libselinux
      - python3-policycoreutils
      - policycoreutils-python-utils
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Create the faillock directory if it does not
        exist
      ansible.builtin.file:
        path: '{{ var_accounts_passwords_pam_faillock_dir }}'
        state: directory
        setype: faillog_t
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Get SELinux context for faillock directory
      ansible.builtin.command:
        cmd: ls -dZ {{ var_accounts_passwords_pam_faillock_dir }}
      register: faillock_selinux_context
      changed_when: false
      check_mode: false
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure SELinux file context is permanently set
      ansible.builtin.command:
        cmd: semanage fcontext -a -t faillog_t "{{ var_accounts_passwords_pam_faillock_dir
          }}(/.*)?"
      register: result_accounts_passwords_pam_faillock_dir_semanage
      failed_when: false
      changed_when:
      - result_accounts_passwords_pam_faillock_dir_semanage.rc == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - '"faillog_t" not in faillock_selinux_context.stdout'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Lock Accounts Must Persist - Ensure SELinux file context is applied
      ansible.builtin.command:
        cmd: restorecon -R "{{ var_accounts_passwords_pam_faillock_dir }}"
      register: result_accounts_passwords_pam_faillock_dir_restorecon
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - '"faillog_t" not in faillock_selinux_context.stdout'
      tags:
      - DISA-STIG-RHEL-09-411105
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AC-7(b)
      - NIST-800-53-AC-7.1(ii)
      - accounts_passwords_pam_faillock_dir
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

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

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    var_accounts_passwords_pam_faillock_fail_interval='900'

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

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

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

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

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

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

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

                    authselect apply-changes -b
                fi

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

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Check if system relies
        on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Remediation where authselect
        tool is present
      block:

      - name: Set Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - Get authselect current
          features
        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_check_cmd is success

      - name: Set Interval For Counting Failed Password Attempts - Ensure "with-faillock"
          feature is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Set Interval For Counting Failed Password Attempts - Ensure authselect changes
          are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Remediation where authselect
        tool is not present
      block:

      - name: Set Interval For Counting Failed Password Attempts - Check if pam_faillock.so
          is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Set Interval For Counting Failed Password Attempts - Enable pam_faillock.so
          preauth editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Set Interval For Counting Failed Password Attempts - Enable pam_faillock.so
          authfail editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Set Interval For Counting Failed Password Attempts - Enable pam_faillock.so
          account section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_passwords_pam_faillock_fail_interval # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_fail_interval: !!str 900
      tags:
        - always

    - name: Set Interval For Counting Failed Password Attempts - Check the presence of
        /etc/security/faillock.conf file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Ensure the pam_faillock.so
        fail_interval parameter in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*fail_interval\s*=
        line: fail_interval = {{ var_accounts_passwords_pam_faillock_fail_interval }}
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Ensure the pam_faillock.so
        fail_interval parameter not in PAM files
      block:

      - name: Set Interval For Counting Failed Password Attempts - Check if /etc/pam.d/system-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Set Interval For Counting Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Set Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Set Interval For Counting Failed Password Attempts - Ensure authselect
            custom profile is used if authselect is present
          block:

          - name: Set Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - Define a fact for
            control already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Set Interval For Counting Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Set Interval For Counting Failed Password Attempts - Ensure the "fail_interval"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bfail_interval\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Set Interval For Counting Failed Password Attempts - Ensure authselect
            changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Set Interval For Counting Failed Password Attempts - Check if /etc/pam.d/password-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Set Interval For Counting Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Set Interval For Counting Failed Password Attempts - Define the PAM file
            to be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Set Interval For Counting Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Set Interval For Counting Failed Password Attempts - Ensure authselect
            custom profile is used if authselect is present
          block:

          - name: Set Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - 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 Interval For Counting Failed Password Attempts - Define a fact for
            control already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Set Interval For Counting Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Set Interval For Counting Failed Password Attempts - Ensure the "fail_interval"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bfail_interval\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Set Interval For Counting Failed Password Attempts - Ensure authselect
            changes are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interval For Counting Failed Password Attempts - Ensure the pam_faillock.so
        fail_interval parameter in PAM files
      block:

      - name: Set Interval For Counting Failed Password Attempts - Check if pam_faillock.so
          fail_interval parameter is already enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*fail_interval
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_fail_interval_parameter_is_present

      - name: Set Interval For Counting Failed Password Attempts - Ensure the inclusion
          of pam_faillock.so preauth fail_interval parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 fail_interval={{ var_accounts_passwords_pam_faillock_fail_interval
            }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_fail_interval_parameter_is_present.found == 0

      - name: Set Interval For Counting Failed Password Attempts - Ensure the inclusion
          of pam_faillock.so authfail fail_interval parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
          line: \1required\3 fail_interval={{ var_accounts_passwords_pam_faillock_fail_interval
            }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_fail_interval_parameter_is_present.found == 0

      - name: Set Interval For Counting Failed Password Attempts - Ensure the desired
          value for pam_faillock.so preauth fail_interval parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)(fail_interval)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_fail_interval }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_fail_interval_parameter_is_present.found > 0

      - name: Set Interval For Counting Failed Password Attempts - Ensure the desired
          value for pam_faillock.so authfail fail_interval parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)(fail_interval)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_fail_interval }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_fail_interval_parameter_is_present.found > 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - DISA-STIG-RHEL-09-411085
      - NIST-800-53-AC-7(a)
      - NIST-800-53-CM-6(a)
      - accounts_passwords_pam_faillock_interval
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    var_accounts_passwords_pam_faillock_unlock_time='0'

    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

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

    fi

    AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
    SKIP_FAILLOCK_CHECK=false

    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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Check if system relies on
        authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Remediation where authselect
        tool is present
      block:

      - name: Set Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - Get authselect current features
        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_check_cmd is success

      - name: Set Lockout Time for Failed Password Attempts - Ensure "with-faillock" feature
          is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-faillock
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-faillock")

      - name: Set Lockout Time for Failed Password Attempts - Ensure authselect changes
          are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Remediation where authselect
        tool is not present
      block:

      - name: Set Lockout Time for Failed Password Attempts - Check if pam_faillock.so
          is already enabled
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail)
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_is_enabled

      - name: Set Lockout Time for Failed Password Attempts - Enable pam_faillock.so preauth
          editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so preauth
          insertbefore: ^auth.*sufficient.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Set Lockout Time for Failed Password Attempts - Enable pam_faillock.so authfail
          editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: auth        required      pam_faillock.so authfail
          insertbefore: ^auth.*required.*pam_deny\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0

      - name: Set Lockout Time for Failed Password Attempts - Enable pam_faillock.so account
          section editing PAM files
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          line: account     required      pam_faillock.so
          insertbefore: ^account.*required.*pam_unix\.so.*
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_is_enabled.found == 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_passwords_pam_faillock_unlock_time # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_unlock_time: !!str 0
      tags:
        - always

    - name: Set Lockout Time for Failed Password Attempts - Check the presence of /etc/security/faillock.conf
        file
      ansible.builtin.stat:
        path: /etc/security/faillock.conf
      register: result_faillock_conf_check
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Ensure the pam_faillock.so
        unlock_time parameter in /etc/security/faillock.conf
      ansible.builtin.lineinfile:
        path: /etc/security/faillock.conf
        regexp: ^\s*unlock_time\s*=
        line: unlock_time = {{ var_accounts_passwords_pam_faillock_unlock_time }}
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Ensure the pam_faillock.so
        unlock_time parameter not in PAM files
      block:

      - name: Set Lockout Time for Failed Password Attempts - Check if /etc/pam.d/system-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/system-auth
        register: result_pam_file_present

      - name: Set Lockout Time for Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Set Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Set Lockout Time for Failed Password Attempts - Ensure authselect custom
            profile is used if authselect is present
          block:

          - name: Set Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - Define a fact for control
            already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Set Lockout Time for Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Set Lockout Time for Failed Password Attempts - Ensure the "unlock_time"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bunlock_time\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Set Lockout Time for Failed Password Attempts - Ensure authselect changes
            are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists

      - name: Set Lockout Time for Failed Password Attempts - Check if /etc/pam.d/password-auth
          file is present
        ansible.builtin.stat:
          path: /etc/pam.d/password-auth
        register: result_pam_file_present

      - name: Set Lockout Time for Failed Password Attempts - Check the proper remediation
          for the system
        block:

        - name: Set Lockout Time for Failed Password Attempts - Define the PAM file to
            be edited as a local fact
          ansible.builtin.set_fact:
            pam_file_path: /etc/pam.d/password-auth

        - name: Set Lockout Time for Failed Password Attempts - Check if system relies
            on authselect tool
          ansible.builtin.stat:
            path: /usr/bin/authselect
          register: result_authselect_present

        - name: Set Lockout Time for Failed Password Attempts - Ensure authselect custom
            profile is used if authselect is present
          block:

          - name: Set Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - 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 Lockout Time for Failed Password Attempts - Define a fact for control
            already filtered in case filters are used
          ansible.builtin.set_fact:
            pam_module_control: ''

        - name: Set Lockout Time for Failed Password Attempts - Check if {{ pam_file_path
            }} file is present
          ansible.builtin.stat:
            path: '{{ pam_file_path }}'
          register: result_pam_file_present

        - name: Set Lockout Time for Failed Password Attempts - Ensure the "unlock_time"
            option from "pam_faillock.so" is not present in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: (.*auth.*pam_faillock.so.*)\bunlock_time\b=?[0-9a-zA-Z]*(.*)
            replace: \1\2
          register: result_pam_option_removal
          when: result_pam_file_present.stat.exists

        - name: Set Lockout Time for Failed Password Attempts - Ensure authselect changes
            are applied
          ansible.builtin.command:
            cmd: authselect apply-changes -b
          when:
          - result_authselect_present.stat.exists
          - result_pam_option_removal is changed
        when:
        - result_pam_file_present.stat.exists
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Lockout Time for Failed Password Attempts - Ensure the pam_faillock.so
        unlock_time parameter in PAM files
      block:

      - name: Set Lockout Time for Failed Password Attempts - Check if pam_faillock.so
          unlock_time parameter is already enabled in pam files
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: .*auth.*pam_faillock\.so (preauth|authfail).*unlock_time
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_faillock_unlock_time_parameter_is_present

      - name: Set Lockout Time for Failed Password Attempts - Ensure the inclusion of
          pam_faillock.so preauth unlock_time parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
          line: \1required\3 unlock_time={{ var_accounts_passwords_pam_faillock_unlock_time
            }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_unlock_time_parameter_is_present.found == 0

      - name: Set Lockout Time for Failed Password Attempts - Ensure the inclusion of
          pam_faillock.so authfail unlock_time parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
          line: \1required\3 unlock_time={{ var_accounts_passwords_pam_faillock_unlock_time
            }}
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_unlock_time_parameter_is_present.found == 0

      - name: Set Lockout Time for Failed Password Attempts - Ensure the desired value
          for pam_faillock.so preauth unlock_time parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)(unlock_time)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_unlock_time }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_unlock_time_parameter_is_present.found > 0

      - name: Set Lockout Time for Failed Password Attempts - Ensure the desired value
          for pam_faillock.so authfail unlock_time parameter in auth section
        ansible.builtin.lineinfile:
          path: '{{ item }}'
          backrefs: true
          regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)(unlock_time)=[0-9]+(.*)
          line: \1required\3\4={{ var_accounts_passwords_pam_faillock_unlock_time }}\5
          state: present
        loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
        when:
        - result_pam_faillock_unlock_time_parameter_is_present.found > 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not result_faillock_conf_check.stat.exists
      tags:
      - CJIS-5.5.3
      - DISA-STIG-RHEL-09-411090
      - NIST-800-171-3.1.8
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.1.7
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - accounts_passwords_pam_faillock_unlock_time
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Set Password Quality Requirements Group contains 1 group and 14 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 14 rules

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

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

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

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

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

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_dcredit='-1'

    if grep -sq dcredit /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/dcredit/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611070
      - 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 - Find
        pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611070
      - 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: Ensure PAM Enforces Password Requirements - Minimum Digit Characters - Ensure
        dcredit is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bdcredit\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611070
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611070
      - 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
stigref | SV-258110r1045223_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_dictcheck='1'

    if grep -sq dictcheck /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/dictcheck/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611105
      - 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 - Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611105
      - 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: Ensure PAM Enforces Password Requirements - Prevent the Use of Dictionary
        Words - Ensure dictcheck is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bdictcheck\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611105
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611105
      - 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 8 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
stigref | SV-258112r1045229_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_difok='8'

    if grep -sq difok /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/difok/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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
      - DISA-STIG-RHEL-09-611115
      - 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 8
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Different Characters -
        Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611115
      - 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: Ensure PAM Enforces Password Requirements - Minimum Different Characters -
        Ensure difok is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bdifok\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611115
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611115
      - 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.7
stigref | SV-258101r1045204_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; 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:
      - DISA-STIG-RHEL-09-611060
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611060
      - 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 - Minimum Lowercase Characters [ref]

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_lcredit='-1'

    if grep -sq lcredit /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/lcredit/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611065
      - 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 -
        Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611065
      - 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: Ensure PAM Enforces Password Requirements - Minimum Lowercase Characters -
        Ensure lcredit is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\blcredit\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611065
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_lcredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Maximum Consecutive Repeating Characters from Same Character Class [ref]

The pam_pwquality module's `maxclassrepeat` parameter controls requirements for consecutive repeating characters from the same character class. When set to a positive number, it will reject passwords which contain more than that number of consecutive characters from the same character class. Modify the `maxclassrepeat` setting in `/etc/security/pwquality.conf` to equal 4 to prevent a run of (4 + 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 a 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_maxclassrepeat

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, SRG-OS-000730-GPOS-00190
stigref | SV-258113r1045232_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_maxclassrepeat='4'

    if grep -sq maxclassrepeat /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/maxclassrepeat/d" /etc/security/pwquality.conf.d/*.conf
    fi

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

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

    # 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 "^maxclassrepeat\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^maxclassrepeat\\>.*/$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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611120
      - 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_maxclassrepeat
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_maxclassrepeat # promote to variable
      set_fact:
        var_password_pam_maxclassrepeat: !!str 4
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Maximum Consecutive Repeating
        Characters from Same Character Class - Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611120
      - 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_maxclassrepeat
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Maximum Consecutive Repeating
        Characters from Same Character Class - Ensure maxclassrepeat is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bmaxclassrepeat\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611120
      - 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_maxclassrepeat
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Maximum Consecutive Repeating
        Characters from Same Character Class - Ensure PAM variable maxclassrepeat is set
        accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*maxclassrepeat
        line: maxclassrepeat = {{ var_password_pam_maxclassrepeat }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611120
      - 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_maxclassrepeat
      - 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
stigref | SV-258114r1045235_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_maxrepeat='3'

    if grep -sq maxrepeat /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/maxrepeat/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611125
      - 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 - Find pwquality.conf.d
        files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611125
      - 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: Set Password Maximum Consecutive Repeating Characters - Ensure maxrepeat is
        not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bmaxrepeat\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611125
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611125
      - 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 Ensure PAM Enforces Password Requirements - Minimum Different Categories [ref]

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

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_minclass='4'

    if grep -sq minclass /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/minclass/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611130
      - 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 -
        Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611130
      - 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: Ensure PAM Enforces Password Requirements - Minimum Different Categories -
        Ensure minclass is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bminclass\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611130
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611130
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_minclass
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_minlen='15'

    if grep -sq minlen /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/minlen/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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
      - DISA-STIG-RHEL-09-611090
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_minlen
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_minlen # promote to variable
      set_fact:
        var_password_pam_minlen: !!str 15
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Length - Find pwquality.conf.d
        files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611090
      - 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: Ensure PAM Enforces Password Requirements - Minimum Length - Ensure minlen
        is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bminlen\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611090
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611090
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_minlen
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_ocredit='-1'

    if grep -sq ocredit /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/ocredit/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611100
      - 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 - Find
        pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611100
      - 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: Ensure PAM Enforces Password Requirements - Minimum Special Characters - Ensure
        ocredit is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bocredit\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611100
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611100
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_ocredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM password complexity module is enabled in password-auth [ref]

To enable PAM password complexity in password-auth file: Edit the `password` section in `/etc/pam.d/password-auth` to show `password requisite pam_pwquality.so`.
Rationale: | Enabling PAM password complexity permits to enforce strong passwords and consequently makes the system less prone to dictionary attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_pwquality_password_auth

References:

os-srg | SRG-OS-000069-GPOS-00037, SRG-OS-000070-GPOS-00038, SRG-OS-000480-GPOS-00227
stigref | SV-258097r1045193_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

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

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

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

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

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

            authselect apply-changes -b
        fi

    if ! grep -qP "^\s*password\s+requisite\s+pam_pwquality.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_pwquality.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_pwquality.so.*)/\1requisite \2/" "$PAM_FILE_PATH"
        else
            LAST_MATCH_LINE=$(grep -nP "^account.*required.*pam_permit\.so" "$PAM_FILE_PATH" | tail -n 1 | cut -d: -f 1)
            if [ ! -z $LAST_MATCH_LINE ]; then
                sed -i --follow-symlinks $LAST_MATCH_LINE" a password     requisite    pam_pwquality.so" "$PAM_FILE_PATH"
            else
                echo "password    requisite    pam_pwquality.so" >> "$PAM_FILE_PATH"
            fi
        fi
    fi
        if [ -f /usr/bin/authselect ]; then

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611040
      - accounts_password_pam_pwquality_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure PAM password complexity module is enabled in password-auth - Check
        if /etc/pam.d/password-auth file is present
      ansible.builtin.stat:
        path: /etc/pam.d/password-auth
      register: result_pam_file_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611040
      - accounts_password_pam_pwquality_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure PAM password complexity module is enabled in password-auth - Check
        the proper remediation for the system
      block:

      - name: Ensure PAM password complexity module is enabled in password-auth - Define
          the PAM file to be edited as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/password-auth

      - name: Ensure PAM password complexity module is enabled in password-auth - Check
          if system relies on authselect tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Ensure PAM password complexity module is enabled in password-auth - Ensure
          authselect custom profile is used if authselect is present
        block:

        - name: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - Define
          a fact for control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: requisite

      - name: Ensure PAM password complexity module is enabled in password-auth - 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_pwquality.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Ensure PAM password complexity module is enabled in password-auth - Include
          or update the PAM module line in {{ pam_file_path }}
        block:

        - name: Ensure PAM password complexity module is enabled in password-auth - 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_pwquality.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Ensure PAM password complexity module is enabled in password-auth - 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_pwquality.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Ensure PAM password complexity module is enabled in password-auth - Ensure
            the required PAM module line is included in {{ pam_file_path }}
          ansible.builtin.lineinfile:
            dest: '{{ pam_file_path }}'
            insertafter: ^account.*required.*pam_permit\.so
            line: password    {{ pam_module_control }}    pam_pwquality.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: Ensure PAM password complexity module is enabled in password-auth - 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: Ensure PAM password complexity module is enabled in password-auth - Ensure
          authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - |-
          (result_pam_accounts_password_pam_pwquality_password_auth_add is defined and result_pam_accounts_password_pam_pwquality_password_auth_add.changed)
           or (result_pam_accounts_password_pam_pwquality_password_auth_edit is defined and result_pam_accounts_password_pam_pwquality_password_auth_edit.changed)
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611040
      - accounts_password_pam_pwquality_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure PAM Enforces Password Requirements - Authentication Retry Prompts Permitted Per-Session in /etc/security/pwquality.conf [ref]

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

References:

os-srg | SRG-OS-000069-GPOS-00037
stigref | SV-258091r1045185_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_password_pam_retry='3'

    if grep -sq retry /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/retry/d" /etc/security/pwquality.conf.d/*.conf
    fi

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

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

    # 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 "^retry\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^retry\\>.*/$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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611010
      - accounts_password_pam_pwquality_retry
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_retry # promote to variable
      set_fact:
        var_password_pam_retry: !!str 3
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Authentication Retry Prompts Permitted
        Per-Session in /etc/security/pwquality.conf - Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611010
      - accounts_password_pam_pwquality_retry
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Authentication Retry Prompts Permitted
        Per-Session in /etc/security/pwquality.conf - Ensure retry is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bretry\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611010
      - accounts_password_pam_pwquality_retry
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure PAM Enforces Password Requirements - Authentication Retry Prompts Permitted
        Per-Session in /etc/security/pwquality.conf - Ensure PAM variable retry is set
        accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*retry
        line: retry = {{ var_password_pam_retry }}
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611010
      - accounts_password_pam_pwquality_retry
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM password complexity module is enabled in system-auth [ref]

To enable PAM password complexity in system-auth file: Edit the `password` section in `/etc/pam.d/system-auth` to show `password requisite pam_pwquality.so`.
Rationale: | Enabling PAM password complexity permits to enforce strong passwords and consequently makes the system less prone to dictionary attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_pwquality_system_auth

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258098r1045195_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

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

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

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

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

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

            authselect apply-changes -b
        fi

    if ! grep -qP "^\s*password\s+requisite\s+pam_pwquality.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_pwquality.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_pwquality.so.*)/\1requisite \2/" "$PAM_FILE_PATH"
        else
            LAST_MATCH_LINE=$(grep -nP "^account.*required.*pam_permit\.so" "$PAM_FILE_PATH" | tail -n 1 | cut -d: -f 1)
            if [ ! -z $LAST_MATCH_LINE ]; then
                sed -i --follow-symlinks $LAST_MATCH_LINE" a password     requisite    pam_pwquality.so" "$PAM_FILE_PATH"
            else
                echo "password    requisite    pam_pwquality.so" >> "$PAM_FILE_PATH"
            fi
        fi
    fi
        if [ -f /usr/bin/authselect ]; then

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611045
      - accounts_password_pam_pwquality_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure PAM password complexity module is enabled in system-auth - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611045
      - accounts_password_pam_pwquality_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure PAM password complexity module is enabled in system-auth - Check the
        proper remediation for the system
      block:

      - name: Ensure PAM password complexity module is enabled in system-auth - Define
          the PAM file to be edited as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/system-auth

      - name: Ensure PAM password complexity module is enabled in system-auth - Check
          if system relies on authselect tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Ensure PAM password complexity module is enabled in system-auth - Ensure
          authselect custom profile is used if authselect is present
        block:

        - name: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - Define
          a fact for control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: requisite

      - name: Ensure PAM password complexity module is enabled in system-auth - 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_pwquality.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Ensure PAM password complexity module is enabled in system-auth - Include
          or update the PAM module line in {{ pam_file_path }}
        block:

        - name: Ensure PAM password complexity module is enabled in system-auth - 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_pwquality.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Ensure PAM password complexity module is enabled in system-auth - 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_pwquality.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Ensure PAM password complexity module is enabled in system-auth - Ensure
            the required PAM module line is included in {{ pam_file_path }}
          ansible.builtin.lineinfile:
            dest: '{{ pam_file_path }}'
            insertafter: ^account.*required.*pam_permit\.so
            line: password    {{ pam_module_control }}    pam_pwquality.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: Ensure PAM password complexity module is enabled in system-auth - 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: Ensure PAM password complexity module is enabled in system-auth - Ensure
          authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - |-
          (result_pam_accounts_password_pam_pwquality_system_auth_add is defined and result_pam_accounts_password_pam_pwquality_system_auth_add.changed)
           or (result_pam_accounts_password_pam_pwquality_system_auth_edit is defined and result_pam_accounts_password_pam_pwquality_system_auth_edit.changed)
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611045
      - accounts_password_pam_pwquality_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

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

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

Rationale:

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libpwquality; }; then

    var_password_pam_ucredit='-1'

    if grep -sq ucredit /etc/security/pwquality.conf.d/*.conf ; then
        sed -i "/ucredit/d" /etc/security/pwquality.conf.d/*.conf
    fi

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/security/pwquality.conf" >> "/etc/security/pwquality.conf"
        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:
      - DISA-STIG-RHEL-09-611110
      - 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 -
        Find pwquality.conf.d files
      ansible.builtin.find:
        paths: /etc/security/pwquality.conf.d/
        patterns: '*.conf'
      register: pwquality_conf_d_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611110
      - 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: Ensure PAM Enforces Password Requirements - Minimum Uppercase Characters -
        Ensure ucredit is not set in pwquality.conf.d
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^\s*\bucredit\b.*
        state: absent
      with_items: '{{ pwquality_conf_d_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611110
      - 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: 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"libpwquality" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611110
      - 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 3 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/libuser.conf [ref]

In `/etc/libuser.conf`, add or correct the following line in its `[defaults]` section to ensure the system will use the sha512 algorithm for password hashing:

    crypt_style = sha512

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_libuserconf

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q libuser; }; then

    var_password_hashing_algorithm_pam='sha512'

    LIBUSER_CONF="/etc/libuser.conf"
    CRYPT_STYLE_REGEX='[[:space:]]*\[defaults](.*(\n)+)+?[[:space:]]*crypt_style[[:space:]]*'

    # Try find crypt_style in [defaults] section. If it is here, then change algorithm to sha512.
    # If it isn't here, then add it to [defaults] section.
    if grep -qzosP $CRYPT_STYLE_REGEX $LIBUSER_CONF ; then
            sed -i "s/\(crypt_style[[:space:]]*=[[:space:]]*\).*/\1$var_password_hashing_algorithm_pam/g" $LIBUSER_CONF
    elif grep -qs "\[defaults]" $LIBUSER_CONF ; then
            sed -i "/[[:space:]]*\[defaults]/a crypt_style = $var_password_hashing_algorithm_pam" $LIBUSER_CONF
    else
            echo -e "[defaults]\ncrypt_style = $var_password_hashing_algorithm_pam" >> $LIBUSER_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.2
      - DISA-STIG-RHEL-09-611135
      - 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
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_password_hashing_algorithm_libuserconf
    - name: XCCDF Value var_password_hashing_algorithm_pam # promote to variable
      set_fact:
        var_password_hashing_algorithm_pam: !!str sha512
      tags:
        - always

    - name: Set Password Hashing Algorithm in /etc/libuser.conf - Set Password Hashing
        Algorithm in /etc/libuser.conf
      ansible.builtin.lineinfile:
        dest: /etc/libuser.conf
        insertafter: ^\s*\[defaults]
        regexp: ^#?crypt_style
        line: crypt_style = {{ var_password_hashing_algorithm_pam }}
        state: present
        create: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"libuser" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-611135
      - 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
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_password_hashing_algorithm_libuserconf

#### 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 SHA512 as the hashing algorithm:

    ENCRYPT_METHOD SHA512

Rationale:

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q shadow-utils; }; then

    var_password_hashing_algorithm='SHA512'

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/login.defs" >> "/etc/login.defs"
        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.2
      - DISA-STIG-RHEL-09-611140
      - 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
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_password_hashing_algorithm_logindefs
    - name: XCCDF Value var_password_hashing_algorithm # promote to variable
      set_fact:
        var_password_hashing_algorithm: !!str SHA512
      tags:
        - always

    - name: Set Password Hashing Algorithm in /etc/login.defs
      ansible.builtin.lineinfile:
        dest: /etc/login.defs
        regexp: ^#?ENCRYPT_METHOD
        line: ENCRYPT_METHOD {{ var_password_hashing_algorithm.split('|')[0] }}
        state: present
        create: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-611140
      - 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
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - set_password_hashing_algorithm_logindefs

#### Rule Set PAM''s Password Hashing Algorithm - password-auth [ref]

The PAM system service can be configured to only store encrypted representations of passwords. In `/etc/pam.d/password-auth`, 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 `sha512` and no other hashing algorithms as shown below:

    password    sufficient    pam_unix.so sha512
                        other arguments...

This will help ensure that new passwords for local users will be stored using the sha512 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_passwordauth

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
ism | 0418, 1055, 1402
cis | 5.3.3.4.3
stigref | SV-258233r1015136_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; then

    var_password_hashing_algorithm_pam='sha512'

    PAM_FILE_PATH="/etc/pam.d/password-auth"

    if [ -e "$PAM_FILE_PATH" ] ; then
        PAM_FILE_PATH="$PAM_FILE_PATH"
        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_PATH")
            PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

            authselect apply-changes -b
        fi

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

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

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

    for hash_option in "${HASHING_ALGORITHMS_OPTIONS[@]}"; do
      if [ "$hash_option" != "$var_password_hashing_algorithm_pam" ]; then
        if grep -qP "^\s*password\s+.*\s+pam_unix.so\s+.*\b$hash_option\b" "$PAM_FILE_PATH"; then
          if [ -e "$PAM_FILE_PATH" ] ; then
        PAM_FILE_PATH="$PAM_FILE_PATH"
        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_PATH")
            PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

            authselect apply-changes -b
        fi

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-671025
      - 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
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_passwordauth
    - name: XCCDF Value var_password_hashing_algorithm_pam # promote to variable
      set_fact:
        var_password_hashing_algorithm_pam: !!str sha512
      tags:
        - always

    - name: Set PAM's Password Hashing Algorithm - password-auth - Check if /etc/pam.d/password-auth
        file is present
      ansible.builtin.stat:
        path: /etc/pam.d/password-auth
      register: result_pam_file_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-671025
      - 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
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_passwordauth

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

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

      - name: Set PAM's Password Hashing Algorithm - password-auth - 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 - password-auth - Ensure authselect
          custom profile is used if authselect is present
        block:

        - name: Set PAM's Password Hashing Algorithm - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - Include or update
          the PAM module line in {{ pam_file_path }}
        block:

        - name: Set PAM's Password Hashing Algorithm - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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_passwordauth_option_present

      - name: Set PAM's Password Hashing Algorithm - password-auth - 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_passwordauth_add
        when:
        - result_pam_module_set_password_hashing_algorithm_passwordauth_option_present.found
          is defined
        - result_pam_module_set_password_hashing_algorithm_passwordauth_option_present.found
          == 0

      - name: Set PAM's Password Hashing Algorithm - password-auth - 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_passwordauth_add is defined and result_pam_set_password_hashing_algorithm_passwordauth_add.changed)
           or (result_pam_set_password_hashing_algorithm_passwordauth_edit is defined and result_pam_set_password_hashing_algorithm_passwordauth_edit.changed)
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-671025
      - 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
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_passwordauth

    - name: Set PAM's Password Hashing Algorithm - password-auth - Check if /etc/pam.d/password-auth
        File is Present
      ansible.builtin.stat:
        path: /etc/pam.d/password-auth
      register: result_pam_file_present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-671025
      - 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
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_passwordauth

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

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

      - name: Set PAM's Password Hashing Algorithm - password-auth - 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 - password-auth - Ensure authselect
          custom profile is used if authselect is present
        block:

        - name: Set PAM's Password Hashing Algorithm - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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 - password-auth - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - result_pam_file_present.stat.exists
      tags:
      - CJIS-5.6.2.2
      - DISA-STIG-RHEL-09-671025
      - 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
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - set_password_hashing_algorithm_passwordauth

#### Rule Disallow Configuration to Bypass Password Requirements for Privilege Escalation [ref]

Verify the operating system is not configured to bypass password requirements for privilege escalation. Check the configuration of the "/etc/pam.d/sudo" file with the following command:

    $ sudo grep pam_succeed_if /etc/pam.d/sudo

If any occurrences of "pam_succeed_if" is returned from the command, this is a finding.

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 the user re-authenticate.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_disallow_bypass_password_sudo

References:

nist | IA-11
os-srg | SRG-OS-000373-GPOS-00156, SRG-OS-000373-GPOS-00157, SRG-OS-000373-GPOS-00158
stigref | SV-258118r1050789_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q pam && rpm --quiet -q kernel-core ); then

    sed -i '/pam_succeed_if/d' /etc/pam.d/sudo

    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:
      - DISA-STIG-RHEL-09-611145
      - NIST-800-53-IA-11
      - disallow_bypass_password_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Check for pam_succeed_if entry
      ansible.builtin.lineinfile:
        path: /etc/pam.d/sudo
        create: false
        regexp: pam_succeed_if
        state: absent
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-611145
      - NIST-800-53-IA-11
      - disallow_bypass_password_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Displays Last Logon/Access Notification [ref]

To configure the system to notify users of last logon/access using `pam_lastlog`, add or correct the `pam_lastlog` settings in `/etc/pam.d/postlogin` to include `showfailed` option, such as:

    session     [default=1]    pam_lastlog.so showfailed

And make sure that the `silent` option is not set for this specific line.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report.
Warning: `authselect` contains an authselect feature to easily and properly enable Last Logon notifications with `pam_lastlog.so` module. If a custom profile was created and used in the system before this authselect feature was available, the new feature can't be used with this custom profile and the remediation will fail. In this case, the custom profile should be recreated or manually updated.

Rationale: | Users need to be aware of activity that occurs regarding their account. Providing users with information regarding the number of unsuccessful attempts that were made to login to their account allows the user to determine if any unauthorized activity has occurred and gives them an opportunity to notify administrators.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_display_login_attempts

References:

cis-csc | 1, 12, 15, 16
cjis | 5.5.2
cobit5 | DSS05.04, DSS05.10, DSS06.10
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | AC-9, AC-9(1)
nist-csf | PR.AC-7
pcidss | Req-10.2.4
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 10.2.1.4, 10.2.1, 10.2
stigref | SV-258076r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q pam && rpm --quiet -q kernel-core ); then

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

            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 "/etc/pam.d/postlogin")
            PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

            authselect apply-changes -b
            if [ -e "$PAM_FILE_PATH" ] ; then
                PAM_FILE_PATH="$PAM_FILE_PATH"
                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_PATH")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

                    if ! grep -qP "^\s*session\s+\[default=1\]\s+pam_lastlog.so\s*.*" "$PAM_FILE_PATH"; then
                        # Line matching group + control + module was not found. Check group + module.
                        if [ "$(grep -cP '^\s*session\s+.*\s+pam_lastlog.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*session\s+).*(\bpam_lastlog.so.*)/\1[default=1] \2/" "$PAM_FILE_PATH"
                        else
                            LAST_MATCH_LINE=$(grep -nP "^\s*session\s+.*pam_succeed_if\.so.*" "$PAM_FILE_PATH" | tail -n 1 | cut -d: -f 1)
                            if [ ! -z $LAST_MATCH_LINE ]; then
                                sed -i --follow-symlinks $LAST_MATCH_LINE" a session     [default=1]    pam_lastlog.so" "$PAM_FILE_PATH"
                            else
                                echo "session    [default=1]    pam_lastlog.so" >> "$PAM_FILE_PATH"
                            fi
                        fi
                    fi
                    # Check the option
                    if ! grep -qP "^\s*session\s+\[default=1\]\s+pam_lastlog.so\s*.*\sshowfailed\b" "$PAM_FILE_PATH"; then
                        sed -i -E --follow-symlinks "/\s*session\s+\[default=1\]\s+pam_lastlog.so.*/ s/$/ showfailed/" "$PAM_FILE_PATH"
                    fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "$PAM_FILE_PATH was not found" >&2
            fi
            if [ -e "$PAM_FILE_PATH" ] ; then
                PAM_FILE_PATH="$PAM_FILE_PATH"
                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_PATH")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

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

                    authselect apply-changes -b
                fi
            else
                echo "$PAM_FILE_PATH was not found" >&2
            fi
        fi
    else
        if [ -e "/etc/pam.d/postlogin" ] ; then
                PAM_FILE_PATH="/etc/pam.d/postlogin"
                if [ -f /usr/bin/authselect ]; then

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

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

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

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

                    authselect apply-changes -b
                fi

                    if ! grep -qP "^\s*session\s+\[default=1\]\s+pam_lastlog.so\s*.*" "$PAM_FILE_PATH"; then
                        # Line matching group + control + module was not found. Check group + module.
                        if [ "$(grep -cP '^\s*session\s+.*\s+pam_lastlog.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*session\s+).*(\bpam_lastlog.so.*)/\1[default=1] \2/" "$PAM_FILE_PATH"
                        else
                            LAST_MATCH_LINE=$(grep -nP "^\s*session\s+.*pam_succeed_if\.so.*" "$PAM_FILE_PATH" | tail -n 1 | cut -d: -f 1)
                            if [ ! -z $LAST_MATCH_LINE ]; then
                                sed -i --follow-symlinks $LAST_MATCH_LINE" a session     [default=1]    pam_lastlog.so" "$PAM_FILE_PATH"
                            else
                                echo "session    [default=1]    pam_lastlog.so" >> "$PAM_FILE_PATH"
                            fi
                        fi
                    fi
                    # Check the option
                    if ! grep -qP "^\s*session\s+\[default=1\]\s+pam_lastlog.so\s*.*\sshowfailed\b" "$PAM_FILE_PATH"; then
                        sed -i -E --follow-symlinks "/\s*session\s+\[default=1\]\s+pam_lastlog.so.*/ s/$/ showfailed/" "$PAM_FILE_PATH"
                    fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "/etc/pam.d/postlogin was not found" >&2
            fi
        if [ -e "/etc/pam.d/postlogin" ] ; then
                PAM_FILE_PATH="/etc/pam.d/postlogin"
                if [ -f /usr/bin/authselect ]; then

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

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

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

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

                    authselect apply-changes -b
                fi

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

                    authselect apply-changes -b
                fi
            else
                echo "/etc/pam.d/postlogin was not found" >&2
            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
      - DISA-STIG-RHEL-09-412075
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - PCI-DSS-Req-10.2.4
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.4
      - configure_strategy
      - display_login_attempts
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure PAM Displays Last Logon/Access Notification - Check if system relies
        on authselect tool
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-412075
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - PCI-DSS-Req-10.2.4
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.4
      - configure_strategy
      - display_login_attempts
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure PAM Displays Last Logon/Access Notification - Collect the Available
        authselect Features
      ansible.builtin.command:
        cmd: authselect list-features sssd
      register: result_authselect_available_features
      changed_when: false
      check_mode: false
      when:
      - ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-412075
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - PCI-DSS-Req-10.2.4
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.4
      - configure_strategy
      - display_login_attempts
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure PAM Displays Last Logon/Access Notification - Configure pam_lastlog.so
        Using authselect Feature
      block:

      - name: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - Get authselect Features
          Currently Enabled
        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_check_cmd is success

      - name: Ensure PAM Displays Last Logon/Access Notification - Ensure "with-silent-lastlog"
          Feature is Disabled Using authselect Tool
        ansible.builtin.command:
          cmd: authselect disable-feature with-silent-lastlog
        register: result_authselect_disable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is search("with-silent-lastlog")

      - name: Ensure PAM Displays Last Logon/Access Notification - Ensure authselect changes
          are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_disable_feature_cmd is not skipped
        - result_authselect_disable_feature_cmd is success
      when:
      - ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - result_authselect_present.stat.exists
      - result_authselect_available_features.stdout is search("with-silent-lastlog")
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-412075
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - PCI-DSS-Req-10.2.4
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.4
      - configure_strategy
      - display_login_attempts
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure PAM Displays Last Logon/Access Notification - Configure pam_lastlog.so
        in appropriate PAM files
      block:

      - name: Ensure PAM Displays Last Logon/Access Notification - Define the PAM file
          to be edited as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/postlogin

      - name: Ensure PAM Displays Last Logon/Access Notification - Check if system relies
          on authselect tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Ensure PAM Displays Last Logon/Access Notification - Ensure authselect custom
          profile is used if authselect is present
        block:

        - name: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - Define a fact for control
          already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: '[default=1]'

      - name: Ensure PAM Displays Last Logon/Access Notification - Check if expected PAM
          module line is present in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          regexp: ^\s*session\s+{{ pam_module_control | regex_escape() }}\s+pam_lastlog.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Ensure PAM Displays Last Logon/Access Notification - Include or update the
          PAM module line in {{ pam_file_path }}
        block:

        - name: Ensure PAM Displays Last Logon/Access Notification - Check if required
            PAM module line is present in {{ pam_file_path }} with different control
          ansible.builtin.lineinfile:
            path: '{{ pam_file_path }}'
            regexp: ^\s*session\s+.*\s+pam_lastlog.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Ensure PAM Displays Last Logon/Access Notification - Ensure the correct
            control for the required PAM module line in {{ pam_file_path }}
          ansible.builtin.replace:
            dest: '{{ pam_file_path }}'
            regexp: ^(\s*session\s+).*(\bpam_lastlog.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Ensure PAM Displays Last Logon/Access Notification - Ensure the required
            PAM module line is included in {{ pam_file_path }}
          ansible.builtin.lineinfile:
            dest: '{{ pam_file_path }}'
            insertafter: ^\s*session\s+.*pam_succeed_if\.so.*
            line: session    {{ pam_module_control }}    pam_lastlog.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: Ensure PAM Displays Last Logon/Access Notification - 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: Ensure PAM Displays Last Logon/Access Notification - Define a fact for control
          already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: '[default=1]'

      - name: Ensure PAM Displays Last Logon/Access Notification - Check if the required
          PAM module option is present in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          regexp: ^\s*session\s+{{ pam_module_control | regex_escape() }}\s+pam_lastlog.so\s*.*\sshowfailed\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_display_login_attempts_option_present

      - name: Ensure PAM Displays Last Logon/Access Notification - Ensure the "showfailed"
          PAM option for "pam_lastlog.so" is included in {{ pam_file_path }}
        ansible.builtin.lineinfile:
          path: '{{ pam_file_path }}'
          backrefs: true
          regexp: ^(\s*session\s+{{ pam_module_control | regex_escape() }}\s+pam_lastlog.so.*)
          line: \1 showfailed
          state: present
        register: result_pam_display_login_attempts_add
        when:
        - result_pam_module_display_login_attempts_option_present.found is defined
        - result_pam_module_display_login_attempts_option_present.found == 0

      - name: Ensure PAM Displays Last Logon/Access Notification - Define a fact for control
          already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: '[default=1]'

      - name: Ensure PAM Displays Last Logon/Access Notification - Check if {{ pam_file_path
          }} file is present
        ansible.builtin.stat:
          path: '{{ pam_file_path }}'
        register: result_pam_file_present

      - name: Ensure PAM Displays Last Logon/Access Notification - Ensure the "silent"
          option from "pam_lastlog.so" is not present in {{ pam_file_path }}
        ansible.builtin.replace:
          dest: '{{ pam_file_path }}'
          regexp: (.*session.*{{ pam_module_control | regex_escape() }}.*pam_lastlog.so.*)\bsilent\b=?[0-9a-zA-Z]*(.*)
          replace: \1\2
        register: result_pam_option_removal
        when: result_pam_file_present.stat.exists
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-412075
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - PCI-DSS-Req-10.2.4
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.4
      - configure_strategy
      - display_login_attempts
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

Group Protect Physical Console Access Group contains 2 groups and 12 rules
[ref] It is impossible to fully protect a system from an attacker with physical access, so securing the space in which the system is located should be considered a necessary step. However, there are some steps which, if taken, make it more difficult for an attacker to quickly or undetectably modify a system from its console.
Group Configure Screen Locking Group contains 1 group and 5 rules
[ref] When a user must temporarily leave an account logged-in, screen locking should be employed to prevent passersby from abusing the account. User education and training is particularly important for screen locking to be effective, and policies can be implemented to reinforce this. Automatic screen locking is only meant as a safeguard for those cases where a user forgot to lock the screen.
Group Hardware Tokens for Authentication Group contains 5 rules
[ref] The use of hardware tokens such as smart cards for system login provides stronger, two-factor authentication than using a username and password. In Red Hat Enterprise Linux servers and workstations, hardware token login is not enabled by default and must be enabled in the system settings.

#### Rule Install the opensc Package For Multifactor Authentication [ref]

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

    $ sudo dnf install opensc

Rationale:

Using an authentication device, such as a CAC or token that is separate from the information system, ensures that even if the information system is compromised, that compromise will not affect credentials stored on the authentication device.
Multifactor solutions that require devices separate from information systems gaining access include, for example, hardware tokens providing time-based or challenge-response authenticators and smart cards or similar secure authentication devices issued by an organization or identity provider.

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

References:

nist | CM-6(a)
os-srg | SRG-OS-000375-GPOS-00160, SRG-OS-000376-GPOS-00161
ism | 1386
stigref | SV-258126r1045255_rule

Remediation script ⇲

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

    dnf install opensc

Remediation script ⇲

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

    package install opensc

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "opensc" ; then
        dnf install -y "opensc"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_opensc

    class install_opensc {
      package { 'opensc':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=opensc

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611185
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_opensc_installed

    - name: Ensure opensc is installed
      ansible.builtin.package:
        name: opensc
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611185
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_opensc_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Install the pcsc-lite package [ref]

The `pcsc-lite` package can be installed with the following command:

    $ sudo dnf install pcsc-lite

Rationale: | The pcsc-lite package must be installed if it is to be available for multifactor authentication using smartcards.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_pcsc-lite_installed

References:

nist | CM-6(a)
os-srg | SRG-OS-000375-GPOS-00160
ism | 1386
stigref | SV-258124r1045250_rule

Remediation script ⇲

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

    dnf install pcsc-lite

Remediation script ⇲

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

    package install pcsc-lite

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "pcsc-lite" ; then
        dnf install -y "pcsc-lite"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_pcsc-lite

    class install_pcsc-lite {
      package { 'pcsc-lite':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=pcsc-lite

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611175
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pcsc-lite_installed

    - name: Ensure pcsc-lite is installed
      ansible.builtin.package:
        name: pcsc-lite
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611175
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pcsc-lite_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "pcsc-lite"
    version = "*"

#### Rule Install Smart Card Packages For Multifactor Authentication [ref]

Configure the operating system to implement multifactor authentication by installing the required package with the following command: The `openssl-pkcs11` package can be installed with the following command:

    $ sudo dnf install openssl-pkcs11

Rationale:

Using an authentication device, such as a CAC or token that is separate from the information system, ensures that even if the information system is compromised, that compromise will not affect credentials stored on the authentication device.
Multifactor solutions that require devices separate from information systems gaining access include, for example, hardware tokens providing time-based or challenge-response authenticators and smart cards or similar secure authentication devices issued by an organization or identity provider.

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

References:

nist | CM-6(a)
pcidss | Req-8.3
os-srg | SRG-OS-000105-GPOS-00052, SRG-OS-000375-GPOS-00160, SRG-OS-000375-GPOS-00161, SRG-OS-000377-GPOS-00162
stigref | SV-257838r1044912_rule

Remediation script ⇲

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

    dnf install openssl-pkcs11

Remediation script ⇲

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

    package install openssl-pkcs11

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { ! ( grep -sqE "^.*\.s390x$" /proc/sys/kernel/osrelease || grep -sqE "^s390x$" /proc/sys/kernel/arch; ); }; then

    if ! rpm -q --quiet "openssl-pkcs11" ; then
        dnf install -y "openssl-pkcs11"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_openssl-pkcs11

    class install_openssl-pkcs11 {
      package { 'openssl-pkcs11':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=openssl-pkcs11

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-215075
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.3
      - enable_strategy
      - install_smartcard_packages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure openssl-pkcs11 is installed
      ansible.builtin.package:
        name: openssl-pkcs11
        state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ansible_architecture != "s390x"
      tags:
      - DISA-STIG-RHEL-09-215075
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.3
      - enable_strategy
      - install_smartcard_packages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "openssl-pkcs11"
    version = "*"

#### Rule Enable the pcscd Service [ref]

The `pcscd` service can be enabled with the following command:

    $ sudo systemctl enable pcscd.service

Rationale:

Using an authentication device, such as a CAC or token that is separate from the information system, ensures that even if the information system is compromised, that compromise will not affect credentials stored on the authentication device.
Multifactor solutions that require devices separate from information systems gaining access include, for example, hardware tokens providing time-based or challenge-response authenticators and smart cards or similar secure authentication devices issued by an organization or identity provider.

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

References:

nist | IA-2(1), IA-2(2), IA-2(3), IA-2(4), IA-2(6), IA-2(7), IA-2(11), CM-6(a)
pcidss | Req-8.3
os-srg | SRG-OS-000375-GPOS-00160
ism | 1386
stigref | SV-258125r1045253_rule

Remediation script ⇲

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

    service enable pcscd

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'pcscd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'pcscd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'pcscd.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_pcscd

    class enable_pcscd {
      service {'pcscd':
        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:
      - DISA-STIG-RHEL-09-611180
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - NIST-800-53-IA-2(11)
      - NIST-800-53-IA-2(2)
      - NIST-800-53-IA-2(3)
      - NIST-800-53-IA-2(4)
      - NIST-800-53-IA-2(6)
      - NIST-800-53-IA-2(7)
      - PCI-DSS-Req-8.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_pcscd_enabled

    - name: Enable the pcscd Service - Enable service pcscd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable the pcscd Service - Enable Service pcscd
        ansible.builtin.systemd:
          name: pcscd
          enabled: true
          state: started
          masked: false
        when:
        - '"pcsc-lite" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611180
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - NIST-800-53-IA-2(11)
      - NIST-800-53-IA-2(2)
      - NIST-800-53-IA-2(3)
      - NIST-800-53-IA-2(4)
      - NIST-800-53-IA-2(6)
      - NIST-800-53-IA-2(7)
      - PCI-DSS-Req-8.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_pcscd_enabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["pcscd"]

#### Rule Configure opensc Smart Card Drivers [ref]

The OpenSC smart card tool can auto-detect smart card drivers; however, setting the smart card drivers in use by your organization helps to prevent users from using unauthorized smart cards. The default smart card driver for this profile is `cac`. To configure the OpenSC driver, edit the `/etc/opensc.conf` and add the following line into the file in the `app default` block, so it will look like:

    app default {
       ...
       card_drivers = cac;
    }

Rationale: | Smart card login provides two-factor authentication stronger than that provided by a username and password combination. Smart cards leverage PKI (public key infrastructure) in order to provide and verify credentials. Configuring the smart card driver in use by your organization helps to prevent users from using unauthorized smart cards.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_configure_opensc_card_drivers

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-2(1), IA-2(2), IA-2(3), IA-2(4), IA-2(6), IA-2(7), IA-2(11), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
pcidss | Req-8.3
os-srg | SRG-OS-000104-GPOS-00051, SRG-OS-000106-GPOS-00053, SRG-OS-000107-GPOS-00054, SRG-OS-000109-GPOS-00056, SRG-OS-000108-GPOS-00055, SRG-OS-000108-GPOS-00057, SRG-OS-000108-GPOS-00058
ism | 1386
stigref | SV-258121r1102086_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_smartcard_drivers='cac'

    OPENSC_TOOL="/usr/bin/opensc-tool"

    if [ -f "${OPENSC_TOOL}" ]; then
        ${OPENSC_TOOL} -S app:default:card_drivers:$var_smartcard_drivers
    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:
      - DISA-STIG-RHEL-09-611160
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - NIST-800-53-IA-2(11)
      - NIST-800-53-IA-2(2)
      - NIST-800-53-IA-2(3)
      - NIST-800-53-IA-2(4)
      - NIST-800-53-IA-2(6)
      - NIST-800-53-IA-2(7)
      - PCI-DSS-Req-8.3
      - configure_opensc_card_drivers
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_smartcard_drivers # promote to variable
      set_fact:
        var_smartcard_drivers: !!str cac
      tags:
        - always

    - name: Check existence of opensc conf
      ansible.builtin.stat:
        path: /etc/opensc-{{ ansible_architecture }}.conf
      register: opensc_conf_cd
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611160
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - NIST-800-53-IA-2(11)
      - NIST-800-53-IA-2(2)
      - NIST-800-53-IA-2(3)
      - NIST-800-53-IA-2(4)
      - NIST-800-53-IA-2(6)
      - NIST-800-53-IA-2(7)
      - PCI-DSS-Req-8.3
      - configure_opensc_card_drivers
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure smartcard driver block
      block:

      - name: Check if card_drivers is defined
        ansible.builtin.command: /usr/bin/opensc-tool -G app:default:card_drivers
        changed_when: false
        register: card_drivers

      - name: Configure opensc Smart Card Drivers
        ansible.builtin.command: |
          /usr/bin/opensc-tool -S app:default:card_drivers:{{ var_smartcard_drivers }}
        when:
        - card_drivers.stdout != var_smartcard_drivers
      when:
      - '"kernel-core" in ansible_facts.packages'
      - opensc_conf_cd.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611160
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - NIST-800-53-IA-2(11)
      - NIST-800-53-IA-2(2)
      - NIST-800-53-IA-2(3)
      - NIST-800-53-IA-2(4)
      - NIST-800-53-IA-2(6)
      - NIST-800-53-IA-2(7)
      - PCI-DSS-Req-8.3
      - configure_opensc_card_drivers
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Disable debug-shell SystemD Service [ref]

SystemD's `debug-shell` service is intended to diagnose SystemD related boot issues with various `systemctl` commands. Once enabled and following a system reboot, the root shell will be available on `tty9` which is access by pressing `CTRL-ALT-F9`. The `debug-shell` service should only be used for SystemD related issues and should otherwise be disabled.
By default, the `debug-shell` SystemD service is already disabled. The `debug-shell` service can be disabled with the following command:

    $ sudo systemctl mask --now debug-shell.service

Rationale: | This prevents attackers with physical access from trivially bypassing security on the machine through valid troubleshooting configurations and gaining root access when the system is rebooted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_debug-shell_disabled

References:

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)
nist | CM-6
ospp | FIA_UAU.1
os-srg | SRG-OS-000324-GPOS-00125, SRG-OS-000480-GPOS-00227
stigref | SV-257786r1044834_rule

Remediation script ⇲

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

    service disable debug-shell

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" stop 'debug-shell.service'
    fi
    "$SYSTEMCTL_EXEC" disable 'debug-shell.service'
    "$SYSTEMCTL_EXEC" mask 'debug-shell.service'
    # Disable socket activation if we have a unit file for it
    if "$SYSTEMCTL_EXEC" -q list-unit-files debug-shell.socket; then
        if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
          "$SYSTEMCTL_EXEC" stop 'debug-shell.socket'
        fi
        "$SYSTEMCTL_EXEC" mask 'debug-shell.socket'
    fi
    # The service may not be running because it has been started and failed,
    # so let's reset the state so OVAL checks pass.
    # Service should be 'inactive', not 'failed' after reboot though.
    "$SYSTEMCTL_EXEC" reset-failed 'debug-shell.service' || true

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

Remediation Puppet snippet ⇲

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

    include disable_debug-shell

    class disable_debug-shell {
      service {'debug-shell':
        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:
      - DISA-STIG-RHEL-09-211055
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_debug-shell_disabled

    - name: Disable debug-shell SystemD Service - Disable service debug-shell
      block:

      - name: Disable debug-shell SystemD 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 debug-shell SystemD Service - Ensure debug-shell.service is Masked
        ansible.builtin.systemd:
          name: debug-shell.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("debug-shell.service", multiline=True)

      - name: Unit Socket Exists - debug-shell.socket
        ansible.builtin.command: systemctl -q list-unit-files debug-shell.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable debug-shell SystemD Service - Disable Socket debug-shell
        ansible.builtin.systemd:
          name: debug-shell.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("debug-shell.socket", multiline=True)
      tags:
      - DISA-STIG-RHEL-09-211055
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_debug-shell_disabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: debug-shell.service
            enabled: false
            mask: true
          - name: debug-shell.socket
            enabled: false
            mask: true

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["debug-shell"]

#### Rule Disable Ctrl-Alt-Del Burst Action [ref]

By default, `SystemD` will reboot the system if the `Ctrl-Alt-Del` key sequence is pressed Ctrl-Alt-Delete more than 7 times in 2 seconds.
To configure the system to ignore the `CtrlAltDelBurstAction` setting, add or modify the following to `/etc/systemd/system.conf`:

    CtrlAltDelBurstAction=none

Warning: Disabling the `Ctrl-Alt-Del` key sequence in `/etc/init/control-alt-delete.conf` DOES NOT disable the `Ctrl-Alt-Del` key sequence if running in `runlevel 6` (e.g. in GNOME, KDE, etc.)! The `Ctrl-Alt-Del` key sequence will only be disabled if running in the non-graphical `runlevel 3`.

Rationale: | A locally logged-in user who presses Ctrl-Alt-Del, when at the console, can reboot the system. If accidentally pressed, as could happen in the case of mixed OS environment, this can create the risk of short-term loss of availability of systems due to unintentional reboot.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_disable_ctrlaltdel_burstaction

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
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), CM-6(a)
nist-csf | PR.AC-4, PR.DS-5
ospp | FAU_GEN.1.2
os-srg | SRG-OS-000324-GPOS-00125, SRG-OS-000480-GPOS-00227
stigref | SV-257784r1044832_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q systemd; }; then

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

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

    # 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 "^CtrlAltDelBurstAction=\\>" "/etc/systemd/system.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^CtrlAltDelBurstAction=\\>.*/$escaped_formatted_output/gi" "/etc/systemd/system.conf"
    else
        if [[ -s "/etc/systemd/system.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/systemd/system.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/systemd/system.conf"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/systemd/system.conf" >> "/etc/systemd/system.conf"
        printf '%s\n' "$formatted_output" >> "/etc/systemd/system.conf"
    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:
      - DISA-STIG-RHEL-09-211045
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(a)
      - disable_ctrlaltdel_burstaction
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

    - name: Disable Ctrl-Alt-Del Burst Action
      ansible.builtin.lineinfile:
        dest: /etc/systemd/system.conf
        state: present
        regexp: ^CtrlAltDelBurstAction
        line: CtrlAltDelBurstAction=none
        create: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-211045
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(a)
      - disable_ctrlaltdel_burstaction
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,CtrlAltDelBurstAction%3Dnone
            mode: 0644
            path: /etc/systemd/system.conf.d/disable_ctrlaltdelete_burstaction.conf
            overwrite: true

#### Rule Disable Ctrl-Alt-Del Reboot Activation [ref]

By default, `SystemD` will reboot the system if the `Ctrl-Alt-Del` key sequence is pressed.
To configure the system to ignore the `Ctrl-Alt-Del` key sequence from the command line instead of rebooting the system, do either of the following:

    ln -sf /dev/null /etc/systemd/system/ctrl-alt-del.target

or

    systemctl mask ctrl-alt-del.target

Do not simply delete the `/usr/lib/systemd/system/ctrl-alt-del.service` file, as this file may be restored during future system updates.

Rationale: | A locally logged-in user who presses Ctrl-Alt-Del, when at the console, can reboot the system. If accidentally pressed, as could happen in the case of mixed OS environment, this can create the risk of short-term loss of availability of systems due to unintentional reboot.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_disable_ctrlaltdel_reboot

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
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
ospp | FAU_GEN.1.2
os-srg | SRG-OS-000324-GPOS-00125, SRG-OS-000480-GPOS-00227
stigref | SV-257785r1044833_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        systemctl disable ctrl-alt-del.target
        systemctl mask ctrl-alt-del.target
    else
        systemctl disable --now ctrl-alt-del.target
        systemctl mask --now ctrl-alt-del.target
    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:
      - DISA-STIG-RHEL-09-211050
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_ctrlaltdel_reboot
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

    - name: Disable Ctrl-Alt-Del Reboot Activation
      ansible.builtin.systemd:
        name: ctrl-alt-del.target
        force: true
        masked: true
        state: stopped
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-211050
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_ctrlaltdel_reboot
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed

Remediation Kubernetes snippet ⇲

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

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: ctrl-alt-del.target
            mask: true

#### Rule Verify that Interactive Boot is Disabled [ref]

Red Hat Enterprise Linux 9 systems support an "interactive boot" option that can be used to prevent services from being started. On a Red Hat Enterprise Linux 9 system, interactive boot can be enabled by providing a `1`, `yes`, `true`, or `on` value to the `systemd.confirm_spawn` kernel argument in `/etc/default/grub`. Remove any instance of

    systemd.confirm_spawn=(1|yes|true|on)

from the kernel arguments in that file to disable interactive boot. Recovery booting must also be disabled. Confirm that `GRUB_DISABLE_RECOVERY=true` is set in `/etc/default/grub`. It is also required to change the runtime configuration, run:

    /sbin/grubby --update-kernel=ALL --remove-args="systemd.confirm_spawn"

    grub2-mkconfig -o /boot/grub2/grub.cfg

Rationale: | Using interactive or recovery boot, the console user could disable auditing, firewalls, or other services, weakening system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_disable_interactive_boot

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.2, 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 | SC-2(1), CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257788r1044838_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q grub2-common; }; then

    # Verify that Interactive Boot is Disabled in /etc/default/grub
    CONFIRM_SPAWN_YES="systemd.confirm_spawn\(=\(1\|yes\|true\|on\)\|\b\)"
    CONFIRM_SPAWN_NO="systemd.confirm_spawn=no"

    if grep -q "\(GRUB_CMDLINE_LINUX\|GRUB_CMDLINE_LINUX_DEFAULT\)" /etc/default/grub
    then
    	sed -i "s/${CONFIRM_SPAWN_YES}/${CONFIRM_SPAWN_NO}/" /etc/default/grub
    fi

    # make sure GRUB_DISABLE_RECOVERY=true
    if grep -q '^GRUB_DISABLE_RECOVERY=.*'  '/etc/default/grub' ; then
           # modify the GRUB command-line if an GRUB_DISABLE_RECOVERY= arg already exists
           sed -i 's/GRUB_DISABLE_RECOVERY=.*/GRUB_DISABLE_RECOVERY=true/' /etc/default/grub
    else
           # no GRUB_DISABLE_RECOVERY=arg is present, append it to file
           echo "GRUB_DISABLE_RECOVERY=true"  >> '/etc/default/grub'
    fi

    # Remove 'systemd.confirm_spawn' kernel argument also from runtime settings
    /sbin/grubby --update-kernel=ALL --remove-args="systemd.confirm_spawn"

    #Regen grub.cfg handle updated GRUB_DISABLE_RECOVERY and confirm_spawn
    grub2-mkconfig -o /boot/grub2/grub.cfg

    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:
      - DISA-STIG-RHEL-09-212015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-2(1)
      - grub2_disable_interactive_boot
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Verify that Interactive Boot is Disabled - Verify GRUB_DISABLE_RECOVERY=true
      ansible.builtin.lineinfile:
        path: /etc/default/grub
        regexp: ^GRUB_DISABLE_RECOVERY=.*
        line: GRUB_DISABLE_RECOVERY=true
        state: present
      register: grub_disable_recovery_changed
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-2(1)
      - grub2_disable_interactive_boot
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Verify that Interactive Boot is Disabled - Verify that Interactive Boot is
        Disabled in /etc/default/grub
      ansible.builtin.replace:
        dest: /etc/default/grub
        regexp: systemd.confirm_spawn(=(1|yes|true|on)|\b)
        replace: systemd.confirm_spawn=no
      register: grub_confirm_spawn_changed
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-2(1)
      - grub2_disable_interactive_boot
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Verify that Interactive Boot is Disabled - Verify that Interactive Boot is
        Disabled (runtime)
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --remove-args="systemd.confirm_spawn"
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - grub_confirm_spawn_changed is changed
      tags:
      - DISA-STIG-RHEL-09-212015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-2(1)
      - grub2_disable_interactive_boot
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Verify that Interactive Boot is Disabled - Regen grub.cfg handle updated GRUB_DISABLE_RECOVERY
        and confirm_spawn
      ansible.builtin.command: grub2-mkconfig -o  /boot/grub2/grub.cfg
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - grub_disable_recovery_changed is changed or grub_confirm_spawn_changed is changed
      tags:
      - DISA-STIG-RHEL-09-212015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.4.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-2(1)
      - grub2_disable_interactive_boot
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

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

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

    [Login]

which contains the configuration

    StopIdleSessionSec=900

.

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { ( grep -qP "^ID=[\"']?rhel[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="8.7"; printf "%s\n%s" "$expected" "$real" | sort -VC; } && grep -qP "^ID=[\"']?rhel[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="9.0"; [[ "$real" != "$expected" ]]; } ) || grep -qP "^ID=[\"']?ol[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="8.7"; printf "%s\n%s" "$expected" "$real" | sort -VC; }; }; then

    var_logind_session_timeout='900'

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

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

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

Remediation Ansible snippet ⇲

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

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

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

#### Rule Require Authentication for Emergency Systemd Target [ref]

Emergency mode is intended as a system recovery method, providing a single user root access to the system during a failed boot sequence. By default, Emergency mode is protected by requiring a password and is set in `/usr/lib/systemd/system/emergency.service`.
Rationale: | This prevents attackers with physical access from trivially bypassing security on the machine and gaining root access. Such accesses are further prevented by configuring the bootloader password.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_require_emergency_target_auth

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.1.1, 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 | IA-2, AC-3, CM-6(a)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.PT-3
os-srg | SRG-OS-000080-GPOS-00048
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
stigref | SV-258128r1117265_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    service_dropin_cfg_dir="/etc/systemd/system/emergency.service.d"
    service_dropin_file="${service_dropin_cfg_dir}/10-oscap.conf"

    sulogin="/usr/lib/systemd/systemd-sulogin-shell emergency"

    mkdir -p "${service_dropin_cfg_dir}"
    echo "[Service]" >> "${service_dropin_file}"
    echo "ExecStart=-$sulogin" >> "${service_dropin_file}"

    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:
      - DISA-STIG-RHEL-09-611195
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_emergency_target_auth
      - restrict_strategy

    - name: Require emergency mode password
      ansible.builtin.blockinfile:
        create: true
        dest: /etc/systemd/system/emergency.service.d/10-oscap.conf
        block: |-
          [Service]
          ExecStart=-/usr/lib/systemd/systemd-sulogin-shell emergency
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611195
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_emergency_target_auth
      - restrict_strategy

#### Rule Require Authentication for Single User Mode [ref]

Single-user mode is intended as a system recovery method, providing a single user root access to the system by providing a boot option at startup. By default, single-user mode is protected by requiring a password and is set in `/usr/lib/systemd/system/rescue.service`.
Rationale: | This prevents attackers with physical access from trivially bypassing security on the machine and gaining root access. Such accesses are further prevented by configuring the bootloader password.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_require_singleuser_auth

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.1.1, 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
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-3, 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
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
stigref | SV-258129r1117265_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/systemd/system/rescue.service.d/10-oscap.conf /etc/systemd/system/rescue.service.d/*.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Service\]([^\n\[]*\n+)+?[[:space:]]*ExecStart" "$f"; then
            if ! grep -qPz "ExecStart=\nExecStart=-/usr/lib/systemd/systemd-sulogin-shell rescue" "$f"; then

                sed -i "s/ExecStart[^(\n)]*/ExecStart=\nExecStart=-\/usr\/lib\/systemd\/systemd-sulogin-shell rescue/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Service\]" "$f"; then

                sed -i "/[[:space:]]*\[Service\]/a ExecStart=\nExecStart=-\/usr\/lib\/systemd\/systemd-sulogin-shell rescue" "$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 "/etc/systemd/system/rescue.service.d/10-oscap.conf /etc/systemd/system/rescue.service.d/*.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Service]\nExecStart=\nExecStart=-/usr/lib/systemd/systemd-sulogin-shell rescue" >> "$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:
      - DISA-STIG-RHEL-09-611200
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_singleuser_auth
      - restrict_strategy

    - name: Require Authentication for Single User Mode - find files which already override
        Execstart of rescue.service
      ansible.builtin.find:
        paths: /etc/systemd/system/rescue.service.d
        patterns: '*.conf'
        contains: ^\s*ExecStart=.*$
      register: rescue_service_overrides_found
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611200
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_singleuser_auth
      - restrict_strategy

    - name: Require Authentication for Single User Mode - set files containing ExecStart
        overrides as target
      ansible.builtin.set_fact:
        rescue_service_remediation_target_file: '{{ rescue_service_overrides_found.files
          | map(attribute=''path'') | list }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - rescue_service_overrides_found.matched is defined and rescue_service_overrides_found.matched
        > 0
      tags:
      - DISA-STIG-RHEL-09-611200
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_singleuser_auth
      - restrict_strategy

    - name: Require Authentication for Single User Mode - set default target for rescue.service
        override
      ansible.builtin.set_fact:
        rescue_service_remediation_target_file:
        - /etc/systemd/system/rescue.service.d/10-oscap.conf
      when:
      - '"kernel-core" in ansible_facts.packages'
      - rescue_service_overrides_found.matched is defined and rescue_service_overrides_found.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-611200
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_singleuser_auth
      - restrict_strategy

    - name: Require Authentication for Single User Mode - Require emergency user mode
        password
      community.general.ini_file:
        path: '{{ item }}'
        section: Service
        option: ExecStart
        values:
        - ''
        - -/usr/lib/systemd/systemd-sulogin-shell rescue
      loop: '{{ rescue_service_remediation_target_file }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611200
      - NIST-800-171-3.1.1
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - require_singleuser_auth
      - restrict_strategy

Group Protect Accounts by Restricting Password-Based Login Group contains 4 groups and 18 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 2 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=35

If a password is currently on the verge of expiration, then `35` 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 `35` 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
pcidss4 | 8.2.6, 8.2
cis | 5.4.1.5
stigref | SV-258049r1015092_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q shadow-utils; }; then

    var_account_disable_post_pw_expiration='35'

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/default/useradd" >> "/etc/default/useradd"
        printf '%s\n' "$formatted_output" >> "/etc/default/useradd"
    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
      - DISA-STIG-RHEL-09-411050
      - 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
      - account_disable_post_pw_expiration
      - 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 35
      tags:
        - always

    - name: Set Account Expiration Following Inactivity
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/default/useradd
        regexp: ^INACTIVE
        line: INACTIVE={{ var_account_disable_post_pw_expiration }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-411050
      - 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
      - account_disable_post_pw_expiration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Assign Expiration Date to Temporary Accounts [ref]

Temporary accounts are established as part of normal account activation procedures when there is a need for short-term accounts. In the event temporary accounts are required, configure the system to terminate them after a documented time period. For every temporary account, run the following command to set an expiration date on it, substituting `USER` and `YYYY-MM-DD` appropriately:

    $ sudo chage -E YYYY-MM-DD USER

`YYYY-MM-DD` indicates the documented expiration date for the account. For U.S. Government systems, the operating system must be configured to automatically terminate these types of accounts after a period of 72 hours.

Rationale: | If temporary user accounts remain active when no longer needed or for an excessive period, these accounts may be used to gain unauthorized access. To mitigate this risk, automated termination of all temporary accounts must be set upon account creation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_account_temp_expire_date

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-2(2), AC-2(3), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6
os-srg | SRG-OS-000123-GPOS-00064, SRG-OS-000002-GPOS-00002
stigref | SV-258047r1101951_rule

Group Set Password Expiration Parameters Group contains 4 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 60

The profile requirement is `60`.

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
ism | 0418, 1055, 1402
pcidss4 | 8.3.9, 8.3
cis | 5.4.1.1
stigref | SV-258041r1038967_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q shadow-utils; }; then

    var_accounts_maximum_age_login_defs='60'

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/login.defs" >> "/etc/login.defs"
        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
      - DISA-STIG-RHEL-09-411010
      - 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 60
      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:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1
      - DISA-STIG-RHEL-09-411010
      - 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
ism | 0418, 1055, 1402
cis | 5.4.1.2
stigref | SV-258104r1015104_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q shadow-utils; }; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/login.defs" >> "/etc/login.defs"
        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.1
      - DISA-STIG-RHEL-09-611075
      - NIST-800-171-3.5.8
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - accounts_minimum_age_login_defs
      - 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: Set Password Minimum Age
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/login.defs
        regexp: ^#?PASS_MIN_DAYS
        line: PASS_MIN_DAYS {{ var_accounts_minimum_age_login_defs }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - DISA-STIG-RHEL-09-611075
      - NIST-800-171-3.5.8
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - accounts_minimum_age_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

    $ sudo chage -M 60
                        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
pcidss4 | 8.3.9, 8.3
cis | 5.4.1.1
stigref | SV-258042r1045133_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_accounts_maximum_age_login_defs='60'

    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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-411015
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.9
      - accounts_password_set_max_life_existing
      - 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 60
      tags:
        - always

    - name: Collect users with not correct maximum time period between password changes
      ansible.builtin.command:
        cmd: awk -F':' '(/^[^:]+:[^!*]/ && ($5 > {{ var_accounts_maximum_age_login_defs
          }} || $5 == "")) {print $1}' /etc/shadow
      register: user_names
      changed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411015
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.9
      - accounts_password_set_max_life_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Change the maximum time period between password changes
      ansible.builtin.user:
        user: '{{ item }}'
        password_expire_max: '{{ var_accounts_maximum_age_login_defs }}'
      with_items: '{{ user_names.stdout_lines }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - user_names.stdout_lines | length > 0
      tags:
      - DISA-STIG-RHEL-09-411015
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(d)
      - NIST-800-53-IA-5(f)
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.9
      - accounts_password_set_max_life_existing
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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
stigref | SV-258105r1045212_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-611080
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611080
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - user_names.stdout_lines | length > 0
      tags:
      - DISA-STIG-RHEL-09-611080
      - 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

Group Verify Proper Storage and Existence of Password Hashes Group contains 6 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 with SHA512 [ref]

Verify the operating system requires the shadow password suite configuration be set to encrypt interactive user passwords using a strong cryptographic hash. Check that the interactive user account passwords are using a strong password hash with the following command:

    $ sudo cut -d: -f2 /etc/shadow
    $6$kcOnRq/5$NUEYPuyL.wghQwWssXRcLRFiiru7f5JPV6GaJhNC2aK5F3PZpE/BCCtwrxRc/AInKMNX3CdMw11m9STiql12f/

Password hashes `!` or `*` indicate inactive accounts not available for logon and are not evaluated. If any interactive user password hash does not begin with `$6`, this is a finding.

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.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_all_shadowed_sha512

References:

nist | IA-5(1)(c), IA-5(1).1(v), IA-7, IA-7.1
os-srg | SRG-OS-000073-GPOS-00041, SRG-OS-000120-GPOS-00061
stigref | SV-258231r1069375_rule

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

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

    password sufficient pam_unix.so ...existing_options... rounds=100000

The system's default number of rounds is 5000.
Warning: Setting a high number of hashing rounds makes it more difficult to brute force the password, but requires more CPU resources to authenticate users.

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

References:

os-srg | SRG-OS-000073-GPOS-00041
anssi | R68
stigref | SV-258099r1045198_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q pam && rpm --quiet -q kernel-core ); then

    var_password_pam_unix_rounds='100000'

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

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

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

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

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

            authselect apply-changes -b
        fi

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611050
      - accounts_password_pam_unix_rounds_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_password_pam_unix_rounds # promote to variable
      set_fact:
        var_password_pam_unix_rounds: !!str 100000
      tags:
        - always

    - name: Set number of Password Hashing Rounds - password-auth - Check if /etc/pam.d/password-auth
        file is present
      ansible.builtin.stat:
        path: /etc/pam.d/password-auth
      register: result_pam_file_present
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-611050
      - accounts_password_pam_unix_rounds_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set number of Password Hashing Rounds - password-auth - Check the proper remediation
        for the system
      block:

      - name: Set number of Password Hashing Rounds - password-auth - Define the PAM file
          to be edited as a local fact
        ansible.builtin.set_fact:
          pam_file_path: /etc/pam.d/password-auth

      - name: Set number of Password Hashing Rounds - password-auth - Check if system
          relies on authselect tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Set number of Password Hashing Rounds - password-auth - Ensure authselect
          custom profile is used if authselect is present
        block:

        - name: Set number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - Define a fact for
          control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - Include or update
          the PAM module line in {{ pam_file_path }}
        block:

        - name: Set number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - 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 number of Password Hashing Rounds - password-auth - Define a fact for
          control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set number of Password Hashing Rounds - password-auth - 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*.*\srounds\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_accounts_password_pam_unix_rounds_password_auth_option_present

      - name: Set number of Password Hashing Rounds - password-auth - Ensure the "rounds"
          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 rounds={{ var_password_pam_unix_rounds }}
          state: present
        register: result_pam_accounts_password_pam_unix_rounds_password_auth_add
        when:
        - result_pam_module_accounts_password_pam_unix_rounds_password_auth_option_present.found
          is defined
        - result_pam_module_accounts_password_pam_unix_rounds_password_auth_option_present.found
          == 0

      - name: Set number of Password Hashing Rounds - password-auth - Ensure the required
          value for "rounds" PAM option from "pam_unix.so" 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\s+.*)(rounds)=[0-9a-zA-Z]*\s*(.*)
          line: \1\2={{ var_password_pam_unix_rounds }} \3
        register: result_pam_accounts_password_pam_unix_rounds_password_auth_edit
        when:
        - result_pam_module_accounts_password_pam_unix_rounds_password_auth_option_present.found
          > 0

      - name: Set number of Password Hashing Rounds - password-auth - Ensure authselect
          changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - |-
          (result_pam_accounts_password_pam_unix_rounds_password_auth_add is defined and result_pam_accounts_password_pam_unix_rounds_password_auth_add.changed)
           or (result_pam_accounts_password_pam_unix_rounds_password_auth_edit is defined and result_pam_accounts_password_pam_unix_rounds_password_auth_edit.changed)
      when:
      - ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - result_pam_file_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611050
      - accounts_password_pam_unix_rounds_password_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

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

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

    password sufficient pam_unix.so ...existing_options... rounds=100000

The system's default number of rounds is 5000.
Warning: Setting a high number of hashing rounds makes it more difficult to brute force the password, but requires more CPU resources to authenticate users.

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

References:

os-srg | SRG-OS-000073-GPOS-00041
anssi | R68
stigref | SV-258100r1045201_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q pam && rpm --quiet -q kernel-core ); then

    var_password_pam_unix_rounds='100000'

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

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

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

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

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

            authselect apply-changes -b
        fi

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

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

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611055
      - accounts_password_pam_unix_rounds_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_password_pam_unix_rounds # promote to variable
      set_fact:
        var_password_pam_unix_rounds: !!str 100000
      tags:
        - always

    - name: Set number of Password Hashing Rounds - system-auth - 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: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-611055
      - accounts_password_pam_unix_rounds_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set number of Password Hashing Rounds - system-auth - Check the proper remediation
        for the system
      block:

      - name: Set number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - Check if system relies
          on authselect tool
        ansible.builtin.stat:
          path: /usr/bin/authselect
        register: result_authselect_present

      - name: Set number of Password Hashing Rounds - system-auth - Ensure authselect
          custom profile is used if authselect is present
        block:

        - name: Set number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - Define a fact for
          control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - Include or update
          the PAM module line in {{ pam_file_path }}
        block:

        - name: Set number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - 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 number of Password Hashing Rounds - system-auth - Define a fact for
          control already filtered in case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Set number of Password Hashing Rounds - system-auth - 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*.*\srounds\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_accounts_password_pam_unix_rounds_system_auth_option_present

      - name: Set number of Password Hashing Rounds - system-auth - Ensure the "rounds"
          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 rounds={{ var_password_pam_unix_rounds }}
          state: present
        register: result_pam_accounts_password_pam_unix_rounds_system_auth_add
        when:
        - result_pam_module_accounts_password_pam_unix_rounds_system_auth_option_present.found
          is defined
        - result_pam_module_accounts_password_pam_unix_rounds_system_auth_option_present.found
          == 0

      - name: Set number of Password Hashing Rounds - system-auth - Ensure the required
          value for "rounds" PAM option from "pam_unix.so" 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\s+.*)(rounds)=[0-9a-zA-Z]*\s*(.*)
          line: \1\2={{ var_password_pam_unix_rounds }} \3
        register: result_pam_accounts_password_pam_unix_rounds_system_auth_edit
        when:
        - result_pam_module_accounts_password_pam_unix_rounds_system_auth_option_present.found
          > 0

      - name: Set number of Password Hashing Rounds - system-auth - Ensure authselect
          changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_present.stat.exists
        - |-
          (result_pam_accounts_password_pam_unix_rounds_system_auth_add is defined and result_pam_accounts_password_pam_unix_rounds_system_auth_add.changed)
           or (result_pam_accounts_password_pam_unix_rounds_system_auth_edit is defined and result_pam_accounts_password_pam_unix_rounds_system_auth_edit.changed)
      when:
      - ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - result_pam_file_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611055
      - accounts_password_pam_unix_rounds_system_auth
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

#### 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
pcidss4 | 8.2.2, 8.2
bsi | SYS.1.3.A2
cis | 7.2.3
stigref | SV-258048r1069380_rule

#### 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/system-auth` and `/etc/pam.d/password-auth` to prevent logins with empty passwords.
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. 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

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2
cobit5 | APO01.06, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.10
cui | 3.1.1, 3.1.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.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
nist | IA-5(1)(a), IA-5(c), CM-6(a)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5
ospp | FIA_UAU.1
pcidss | Req-8.2.3
os-srg | SRG-OS-000480-GPOS-00227
ism | 1546
pcidss4 | 8.3.1, 8.3
cis | 5.3.3.4.1
stigref | SV-258094r1045187_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if [ -f /usr/bin/authselect ]; then
        if ! authselect check; then
    echo "
    authselect integrity check failed. Remediation aborted!
    This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
    It is not recommended to manually edit the PAM files when authselect tool is available.
    In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
    exit 1
    fi
    authselect enable-feature without-nullok

    authselect apply-changes -b
    else

    if grep -qP "^\s*auth\s+sufficient\s+pam_unix.so\s.*\bnullok\b" "/etc/pam.d/system-auth"; then
        sed -i -E --follow-symlinks "s/(.*auth.*sufficient.*pam_unix.so.*)\bnullok\b=?[[:alnum:]]*(.*)/\1\2/g" "/etc/pam.d/system-auth"
    fi

    if grep -qP "^\s*password\s+sufficient\s+pam_unix.so\s.*\bnullok\b" "/etc/pam.d/system-auth"; then
        sed -i -E --follow-symlinks "s/(.*password.*sufficient.*pam_unix.so.*)\bnullok\b=?[[:alnum:]]*(.*)/\1\2/g" "/etc/pam.d/system-auth"
    fi

    if grep -qP "^\s*auth\s+sufficient\s+pam_unix.so\s.*\bnullok\b" "/etc/pam.d/password-auth"; then
        sed -i -E --follow-symlinks "s/(.*auth.*sufficient.*pam_unix.so.*)\bnullok\b=?[[:alnum:]]*(.*)/\1\2/g" "/etc/pam.d/password-auth"
    fi

    if grep -qP "^\s*password\s+sufficient\s+pam_unix.so\s.*\bnullok\b" "/etc/pam.d/password-auth"; then
        sed -i -E --follow-symlinks "s/(.*password.*sufficient.*pam_unix.so.*)\bnullok\b=?[[:alnum:]]*(.*)/\1\2/g" "/etc/pam.d/password-auth"
    fi
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-611025
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - configure_strategy
      - high_severity
      - low_complexity
      - medium_disruption
      - no_empty_passwords
      - no_reboot_needed

    - name: Prevent Login to Accounts With Empty Password - Check if system relies on
        authselect
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-611025
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - configure_strategy
      - high_severity
      - low_complexity
      - medium_disruption
      - no_empty_passwords
      - no_reboot_needed

    - name: Prevent Login to Accounts With Empty Password - Remediate using authselect
      block:

      - name: Prevent Login to Accounts With Empty Password - 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: Prevent Login to Accounts With Empty Password - 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: Prevent Login to Accounts With Empty Password - Get authselect current features
        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_check_cmd is success

      - name: Prevent Login to Accounts With Empty Password - Ensure "without-nullok"
          feature is enabled using authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature without-nullok
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("without-nullok")

      - name: Prevent Login to Accounts With Empty Password - Ensure authselect changes
          are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-611025
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - configure_strategy
      - high_severity
      - low_complexity
      - medium_disruption
      - no_empty_passwords
      - no_reboot_needed

    - name: Prevent Login to Accounts With Empty Password - Remediate directly editing
        PAM files
      ansible.builtin.replace:
        dest: '{{ item }}'
        regexp: nullok
      loop:
      - /etc/pam.d/system-auth
      - /etc/pam.d/password-auth
      when:
      - '"kernel-core" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - CJIS-5.5.2
      - DISA-STIG-RHEL-09-611025
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.1
      - configure_strategy
      - high_severity
      - low_complexity
      - medium_disruption
      - no_empty_passwords
      - no_reboot_needed

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,%23%20Generated%20by%20authselect%20on%20Sat%20Oct%2027%2014%3A59%3A36%202018%0A%23%20Do%20not%20modify%20this%20file%20manually.%0A%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_env.so%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_faildelay.so%20delay%3D2000000%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_fprintd.so%0Aauth%20%20%20%20%20%20%20%20%5Bdefault%3D1%20ignore%3Dignore%20success%3Dok%5D%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3E%3D%201000%20quiet%0Aauth%20%20%20%20%20%20%20%20%5Bdefault%3D1%20ignore%3Dignore%20success%3Dok%5D%20%20%20%20%20%20%20%20%20pam_localuser.so%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%20try_first_pass%0Aauth%20%20%20%20%20%20%20%20requisite%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3E%3D%201000%20quiet_success%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%20forward_pass%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_deny.so%0A%0Aaccount%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%0Aaccount%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_localuser.so%0Aaccount%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3C%201000%20quiet%0Aaccount%20%20%20%20%20%5Bdefault%3Dbad%20success%3Dok%20user_unknown%3Dignore%5D%20pam_sss.so%0Aaccount%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_permit.so%0A%0Apassword%20%20%20%20requisite%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_pwquality.so%20try_first_pass%20local_users_only%0Apassword%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%20sha512%20shadow%20try_first_pass%20use_authtok%0Apassword%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%20use_authtok%0Apassword%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_deny.so%0A%0Asession%20%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_keyinit.so%20revoke%0Asession%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_limits.so%0A-session%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_systemd.so%0Asession%20%20%20%20%20%5Bsuccess%3D1%20default%3Dignore%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20service%20in%20crond%20quiet%20use_uid%0Asession%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%0Asession%20%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%0A
            mode: 0644
            path: /etc/pam.d/password-auth
            overwrite: true
          - contents:
              source: data:,%23%20Generated%20by%20authselect%20on%20Sat%20Oct%2027%2014%3A59%3A36%202018%0A%23%20Do%20not%20modify%20this%20file%20manually.%0A%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_env.so%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_faildelay.so%20delay%3D2000000%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_fprintd.so%0Aauth%20%20%20%20%20%20%20%20%5Bdefault%3D1%20ignore%3Dignore%20success%3Dok%5D%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3E%3D%201000%20quiet%0Aauth%20%20%20%20%20%20%20%20%5Bdefault%3D1%20ignore%3Dignore%20success%3Dok%5D%20%20%20%20%20%20%20%20%20pam_localuser.so%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%20try_first_pass%0Aauth%20%20%20%20%20%20%20%20requisite%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3E%3D%201000%20quiet_success%0Aauth%20%20%20%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%20forward_pass%0Aauth%20%20%20%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_deny.so%0A%0Aaccount%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%0Aaccount%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_localuser.so%0Aaccount%20%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20uid%20%3C%201000%20quiet%0Aaccount%20%20%20%20%20%5Bdefault%3Dbad%20success%3Dok%20user_unknown%3Dignore%5D%20pam_sss.so%0Aaccount%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_permit.so%0A%0Apassword%20%20%20%20requisite%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_pwquality.so%20try_first_pass%20local_users_only%0Apassword%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%20sha512%20shadow%20try_first_pass%20use_authtok%0Apassword%20%20%20%20sufficient%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%20use_authtok%0Apassword%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_deny.so%0A%0Asession%20%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_keyinit.so%20revoke%0Asession%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_limits.so%0A-session%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_systemd.so%0Asession%20%20%20%20%20%5Bsuccess%3D1%20default%3Dignore%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_succeed_if.so%20service%20in%20crond%20quiet%20use_uid%0Asession%20%20%20%20%20required%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_unix.so%0Asession%20%20%20%20%20optional%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pam_sss.so%0A
            mode: 0644
            path: /etc/pam.d/system-auth
            overwrite: true

#### 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
pcidss4 | 2.2.2, 2.2
cis | 7.2.2
stigref | SV-258120r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-611155
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611155
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - users_nopasswd is not skipped and users_nopasswd.stdout_lines | length > 0
      tags:
      - DISA-STIG-RHEL-09-611155
      - 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

Group Restrict Root Logins Group contains 3 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
ism | 1546
pcidss4 | 8.2.1, 8.2
cis | 5.4.2.1
stigref | SV-258059r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-411100
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411100
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - item.value.1  == '0'
      tags:
      - DISA-STIG-RHEL-09-411100
      - 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 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
ism | 1491
pcidss4 | 8.2.2, 8.2
cis | 5.4.2.7
stigref | SV-258046r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-411035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411035
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-411035
      - 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 for su authentication [ref]

To ensure that only users who are members of the `wheel` group 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

Warning: Members of "wheel" or GID 0 groups are checked by default if the group option is not set for pam_wheel.so module. Therefore, members of these groups should be manually checked or a different group should be informed according to the site policy.

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_for_su

References:

ospp | FMT_SMF_EXT.1.1
os-srg | SRG-OS-000373-GPOS-00156, SRG-OS-000312-GPOS-00123
stigref | SV-258088r1050789_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q pam; then

    # uncomment the option if commented
    sed '/^[[:space:]]*#[[:space:]]*auth[[:space:]]\+required[[:space:]]\+pam_wheel\.so[[:space:]]\+use_uid$/s/^[[:space:]]*#//' -i /etc/pam.d/su

    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:
      - DISA-STIG-RHEL-09-432035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - use_pam_wheel_for_su

    - name: Restrict usage of su command only to members of wheel group
      ansible.builtin.replace:
        path: /etc/pam.d/su
        regexp: ^[\s]*#[\s]*auth[\s]+required[\s]+pam_wheel\.so[\s]+use_uid$
        replace: auth             required        pam_wheel.so use_uid
      when: '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-432035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - use_pam_wheel_for_su

#### 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
pcidss4 | 8.2.1, 8.2
bsi | SYS.1.3.A2
cis | 7.2.4
stigref | SV-258045r958482_rule

#### Rule Only Authorized Local User Accounts Exist on Operating System [ref]

Enterprise Application tends to use the server or virtual machine exclusively. Besides the default operating system user, there should be only authorized local users required by the installed software groups and applications that exist on the operating system. The authorized user list can be customized in the refine value variable `var_accounts_authorized_local_users_regex`. OVAL regular expression is used for the user list. Configure the system so all accounts on the system are assigned to an active system, application, or user account. Remove accounts that do not support approved system activities or that allow for a normal user to perform administrative-level actions. To remove unauthorized system accounts, use the following command:

    $ sudo userdel unauthorized_user

Warning: Automatic remediation of this control is not available due to the unique requirements of each system.

Rationale: | Accounts providing no operational purpose provide additional opportunities for system compromise. Unnecessary accounts include user accounts for individuals not requiring access to the system and application accounts for applications not installed on the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_authorized_local_users

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258058r1045148_rule

#### 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
pcidss4 | 8.2.1, 8.2
bsi | SYS.1.3.A2
cis | 7.2.5
stigref | SV-258061r958482_rule

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

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

Group Ensure that Users Have Sensible Umask Values Group contains 5 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/bashrc` to read as follows:

    umask 077

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q bash; }; then

    var_accounts_user_umask='077'

    grep -q "^[^#]*\bumask" /etc/bashrc && \
      sed -i -E -e "s/^([^#]*\bumask)[[:space:]]+[[:digit:]]+/\1 $var_accounts_user_umask/g" /etc/bashrc
    if ! [ $? -eq 0 ]; then
        echo "umask $var_accounts_user_umask" >> /etc/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:
      - DISA-STIG-RHEL-09-412055
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_bashrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Check if umask in /etc/bashrc is already set
      ansible.builtin.lineinfile:
        path: /etc/bashrc
        regexp: ^[^#]*\bumask\s+\d+$
        state: absent
      check_mode: true
      changed_when: false
      register: umask_replace
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412055
      - 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/bashrc
      ansible.builtin.replace:
        path: /etc/bashrc
        regexp: ^([^#]*\b)umask\s+\d+$
        replace: \g<1>umask {{ var_accounts_user_umask }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      - umask_replace.found > 0
      tags:
      - DISA-STIG-RHEL-09-412055
      - 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/bashrc
        line: umask {{ var_accounts_user_umask }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      - umask_replace.found == 0
      tags:
      - DISA-STIG-RHEL-09-412055
      - 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 C Shell Umask is Set Correctly [ref]

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

    umask 077

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

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
stigref | SV-258073r1045157_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_accounts_user_umask='077'

    grep -q "^\s*umask" /etc/csh.cshrc && \
      sed -i -E -e "s/^(\s*umask).*/\1 $var_accounts_user_umask/g" /etc/csh.cshrc
    if ! [ $? -eq 0 ]; then
        echo "umask $var_accounts_user_umask" >> /etc/csh.cshrc
    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:
      - DISA-STIG-RHEL-09-412060
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_csh_cshrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Check if umask in /etc/csh.cshrc is already set
      ansible.builtin.lineinfile:
        path: /etc/csh.cshrc
        regexp: ^(\s*)umask\s+.*
        state: absent
      check_mode: true
      changed_when: false
      register: umask_replace
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412060
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_csh_cshrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Replace user umask in /etc/csh.cshrc
      ansible.builtin.replace:
        path: /etc/csh.cshrc
        regexp: ^(\s*)umask(\s+).*
        replace: \g<1>umask\g<2>{{ var_accounts_user_umask }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - umask_replace.found > 0
      tags:
      - DISA-STIG-RHEL-09-412060
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_csh_cshrc
      - 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/csh.cshrc
        line: umask {{ var_accounts_user_umask }}
      when:
      - '"kernel-core" in ansible_facts.packages'
      - umask_replace.found == 0
      tags:
      - DISA-STIG-RHEL-09-412060
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_csh_cshrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

    UMASK 077

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q shadow-utils; }; then

    var_accounts_user_umask='077'

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

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^UMASK\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^UMASK\\>.*/$escaped_formatted_output/gi" "/etc/login.defs"
    else
        if [[ -s "/etc/login.defs" ]] && [[ -n "$(tail -c 1 -- "/etc/login.defs" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/login.defs"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/login.defs" >> "/etc/login.defs"
        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:
      - DISA-STIG-RHEL-09-412065
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Check if UMASK is already set
      ansible.builtin.lineinfile:
        path: /etc/login.defs
        regexp: ^(\s*)UMASK\s+.*
        state: absent
      check_mode: true
      changed_when: false
      register: result_umask_is_set
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412065
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      - result_umask_is_set.found > 0
      tags:
      - DISA-STIG-RHEL-09-412065
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"shadow-utils" in ansible_facts.packages'
      - result_umask_is_set.found == 0
      tags:
      - DISA-STIG-RHEL-09-412065
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

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

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

    umask 077

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

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

References:

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

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_accounts_user_umask='077'

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

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

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

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

Remediation Ansible snippet ⇲

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

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

    - name: Ensure the Default Umask is Set Correctly in /etc/profile - Locate Profile
        Configuration Files Where umask Is Defined
      ansible.builtin.find:
        paths:
        - /etc/profile.d
        patterns:
        - sh.local
        - '*.sh'
        contains: ^[\s]*umask\s+\d+
      register: result_profile_d_files
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412070
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - result_profile_d_files.matched
      tags:
      - DISA-STIG-RHEL-09-412070
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - not result_profile_d_files.matched
      tags:
      - DISA-STIG-RHEL-09-412070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412070
      - 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 Default Umask is Set Correctly For Interactive Users [ref]

Remove the `UMASK` environment variable from all interactive users initialization files.

Rationale:

The umask controls the default access mode assigned to newly created files. A umask of 077 limits new files to mode 700 or less permissive. Although umask can be represented as a four-digit number, the first digit representing special access modes is typically ignored or required to be 0. This requirement applies to the globally configured system defaults and the local interactive user defaults for each account on the system.

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

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000480-GPOS-00228
stigref | SV-258044r1045135_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    while IFS= read -r dir; do
        while IFS= read -r -d '' file; do
            if [ "$(basename $file)" != ".bash_history" ]; then
                sed -i 's/^\(\s*umask\s*\)/#\1/g' "$file"
            fi
        done <   <(find $dir -maxdepth 1 -type f -name ".*" -print0)
    done <   <(awk -F':' '{ if ($3 >= 1000 && $3 != 65534) print $6}' /etc/passwd)

    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:
      - DISA-STIG-RHEL-09-411025
      - accounts_umask_interactive_users
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly For Interactive Users - Get interactive
        users from passwd file
      ansible.builtin.getent:
        database: passwd
      register: passwd_entries
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411025
      - accounts_umask_interactive_users
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly For Interactive Users - Filter interactive
        users and get home directories
      ansible.builtin.set_fact:
        interactive_user_homes: '{{ interactive_user_homes | default([]) + [item.value[4]]
          }}'
      loop: '{{ passwd_entries.ansible_facts.getent_passwd | dict2items }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.value[2] | int >= 1000 | int
      - item.value[2] | int != 65534 | int
      - item.value[4] != ""
      tags:
      - DISA-STIG-RHEL-09-411025
      - accounts_umask_interactive_users
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly For Interactive Users - Find dot
        files in interactive user home directories
      ansible.builtin.find:
        paths: '{{ item }}'
        patterns: .*
        file_type: file
        hidden: true
        depth: 1
      register: user_dotfiles
      with_items: '{{ interactive_user_homes | default([]) }}'
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item != ""
      tags:
      - DISA-STIG-RHEL-09-411025
      - accounts_umask_interactive_users
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly For Interactive Users - Comment
        out umask statements in user initialization files
      ansible.builtin.replace:
        path: '{{ item.1.path }}'
        regexp: ^\s*umask\s+
        replace: '#\g<0>'
        backup: false
      with_subelements:
      - '{{ user_dotfiles.results }}'
      - files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.0 is not skipped
      - item.1.path is defined
      - '''.bash_history'' not in item.1.path'
      tags:
      - DISA-STIG-RHEL-09-411025
      - accounts_umask_interactive_users
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure Home Directories are Created for New Users [ref]

All local interactive user accounts, upon creation, should be assigned a home directory.
Configure the operating system to assign home directories to all new local interactive users by setting the `CREATE_HOME` parameter in `/etc/login.defs` to `yes` as follows:

    CREATE_HOME yes

Rationale: | If local interactive users are not assigned a valid home directory, there is no place for the storage and control of files they should own.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_have_homedir_login_defs

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258043r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q shadow-utils && rpm --quiet -q kernel-core ); then

    if [ -e "/etc/login.defs" ] ; then

        LC_ALL=C sed -i "/^\s*CREATE_HOME\s\+/Id" "/etc/login.defs"
    else
        touch "/etc/login.defs"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/login.defs"

    cp "/etc/login.defs" "/etc/login.defs.bak"
    # Insert before the line matching the regex '^\s*CREATE_HOME'.
    line_number="$(LC_ALL=C grep -n "^\s*CREATE_HOME" "/etc/login.defs.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^\s*CREATE_HOME', insert at
        # the end of the file.
        printf '%s\n' "CREATE_HOME yes" >> "/etc/login.defs"
    else
        head -n "$(( line_number - 1 ))" "/etc/login.defs.bak" > "/etc/login.defs"
        printf '%s\n' "CREATE_HOME yes" >> "/etc/login.defs"
        tail -n "+$(( line_number ))" "/etc/login.defs.bak" >> "/etc/login.defs"
    fi
    # Clean up after ourselves.
    rm "/etc/login.defs.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:
      - DISA-STIG-RHEL-09-411020
      - accounts_have_homedir_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure new users receive home directories
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/login.defs
          create: true
          regexp: (?i)^\s*CREATE_HOME\s+
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/login.defs
        ansible.builtin.lineinfile:
          path: /etc/login.defs
          create: true
          regexp: (?i)^\s*CREATE_HOME\s+
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/login.defs
        ansible.builtin.lineinfile:
          path: /etc/login.defs
          create: true
          regexp: (?i)^\s*CREATE_HOME\s+
          line: CREATE_HOME yes
          state: present
      when: ( "shadow-utils" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-411020
      - accounts_have_homedir_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure the Logon Failure Delay is Set Correctly in login.defs [ref]

To ensure the logon failure delay controlled by `/etc/login.defs` is set properly, add or correct the `FAIL_DELAY` setting in `/etc/login.defs` to read as follows:

    FAIL_DELAY 4

Rationale: | Increasing the time between a failed authentication attempt and re-prompting to enter credentials helps to slow a single-threaded brute force attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_logon_fail_delay

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 | AC-7(b), CM-6(a)
nist-csf | PR.IP-1
os-srg | SRG-OS-000480-GPOS-00226
stigref | SV-258071r991588_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q shadow-utils && rpm --quiet -q kernel-core ); then

    var_accounts_fail_delay='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' <<< "^FAIL_DELAY")

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

    # 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 "^FAIL_DELAY\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^FAIL_DELAY\\>.*/$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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/login.defs" >> "/etc/login.defs"
        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: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-412050
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - accounts_logon_fail_delay
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_accounts_fail_delay # promote to variable
      set_fact:
        var_accounts_fail_delay: !!str 4
      tags:
        - always

    - name: Set accounts logon fail delay
      ansible.builtin.lineinfile:
        dest: /etc/login.defs
        regexp: ^FAIL_DELAY
        line: FAIL_DELAY {{ var_accounts_fail_delay }}
        create: true
      when: ( "shadow-utils" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-412050
      - NIST-800-53-AC-7(b)
      - NIST-800-53-CM-6(a)
      - accounts_logon_fail_delay
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Limit the Number of Concurrent Login Sessions Allowed Per User [ref]

Limiting the number of allowed users and sessions per user can limit risks related to Denial of Service attacks. This addresses concurrent sessions for a single account and does not address concurrent sessions by a single user via multiple accounts. To set the number of concurrent sessions per user add the following line in `/etc/security/limits.conf` or a file under `/etc/security/limits.d/`:

    * hard maxlogins 10

Rationale: | Limiting simultaneous user logins can insulate the system from denial of service problems caused by excessive logins. Automated login processes operating improperly or maliciously may result in an exceptional number of simultaneous login sessions.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_max_concurrent_login_sessions

References:

cis-csc | 14, 15, 18, 9
cjis | 5.5.2.2
cobit5 | DSS01.05, DSS05.02
isa-62443-2009 | 4.3.3.4
isa-62443-2013 | SR 3.1, SR 3.8
iso27001-2013 | A.13.1.1, A.13.1.3, A.13.2.1, A.14.1.2, A.14.1.3
nerc-cip | CIP-007-3 R5.1, CIP-007-3 R5.1.2
nist | AC-10, CM-6(a)
nist-csf | PR.AC-5
os-srg | SRG-OS-000027-GPOS-00008
stigref | SV-258069r958398_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q pam && rpm --quiet -q kernel-core ); then

    var_accounts_max_concurrent_login_sessions='10'

    if grep -q '^[^#]*\<maxlogins\>' /etc/security/limits.d/*.conf; then
    	sed -i "/^[^#]*\<maxlogins\>/ s/maxlogins.*/maxlogins $var_accounts_max_concurrent_login_sessions/" /etc/security/limits.d/*.conf
    elif grep -q '^[^#]*\<maxlogins\>' /etc/security/limits.conf; then
    	sed -i "/^[^#]*\<maxlogins\>/ s/maxlogins.*/maxlogins $var_accounts_max_concurrent_login_sessions/" /etc/security/limits.conf
    else
    	echo "*	hard	maxlogins	$var_accounts_max_concurrent_login_sessions" >> /etc/security/limits.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.5.2.2
      - DISA-STIG-RHEL-09-412040
      - NIST-800-53-AC-10
      - NIST-800-53-CM-6(a)
      - accounts_max_concurrent_login_sessions
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_max_concurrent_login_sessions # promote to variable
      set_fact:
        var_accounts_max_concurrent_login_sessions: !!str 10
      tags:
        - always

    - name: Find /etc/security/limits.d files containing maxlogins configuration
      ansible.builtin.find:
        paths: /etc/security/limits.d
        contains: ^[\s]*\*[\s]+(?:(?:hard)|(?:-))[\s]+maxlogins
        patterns: '*.conf'
      register: maxlogins
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-412040
      - NIST-800-53-AC-10
      - NIST-800-53-CM-6(a)
      - accounts_max_concurrent_login_sessions
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Limit the Number of Concurrent Login Sessions Allowed Per User in files from
        limits.d
      ansible.builtin.replace:
        dest: '{{ item.path }}'
        regexp: ^#?\*.*maxlogins.*
        replace: '*          hard    maxlogins     {{ var_accounts_max_concurrent_login_sessions
          }}'
      with_items:
      - '{{ maxlogins.files }}'
      when: ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-412040
      - NIST-800-53-AC-10
      - NIST-800-53-CM-6(a)
      - accounts_max_concurrent_login_sessions
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Limit the Number of Concurrent Login Sessions Allowed Per User
      ansible.builtin.lineinfile:
        state: present
        dest: /etc/security/limits.conf
        insertbefore: ^# End of file
        regexp: ^#?\*.*maxlogins
        line: '*          hard    maxlogins     {{ var_accounts_max_concurrent_login_sessions
          }}'
        create: true
      when:
      - ( "pam" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - maxlogins.matched == 0
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-412040
      - NIST-800-53-AC-10
      - NIST-800-53-CM-6(a)
      - accounts_max_concurrent_login_sessions
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

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

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

    typeset -xr TMOUT=600

or

    declare -xr TMOUT=600

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

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

References:

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

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_accounts_tmout='600'

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

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

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

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

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

Remediation Ansible snippet ⇲

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

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

    - name: Correct any occurrence of TMOUT in /etc/profile
      ansible.builtin.replace:
        path: /etc/profile
        regexp: ^[^#].*TMOUT=.*
        replace: typeset -xr TMOUT={{ var_accounts_tmout }}
      register: profile_replaced
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-412035
      - 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 Not Run World-Writable Programs [ref]

Set the mode on files being executed by the user initialization files with the following command:

    $ sudo chmod o-w FILE

Rationale: | If user start-up files execute world-writable programs, especially in unprotected directories, they could be maliciously modified to destroy user files or otherwise compromise the system at the user level. If the system is compromised at the user level, it is easier to elevate privileges to eventually compromise the system at the root and network level.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_user_dot_no_world_writable_programs

References:

os-srg | SRG-OS-000480-GPOS-00227
cis | 7.2.9
stigref | SV-258062r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    readarray -t world_writable_files < <(find / -xdev -type f -perm -0002 2> /dev/null)
    readarray -t interactive_home_dirs < <(awk -F':' '{ if ($3 >= 1000 && $3 != 65534) print $6 }' /etc/passwd)

    for world_writable in "${world_writable_files[@]}"; do
        for homedir in "${interactive_home_dirs[@]}"; do
            if grep -q -d skip "$world_writable" "$homedir"/.*; then
                chmod o-w $world_writable
                break
            fi
        done
    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:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Initialize
        variables
      ansible.builtin.set_fact:
        home_user_dirs: []
        world_writable_files: []
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Get user's
        home dir list
      ansible.builtin.getent:
        database: passwd
      register: passwd_database
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Fill home_user_dirs
      ansible.builtin.set_fact:
        home_user_dirs: '{{ home_user_dirs + [item.data[4]] }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.data[4] is defined and item.data[2]|int >= 1000 and item.data[2]|int != 65534
      with_items: '{{ passwd_database.ansible_facts.getent_passwd | dict2items(key_name=''user'',
        value_name=''data'')}}'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Get world
        writable files
      ansible.builtin.shell: |
        find / -xdev -type f -perm -0002 2> /dev/null
      register: world_writable_files
      changed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Find referenced_files
        in init files
      ansible.builtin.find:
        paths: '{{ home_user_dirs }}'
        contains: '{{ item }}'
        hidden: true
        read_whole_file: true
        recurse: true
      with_items: '{{ world_writable_files.stdout_lines }}'
      register: referenced_files
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Not Run World-Writable Programs - Remove world
        writable permissions
      ansible.builtin.file:
        path: '{{ item.item }}'
        mode: o-w
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.matched > 0
      with_items: '{{ referenced_files.results }}'
      tags:
      - DISA-STIG-RHEL-09-411115
      - accounts_user_dot_no_world_writable_programs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure that Users Path Contains Only Local Directories [ref]

Ensure that all interactive user initialization files executable search path statements do not contain statements that will reference a working directory other than the users home directory.

Rationale:

The executable search path (typically the PATH environment variable) contains a list of directories for the shell to search to find executables. If this path includes the current working directory (other than the users home directory), executables in these directories may be executed instead of system commands. This variable is formatted as a colon-separated list of directories. If there is an empty entry, such as a leading or trailing colon or two consecutive colons, this is interpreted as the current working directory. If deviations from the default system search path for the local interactive user are required, they must be documented with the Information System Security Officer (ISSO).

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

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258050r1045137_rule

#### Rule All Interactive Users Must Have A Home Directory Defined [ref]

Assign home directories to all interactive users that currently do not have a home directory assigned. This rule checks if the home directory is properly defined in a folder which has at least one parent folder, like "user" in "/home/user" or "/remote/users/user". Therefore, this rule will report a finding for home directories like `/users`, `/tmp` or `/`.
Rationale: | If local interactive users are not assigned a valid home directory, there is no place for the storage and control of files they should own.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_user_interactive_home_directory_defined

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258051r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    for user in $(awk -F':' '{ if ($3 >= 1000 && $3 != 65534) print $1 }' /etc/passwd); do
        # This follows the same logic of evaluation of home directories as used in OVAL.
        if ! grep -q $user /etc/passwd | cut -d: -f6 | grep '^\/\w*\/\w\{1,\}'; then
            sed -i "s/\($user:x:[0-9]*:[0-9]*:.*:\).*\(:.*\)$/\1\/home\/$user\2/g" /etc/passwd;
        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:
      - DISA-STIG-RHEL-09-411060
      - accounts_user_interactive_home_directory_defined
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411060
      - accounts_user_interactive_home_directory_defined
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411060
      - accounts_user_interactive_home_directory_defined
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure interactive users have an exclusive home directory defined
      ansible.builtin.user:
        name: '{{ item.key }}'
        home: /home/{{ item.key }}
        create_home: false
      loop: '{{ local_users }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - item.value[2]|int >= 1000
      - item.value[2]|int != 65534
      - item.value[2]|int < 61184 or item.value[2]|int > 65519
      - not item.value[4] | regex_search('^\/\w*\/\w{1,}')
      tags:
      - DISA-STIG-RHEL-09-411060
      - accounts_user_interactive_home_directory_defined
      - 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.8
stigref | SV-258052r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-411065
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411065
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-411065
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      tags:
      - DISA-STIG-RHEL-09-411065
      - 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
bsi | SYS.1.3.A14
stigref | SV-258053r991589_rule

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:
      - DISA-STIG-RHEL-09-411070
      - 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:
      - DISA-STIG-RHEL-09-411070
      - 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:
      - DISA-STIG-RHEL-09-411070
      - 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:
      - DISA-STIG-RHEL-09-411070
      - file_groupownership_home_directories
      - 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, including the `root` user, to `0740` with the following commands:

    $ sudo chmod 0740 /root/.INIT_FILE
    $ 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_root

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257889r1044959_rule

Remediation Shell script ⇲

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

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

    readarray -t interactive_users < <(awk -F: '$3==0 || $3>=1000   {print $1}' /etc/passwd)
    readarray -t interactive_users_home < <(awk -F: '$3==0 || $3>=1000   {print $6}' /etc/passwd)
    readarray -t interactive_users_shell < <(awk -F: '$3==0 || $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:
      - DISA-STIG-RHEL-09-232045
      - file_permission_user_init_files_root
      - 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 or item.key == "root"
      register: found_init_files
      tags:
      - DISA-STIG-RHEL-09-232045
      - file_permission_user_init_files_root
      - 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:
      - DISA-STIG-RHEL-09-232045
      - file_permission_user_init_files_root
      - 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
bsi | SYS.1.3.A14
cis | 7.2.8
stigref | SV-257890r1044961_rule

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:
      - DISA-STIG-RHEL-09-232050
      - 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:
      - DISA-STIG-RHEL-09-232050
      - 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:
      - DISA-STIG-RHEL-09-232050
      - 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:
      - DISA-STIG-RHEL-09-232050
      - file_permissions_home_directories
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Enable authselect [ref]

Configure user authentication setup to use the `authselect` tool. If authselect profile is selected, the rule will enable the sssd profile.
Warning: If the `sudo authselect select` command returns an error informing that the chosen profile cannot be selected, it is probably because PAM files have already been modified by the administrator. If this is the case, in order to not overwrite the desired changes made by the administrator, the current PAM settings should be investigated before forcing the selection of the chosen authselect profile.

Rationale: | Authselect is a successor to authconfig. It is a tool to select system authentication and identity sources from a list of supported profiles instead of letting the administrator manually build the PAM stack. That way, it avoids potential breakage of configuration, as it ships several tested profiles that are well tested and supported to solve different use-cases.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_enable_authselect

References:

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)
nist | AC-3
ospp | FIA_UAU.1, FIA_AFL.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R31
ism | 1409
pcidss4 | 8.3.4, 8.3
ccn | enable_authselect
cis | enable_authselect
stigid | needed_rules

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_authselect_profile='sssd'

    authselect current

    if test "$?" -ne 0; then
        if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; }; then
            authselect select --force "$var_authselect_profile"
        else
            authselect select "$var_authselect_profile"
        fi

        if test "$?" -ne 0; then
            if rpm --quiet --verify pam; then
                authselect select --force "$var_authselect_profile"
            else
    	        echo "authselect is not used but files from the 'pam' package have been altered, so the authselect configuration won't be forced." >&2
            fi
        fi
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_authselect_profile # promote to variable
      set_fact:
        var_authselect_profile: !!str sssd
      tags:
        - always

    - name: Enable authselect - Check Current authselect Profile
      ansible.builtin.command:
        cmd: authselect current
      register: result_authselect_current
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable authselect - Try to Select an authselect Profile
      ansible.builtin.command:
        cmd: authselect select "{{ var_authselect_profile }}"
      register: result_authselect_select
      changed_when: result_authselect_select.rc == 0
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_current.rc != 0
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable authselect - Verify If pam Has Been Altered
      ansible.builtin.command:
        cmd: rpm -qV pam
      register: result_altered_authselect
      changed_when: false
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_select is not skipped
      - result_authselect_select.rc != 0
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable authselect - Informative Message Based on authselect Integrity Check
      ansible.builtin.assert:
        that:
        - result_authselect_current.rc == 0 or result_altered_authselect is skipped or
          result_altered_authselect.rc == 0
        fail_msg:
        - authselect is not used but files from the 'pam' package have been altered, so
          the authselect configuration won't be forced.
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable authselect - Force authselect Profile Selection
      ansible.builtin.command:
        cmd: authselect select --force "{{ var_authselect_profile }}"
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_authselect_current.rc != 0
      - result_authselect_select.rc != 0
      - result_altered_authselect.rc == 0
      tags:
      - DISA-STIG-needed_rules
      - NIST-800-53-AC-3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.4
      - configure_strategy
      - enable_authselect
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

Group GRUB2 bootloader configuration Group contains 1 group and 7 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 Red Hat Enterprise Linux 9 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 4 rules
[ref] Non-UEFI GRUB2 bootloader configuration

#### Rule Verify /boot/grub2/grub.cfg Group Ownership [ref]

The file `/boot/grub2/grub.cfg` should be group-owned by the `root` group to prevent destruction or modification of the file. To properly set the group owner of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chgrp root /boot/grub2/grub.cfg

Rationale: | The `root` group is a highly-privileged group. Furthermore, the group-owner of this file should not have any access privileges anyway.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R29
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 1.4.2
stigref | SV-257790r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q grub2-common && rpm --quiet -q kernel-core ) && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

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

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

    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212025
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_grub2_cfg_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_grub2_cfg_newgroup: '0'
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212025
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub2/grub.cfg
      register: file_exists
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212025
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/grub2/grub.cfg
      ansible.builtin.file:
        path: /boot/grub2/grub.cfg
        follow: false
        group: '{{ file_groupowner_grub2_cfg_newgroup }}'
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" 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
      - DISA-STIG-RHEL-09-212025
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub2/grub.cfg User Ownership [ref]

The file `/boot/grub2/grub.cfg` should be owned by the `root` user to prevent destruction or modification of the file. To properly set the owner of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chown root /boot/grub2/grub.cfg

Rationale: | Only root should be able to modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R29
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 1.4.2
stigref | SV-257791r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q grub2-common && rpm --quiet -q kernel-core ) && { ! ( [ -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/grub2/grub.cfg" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /boot/grub2/grub.cfg
    fi

    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212030
      - 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:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212030
      - 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/grub2/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub2/grub.cfg
      register: file_exists
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-212030
      - 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/grub2/grub.cfg
      ansible.builtin.file:
        path: /boot/grub2/grub.cfg
        follow: false
        owner: '{{ file_owner_grub2_cfg_newown }}'
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" 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
      - DISA-STIG-RHEL-09-212030
      - 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 Set the Boot Loader Admin Username to a Non-Default Value [ref]

The grub2 boot loader should have a superuser account and password protection enabled to protect boot-time settings.
To maximize the protection, select a password-protected superuser account with unique name, and modify the `/etc/grub.d/01_users` configuration file to reflect the account name change.
Do not to use common administrator account names like root, admin, or administrator for the grub2 superuser account.
Change the superuser to a different username (The default is 'root').

    $ sed -i 's/\(set superusers=\).*/\1"<unique user ID>"/g' /etc/grub.d/01_users

The line mentioned above must be followed by the line

    export superusers

so that the `superusers` is honored.
Once the superuser account has been added, update the `grub.cfg` file by running:

    grub2-mkconfig -o /boot/grub2/grub.cfg

Warning: To prevent hard-coded admin usernames, 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: | Having a non-default grub superuser username makes password-guessing attacks less effective.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_admin_username

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
os-srg | SRG-OS-000080-GPOS-00048
stigref | SV-257789r1117265_rule

#### 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
stigref | SV-257787r1117265_rule

#### Rule The system must booted with init_on_free=1 [ref]

Setting `init_on_free=1` on boot guarantees that pages and heap objects are initialized right after they're freed, so it won't be possible to access stale data by using a dangling pointer.
Rationale: | `init_on_free` is a Linux kernel boot parameter that enhances security by initializing memory regions when they are freed, preventing data leakage. This process ensures that stale data in freed memory cannot be accessed by malicious programs.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_init_on_free

References:

nist | SC-3
os-srg | SRG-OS-000134-GPOS-00068
stigref | SV-257794r1069362_rule

Remediation script ⇲

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

    bootloader init_on_free=1

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q grub2-common && rpm --quiet -q kernel-core ) && { rpm --quiet -q grub2-common; }; then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "init_on_free" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"init_on_free=[^\"]*\"(.*]\s*)/\1\"init_on_free=1\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"init_on_free=1\"]" >> "$KARGS_DIR/10-init_on_free.toml"
        fi
    else

        grubby --update-kernel=ALL --args=init_on_free=1

    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:
      - DISA-STIG-RHEL-09-212045
      - NIST-800-53-SC-3
      - grub2_init_on_free
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if init_on_free argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212045
      - NIST-800-53-SC-3
      - grub2_init_on_free
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if init_on_free argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212045
      - NIST-800-53-SC-3
      - grub2_init_on_free
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="init_on_free=1"
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - '"grub2-common" in ansible_facts.packages'
      - (grubby_info.stdout is not search('init_on_free=1')) or ((etc_default_grub['content']
        | b64decode) is not search('init_on_free=1'))
      tags:
      - DISA-STIG-RHEL-09-212045
      - NIST-800-53-SC-3
      - grub2_init_on_free
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "init_on_free=1"

#### Rule Enable Kernel Page-Table Isolation (KPTI) [ref]

To enable Kernel page-table isolation, add the argument `pti=on` to the default GRUB 2 command line for the Linux operating system. To ensure that `pti=on` is added as a kernel command line argument to newly installed kernels, add `pti=on` to the default Grub2 command line for Linux operating systems. Modify the line within `/etc/default/grub` as shown below:

    GRUB_CMDLINE_LINUX="... pti=on ..."

Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --args="pti=on"

If the system is distributed as a bootable container image, GRUB2 can't be configured using the method described above, but the following method needs to be used instead. The kernel arguments should be set in `/usr/lib/bootc/kargs.d` in a TOML file that has the following form:

    # /usr/lib/bootc/kargs.d/10-example.toml
    kargs = ["pti=on"]

For more details on configuring kernel arguments in bootable container images, please refer to Bootc documentation.

Rationale: | Kernel page-table isolation is a kernel feature that mitigates the Meltdown security vulnerability and hardens the kernel against attempts to bypass kernel address space layout randomization (KASLR).
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_pti_argument

References:

nist | SI-16
os-srg | SRG-OS-000433-GPOS-00193, SRG-OS-000095-GPOS-00049
anssi | R8
stigref | SV-257795r1044845_rule

Remediation script ⇲

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

    bootloader pti=on

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q grub2-common && rpm --quiet -q kernel-core ); then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "pti" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"pti=[^\"]*\"(.*]\s*)/\1\"pti=on\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"pti=on\"]" >> "$KARGS_DIR/10-pti.toml"
        fi
    else

        grubby --update-kernel=ALL --args=pti=on

    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:
      - DISA-STIG-RHEL-09-212050
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check if pti argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when: ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-212050
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check if pti argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when: ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-212050
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="pti=on"
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - (grubby_info.stdout is not search('pti=on')) or ((etc_default_grub['content']
        | b64decode) is not search('pti=on'))
      tags:
      - DISA-STIG-RHEL-09-212050
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "pti=on"

#### Rule Disable vsyscalls [ref]

To disable use of virtual syscalls, add the argument `vsyscall=none` to the default GRUB 2 command line for the Linux operating system. To ensure that `vsyscall=none` is added as a kernel command line argument to newly installed kernels, add `vsyscall=none` to the default Grub2 command line for Linux operating systems. Modify the line within `/etc/default/grub` as shown below:

    GRUB_CMDLINE_LINUX="... vsyscall=none ..."

Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --args="vsyscall=none"

If the system is distributed as a bootable container image, GRUB2 can't be configured using the method described above, but the following method needs to be used instead. The kernel arguments should be set in `/usr/lib/bootc/kargs.d` in a TOML file that has the following form:

    # /usr/lib/bootc/kargs.d/10-example.toml
    kargs = ["vsyscall=none"]

For more details on configuring kernel arguments in bootable container images, please refer to Bootc documentation.
Warning: The vsyscall emulation is only available on x86_64 architecture (CONFIG_X86_VSYSCALL_EMULATION) making this rule not applicable to other CPU architectures.

Rationale: | Virtual Syscalls provide an opportunity of attack for a user who has control of the return instruction pointer.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_vsyscall_argument

References:

nist | CM-7(a)
ospp | FPT_ASLR_EXT.1
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000134-GPOS-00068
stigref | SV-257792r1044842_rule

Remediation script ⇲

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

    bootloader vsyscall=none

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q grub2-common && rpm --quiet -q kernel-core ) && { ( grep -sqE "^.*\.x86_64$" /proc/sys/kernel/osrelease || grep -sqE "^x86_64$" /proc/sys/kernel/arch; ); }; then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "vsyscall" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"vsyscall=[^\"]*\"(.*]\s*)/\1\"vsyscall=none\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"vsyscall=none\"]" >> "$KARGS_DIR/10-vsyscall.toml"
        fi
    else

        grubby --update-kernel=ALL --args=vsyscall=none

    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:
      - DISA-STIG-RHEL-09-212035
      - NIST-800-53-CM-7(a)
      - grub2_vsyscall_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if vsyscall argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - ansible_architecture == "x86_64"
      tags:
      - DISA-STIG-RHEL-09-212035
      - NIST-800-53-CM-7(a)
      - grub2_vsyscall_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if vsyscall argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - ansible_architecture == "x86_64"
      tags:
      - DISA-STIG-RHEL-09-212035
      - NIST-800-53-CM-7(a)
      - grub2_vsyscall_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="vsyscall=none"
      when:
      - ( "grub2-common" in ansible_facts.packages and "kernel-core" in ansible_facts.packages
        )
      - ansible_architecture == "x86_64"
      - (grubby_info.stdout is not search('vsyscall=none')) or ((etc_default_grub['content']
        | b64decode) is not search('vsyscall=none'))
      tags:
      - DISA-STIG-RHEL-09-212035
      - NIST-800-53-CM-7(a)
      - grub2_vsyscall_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "vsyscall=none"

Group Configure Syslog Group contains 4 groups and 11 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 Red Hat Enterprise Linux 9, rsyslog has replaced ksyslogd as the syslog daemon of choice, and it includes some additional security features such as reliable, connection-oriented (i.e. TCP) transmission of logs, the option to log to database formats, and the encryption of log data en route to a central logging server. This section discusses how to configure rsyslog for best effect, and how to use tools provided with the system to maintain and monitor logs.

Group Ensure Proper Configuration of Log Files Group contains 5 rules

[ref] The file `/etc/rsyslog.conf` controls where log message are written. These are controlled by lines called rules, which consist of a selector and an action. These rules are often customized depending on the role of the system, the requirements of the environment, and whatever may enable the administrator to most effectively make use of log data. The default rules in Red Hat Enterprise Linux 9 are:

    *.info;mail.none;authpriv.none;cron.none                /var/log/messages
    authpriv.*                                              /var/log/secure
    mail.*                                                  -/var/log/maillog
    cron.*                                                  /var/log/cron
    *.emerg                                                 *
    uucp,news.crit                                          /var/log/spooler
    local7.*                                                /var/log/boot.log

See the man page `rsyslog.conf(5)` for more information. Note that the `rsyslog` daemon can be configured to use a timestamp format that some log processing programs may not understand. If this occurs, edit the file `/etc/rsyslog.conf` and add or edit the following line:

    $ ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

#### Rule Ensure cron Is Logging To Rsyslog [ref]

Cron logging must be implemented to spot intrusions or trace cron job status. If `cron` is not logging to `rsyslog`, it can be implemented by adding the following to the RULES section of `/etc/rsyslog.conf`: If the legacy syntax is used:

    cron.*                                                  /var/log/cron

If the modern syntax (RainerScript) is used:

    cron.* action(type="omfile" file="/var/log/cron")

Rationale: | Cron logging can be used to trace the successful or unsuccessful execution of cron jobs. It can also be used to spot intrusions into the use of the cron facility by unauthorized and malicious users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_cron_logging

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
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
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.15.2.1, A.15.2.2
nist | CM-6(a)
nist-csf | ID.SC-4, PR.PT-1
os-srg | SRG-OS-000480-GPOS-00227
ism | 0988, 1405
stigref | SV-258150r1045296_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q rsyslog; then

    RSYSLOG_CONF='/etc/rsyslog.conf'
    RSYSLOG_D_FOLDER='/etc/rsyslog.d'
    RSYSLOG_D_CONF='/etc/rsyslog.d/encrypt.conf'
    test -f $RSYSLOG_CONF || touch $RSYSLOG_CONF
    mkdir -p $RSYSLOG_D_FOLDER
    # remove all multilined cron.* entries
    sed -i '/^[[:space:]]*cron\.\*.*action(/,/)/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*cron\.\*.*action(/,/)/d' {} +
    # remove all legacy format and one line cron.* entries
    sed -i '/^\s*\*\.\*\s+/var/log/cron\s*$/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^\s*\*\.\*\s+/var/log/cron\s*$/d' {} +
    sed -i '/^[[:space:]]*cron\.\*/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*cron\.\*/d' {} +

    echo "cron.*	/var/log/cron" >> $RSYSLOG_D_CONF

    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Ensure /etc/rsyslog.conf exists
      ansible.builtin.file:
        path: /etc/rsyslog.conf
        state: touch
        modification_time: preserve
        access_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Ensure /etc/rsyslog.d directory exists
      ansible.builtin.file:
        path: /etc/rsyslog.d
        state: directory
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Remove multilined cron.* action() entries
        from rsyslog.conf
      ansible.builtin.shell: sed -i '/^[[:space:]]*cron\.\*.*action(/,/)/d' /etc/rsyslog.conf
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Remove multilined cron.* action() entries
        from rsyslog.d/*.conf
      ansible.builtin.shell: find /etc/rsyslog.d -type f -name "*.conf" -exec sed -i '/^[[:space:]]*cron\.\*.*action(/,/)/d'
        {} +
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Remove *.* entries pointing to /var/log/cron from rsyslog.conf
      ansible.builtin.lineinfile:
        path: /etc/rsyslog.conf
        create: false
        regexp: (?i)^\s*\*\.\*\s+/var/log/cron\s*$
        state: absent
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Remove *.* entries pointing to /var/log/cron
        from rsyslog.d/*.conf
      ansible.builtin.shell: find /etc/rsyslog.d -type f -name "*.conf" -exec sed -i '\|^\s*\*\.\*\s\+/var/log/cron\s*$|d'
        {} +
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Check if the parameter cron.* is configured
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "cron.*"| regex_escape }}
      register: _sshd_config_has_parameter
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Check if the parameter cron.* is configured
        correctly
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "cron.*"| regex_escape }}/var/log/cron$
      register: _sshd_config_correctly
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog
      block:

      - name: Deduplicate values from /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: false
          regexp: (?i)^\s*{{ "cron.*"| regex_escape }}
          state: absent

      - name: Check if /etc/rsyslog.d exists
        ansible.builtin.stat:
          path: /etc/rsyslog.d
        register: _etc_rsyslog_d_exists

      - name: Check if the parameter cron.* is present in /etc/rsyslog.d
        ansible.builtin.find:
          paths: /etc/rsyslog.d
          recurse: 'yes'
          follow: 'no'
          contains: ^\s*{{ "cron.*"| regex_escape }}
        register: _etc_rsyslog_d_has_parameter
        when: _etc_rsyslog_d_exists.stat.isdir is defined and _etc_rsyslog_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/rsyslog.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)^\s*{{ "cron.*"| regex_escape }}
          state: absent
        with_items: '{{ _etc_rsyslog_d_has_parameter.files }}'
        when: _etc_rsyslog_d_has_parameter.matched

      - name: Insert correct line to /etc/rsyslog.d/cron.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.d/cron.conf
          create: true
          regexp: (?i)^\s*{{ "cron.*"| regex_escape }}
          line: cron.* /var/log/cron
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

    - name: Ensure cron Is Logging To Rsyslog - Restart the rsyslog service now
      ansible.builtin.service:
        name: rsyslog
        state: restarted
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652060
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_cron_logging

#### Rule Ensure Rsyslog Authenticates Off-Loaded Audit Records [ref]

Rsyslogd is a system utility providing support for message logging. Support for both internet and UNIX domain sockets enables this utility to support both local and remote logging. Couple this utility with `gnutls` (which is a secure communications library implementing the SSL, TLS and DTLS protocols), and you have a method to securely encrypt and off-load auditing. When using `rsyslogd` to off-load logs the remote system must be authenticated. Set the following configuration option in /etc/rsyslog.conf or in a file in /etc/rsyslog.d (using legacy syntax):

    $ActionSendStreamDriverAuthMode x509/name

Alternatively, use the RainerScript syntax:

    action(type="omfwd" Target="some.example.com" StreamDriverAuthMode="x509/name")

Rationale: | The audit records generated by Rsyslog contain valuable information regarding system configuration, user authentication, and other such information. Audit records should be protected from unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_encrypt_offload_actionsendstreamdriverauthmode

References:

nist | AU-4(1)
os-srg | SRG-OS-000342-GPOS-00133, SRG-OS-000479-GPOS-00224
stigref | SV-258146r1045288_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q rsyslog; then

    RSYSLOG_CONF='/etc/rsyslog.conf'
    RSYSLOG_D_FOLDER='/etc/rsyslog.d'
    RSYSLOG_D_CONF='/etc/rsyslog.d/encrypt.conf'
    test -f $RSYSLOG_CONF || touch $RSYSLOG_CONF
    mkdir -p $RSYSLOG_D_FOLDER
    # remove legacy entries
    sed -i '/^[[:space:]]*\$ActionSendStreamDriverAuthMode/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*\$ActionSendStreamDriverAuthMode/d' {} +
    # remove all multilined and onelined RainerScript entries
    sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverAuthMode/d }' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverAuthMode/d }' {} +

    if [ -e "$RSYSLOG_D_CONF" ] ; then

        LC_ALL=C sed -i "/^\s*\$ActionSendStreamDriverAuthMode /Id" "$RSYSLOG_D_CONF"
    else
        touch "$RSYSLOG_D_CONF"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "$RSYSLOG_D_CONF"

    cp "$RSYSLOG_D_CONF" "$RSYSLOG_D_CONF.bak"
    # Insert at the end of the file
    printf '%s\n' "\$ActionSendStreamDriverAuthMode x509/name" >> "$RSYSLOG_D_CONF"
    # Clean up after ourselves.
    rm "$RSYSLOG_D_CONF.bak"

    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:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Ensure /etc/rsyslog.conf
        exists
      ansible.builtin.file:
        path: /etc/rsyslog.conf
        state: touch
        modification_time: preserve
        access_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Ensure /etc/rsyslog.d
        directory exists
      ansible.builtin.file:
        path: /etc/rsyslog.d
        state: directory
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Remove RainerScript
        action() entries with StreamDriverAuthMode from rsyslog.conf
      ansible.builtin.shell: |
        sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverAuthMode/d }' /etc/rsyslog.conf
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Remove RainerScript
        action() entries with StreamDriverAuthMode from rsyslog.d/*.conf
      ansible.builtin.shell: |
        find /etc/rsyslog.d -type f -name "*.conf" -exec sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverAuthMode/d }' {} +
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Check if the parameter
        $ActionSendStreamDriverAuthMode is configured
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\s
      register: _sshd_config_has_parameter
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records - Check if the parameter
        $ActionSendStreamDriverAuthMode is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\sx509/name$
      register: _sshd_config_correctly
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

    - name: Ensure Rsyslog Authenticates Off-Loaded Audit Records
      block:

      - name: Deduplicate values from /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: false
          regexp: (?i)^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\s
          state: absent

      - name: Check if /etc/rsyslog.d exists
        ansible.builtin.stat:
          path: /etc/rsyslog.d
        register: _etc_rsyslog_d_exists

      - name: Check if the parameter $ActionSendStreamDriverAuthMode is present in /etc/rsyslog.d
        ansible.builtin.find:
          paths: /etc/rsyslog.d
          recurse: 'yes'
          follow: 'no'
          contains: ^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\s
        register: _etc_rsyslog_d_has_parameter
        when: _etc_rsyslog_d_exists.stat.isdir is defined and _etc_rsyslog_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/rsyslog.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\s
          state: absent
        with_items: '{{ _etc_rsyslog_d_has_parameter.files }}'
        when: _etc_rsyslog_d_has_parameter.matched

      - name: Insert correct line to /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: true
          regexp: (?i)^\s*{{ "$ActionSendStreamDriverAuthMode"| regex_escape }}\s
          line: $ActionSendStreamDriverAuthMode x509/name
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-652040
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdriverauthmode

#### Rule Ensure Rsyslog Encrypts Off-Loaded Audit Records [ref]

Rsyslogd is a system utility providing support for message logging. Support for both internet and UNIX domain sockets enables this utility to support both local and remote logging. Couple this utility with `gnutls` (which is a secure communications library implementing the SSL, TLS and DTLS protocols), and you have a method to securely encrypt and off-load auditing. When using `rsyslogd` to off-load logs off a encryption system must be used. Set the following configuration option in /etc/rsyslog.conf or in a file in /etc/rsyslog.d (using legacy syntax):

    $ActionSendStreamDriverMode 1

Alternatively, use the RainerScript syntax:

    action(type="omfwd" ... StreamDriverMode="1")

Rationale: | The audit records generated by Rsyslog contain valuable information regarding system configuration, user authentication, and other such information. Audit records should be protected from unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_encrypt_offload_actionsendstreamdrivermode

References:

nist | AU-4(1)
os-srg | SRG-OS-000342-GPOS-00133, SRG-OS-000479-GPOS-00224
stigref | SV-258147r1045290_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q rsyslog; then

    RSYSLOG_CONF='/etc/rsyslog.conf'
    RSYSLOG_D_FOLDER='/etc/rsyslog.d'
    RSYSLOG_D_CONF='/etc/rsyslog.d/encrypt.conf'
    test -f $RSYSLOG_CONF || touch $RSYSLOG_CONF
    mkdir -p $RSYSLOG_D_FOLDER
    # remove ActionSendStreamDriverMode entries
    sed -i '/^[[:space:]]*\$ActionSendStreamDriverMode/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*\$ActionSendStreamDriverMode/d' {} +
    # remove all multilined and onelined RainerScript entries
    sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverMode/d }' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverMode/d }' {} +

    if [ -e "$RSYSLOG_D_CONF" ] ; then

        LC_ALL=C sed -i "/^\s*\$ActionSendStreamDriverMode /Id" "$RSYSLOG_D_CONF"
    else
        touch "$RSYSLOG_D_CONF"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "$RSYSLOG_D_CONF"

    cp "$RSYSLOG_D_CONF" "$RSYSLOG_D_CONF.bak"
    # Insert at the end of the file
    printf '%s\n' "\$ActionSendStreamDriverMode 1" >> "$RSYSLOG_D_CONF"
    # Clean up after ourselves.
    rm "$RSYSLOG_D_CONF.bak"

    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:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Ensure /etc/rsyslog.conf
        exists
      ansible.builtin.file:
        path: /etc/rsyslog.conf
        state: touch
        modification_time: preserve
        access_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Ensure /etc/rsyslog.d directory
        exists
      ansible.builtin.file:
        path: /etc/rsyslog.d
        state: directory
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Remove RainerScript action()
        entries with StreamDriverMode from rsyslog.conf
      ansible.builtin.shell: |
        sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverMode/d }' /etc/rsyslog.conf
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Remove RainerScript action()
        entries with StreamDriverMode from rsyslog.d/*.conf
      ansible.builtin.shell: |
        find /etc/rsyslog.d -type f -name "*.conf" -exec sed -i '/^[[:space:]]*action(/ { :a; N; /)/!ba; /StreamDriverMode/d }' {} +
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Check if the parameter
        $ActionSendStreamDriverMode is configured
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }}
      register: _sshd_config_has_parameter
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Check if the parameter
        $ActionSendStreamDriverMode is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }} 1$
      register: _sshd_config_correctly
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records
      block:

      - name: Deduplicate values from /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: false
          regexp: '(?i)^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }} '
          state: absent

      - name: Check if /etc/rsyslog.d exists
        ansible.builtin.stat:
          path: /etc/rsyslog.d
        register: _etc_rsyslog_d_exists

      - name: Check if the parameter $ActionSendStreamDriverMode is present in /etc/rsyslog.d
        ansible.builtin.find:
          paths: /etc/rsyslog.d
          recurse: 'yes'
          follow: 'no'
          contains: '^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }} '
        register: _etc_rsyslog_d_has_parameter
        when: _etc_rsyslog_d_exists.stat.isdir is defined and _etc_rsyslog_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/rsyslog.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: '(?i)^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }} '
          state: absent
        with_items: '{{ _etc_rsyslog_d_has_parameter.files }}'
        when: _etc_rsyslog_d_has_parameter.matched

      - name: Insert correct line to /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: true
          regexp: '(?i)^\s*{{ "$ActionSendStreamDriverMode"| regex_escape }} '
          line: $ActionSendStreamDriverMode 1
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-652045
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_actionsendstreamdrivermode

#### Rule Ensure Rsyslog Encrypts Off-Loaded Audit Records [ref]

Rsyslogd is a system utility providing support for message logging. Support for both internet and UNIX domain sockets enables this utility to support both local and remote logging. Couple this utility with `gnutls` (which is a secure communications library implementing the SSL, TLS and DTLS protocols), and you have a method to securely encrypt and off-load auditing. When using `rsyslogd` to off-load logs off an encryption system must be used. Set the following configuration option in /etc/rsyslog.conf or in a file in /etc/rsyslog.d (using legacy syntax):

    $DefaultNetstreamDriver gtls

Alternatively, use the RainerScript syntax:

    global(DefaultNetstreamDriver="gtls")

Rationale: | The audit records generated by Rsyslog contain valuable information regarding system configuration, user authentication, and other such information. Audit records should be protected from unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_encrypt_offload_defaultnetstreamdriver

References:

nist | AU-4(1)
os-srg | SRG-OS-000342-GPOS-00133, SRG-OS-000479-GPOS-00224
stigref | SV-258148r1045292_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q rsyslog; then

    RSYSLOG_CONF='/etc/rsyslog.conf'
    RSYSLOG_D_FOLDER='/etc/rsyslog.d'
    RSYSLOG_D_CONF='/etc/rsyslog.d/encrypt.conf'
    test -f $RSYSLOG_CONF || touch $RSYSLOG_CONF
    mkdir -p $RSYSLOG_D_FOLDER
    # remove DefaultNetstreamDriver entries
    sed -i '/^[[:space:]]*\$DefaultNetstreamDriver/d' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*\$DefaultNetstreamDriver/d' {} +
    # remove all multilined and onelined RainerScript entries
    sed -i '/^[[:space:]]*global(/ { :a; N; /)/!ba; /DefaultNetstreamDriver/d }' $RSYSLOG_CONF
    find $RSYSLOG_D_FOLDER -type f -name "*.conf" -exec sed -i '/^[[:space:]]*global(/ { :a; N; /)/!ba; /DefaultNetstreamDriver/d }' {} +

    if [ -e "$RSYSLOG_D_CONF" ] ; then

        LC_ALL=C sed -i "/^\s*\$DefaultNetstreamDriver /Id" "$RSYSLOG_D_CONF"
    else
        touch "$RSYSLOG_D_CONF"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "$RSYSLOG_D_CONF"

    cp "$RSYSLOG_D_CONF" "$RSYSLOG_D_CONF.bak"
    # Insert at the end of the file
    printf '%s\n' "\$DefaultNetstreamDriver gtls" >> "$RSYSLOG_D_CONF"
    # Clean up after ourselves.
    rm "$RSYSLOG_D_CONF.bak"

    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:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Ensure /etc/rsyslog.conf
        exists
      ansible.builtin.file:
        path: /etc/rsyslog.conf
        state: touch
        modification_time: preserve
        access_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Ensure /etc/rsyslog.d directory
        exists
      ansible.builtin.file:
        path: /etc/rsyslog.d
        state: directory
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Remove RainerScript global()
        entries with DefaultNetstreamDriver from rsyslog.conf
      ansible.builtin.shell: |
        sed -i '/^[[:space:]]*global(/ { :a; N; /)/!ba; /DefaultNetstreamDriver/d }' /etc/rsyslog.conf
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Remove RainerScript global()
        entries with DefaultNetstreamDriver from rsyslog.d/*.conf
      ansible.builtin.shell: |
        find /etc/rsyslog.d -type f -name "*.conf" -exec sed -i '/^[[:space:]]*global(/ { :a; N; /)/!ba; /DefaultNetstreamDriver/d }' {} +
      changed_when: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Check if the parameter
        $DefaultNetstreamDriver is configured
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$DefaultNetstreamDriver"| regex_escape }}
      register: _sshd_config_has_parameter
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records - Check if the parameter
        $DefaultNetstreamDriver is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/rsyslog.conf
        - /etc/rsyslog.d
        contains: ^\s*{{ "$DefaultNetstreamDriver"| regex_escape }} gtls$
      register: _sshd_config_correctly
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

    - name: Ensure Rsyslog Encrypts Off-Loaded Audit Records
      block:

      - name: Deduplicate values from /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: false
          regexp: '(?i)^\s*{{ "$DefaultNetstreamDriver"| regex_escape }} '
          state: absent

      - name: Check if /etc/rsyslog.d exists
        ansible.builtin.stat:
          path: /etc/rsyslog.d
        register: _etc_rsyslog_d_exists

      - name: Check if the parameter $DefaultNetstreamDriver is present in /etc/rsyslog.d
        ansible.builtin.find:
          paths: /etc/rsyslog.d
          recurse: 'yes'
          follow: 'no'
          contains: '^\s*{{ "$DefaultNetstreamDriver"| regex_escape }} '
        register: _etc_rsyslog_d_has_parameter
        when: _etc_rsyslog_d_exists.stat.isdir is defined and _etc_rsyslog_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/rsyslog.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: '(?i)^\s*{{ "$DefaultNetstreamDriver"| regex_escape }} '
          state: absent
        with_items: '{{ _etc_rsyslog_d_has_parameter.files }}'
        when: _etc_rsyslog_d_has_parameter.matched

      - name: Insert correct line to /etc/rsyslog.conf
        ansible.builtin.lineinfile:
          path: /etc/rsyslog.conf
          create: true
          regexp: '(?i)^\s*{{ "$DefaultNetstreamDriver"| regex_escape }} '
          line: $DefaultNetstreamDriver gtls
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-652050
      - NIST-800-53-AU-4(1)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_encrypt_offload_defaultnetstreamdriver

#### Rule Ensure remote access methods are monitored in Rsyslog [ref]

Logging of remote access methods must be implemented to help identify cyber attacks and ensure ongoing compliance with remote access policies are being audited and upheld. An examples of a remote access method is the use of the Remote Desktop Protocol (RDP) from an external, non-organization controlled network. The `/etc/rsyslog.conf` or `/etc/rsyslog.d/*.conf` file should contain a match for the following selectors: `auth.*`, `authpriv.*`, and `daemon.*`. If not, use the following as an example configuration: `auth.*;authpriv.* /var/log/secure daemon.* /var/log/messages`

Rationale: | Logging remote access methods can be used to trace the decrease the risks associated with remote user access management. It can also be used to spot cyber attacks and ensure ongoing compliance with organizational policies surrounding the use of remote access methods.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_remote_access_monitoring

References:

nist | AC-17(1)
os-srg | SRG-OS-000032-GPOS-00013
stigref | SV-258144r1045286_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q rsyslog; then

    declare -A REMOTE_METHODS=( ['auth.*']='^[^#]*auth\.\*.*$' ['authpriv.*']='^[^#]*authpriv\.\*.*$' ['daemon.*']='^[^#]*daemon\.\*.*$' )
    declare -A LOCATIONS=( ['auth.*']='/var/log/secure' ['authpriv.*']='/var/log/secure' ['daemon.*']='/var/log/messages' )

    if [[ ! -f /etc/rsyslog.conf ]]; then
    	# Something is not right, create the file
    	touch /etc/rsyslog.conf
    fi

    # Loop through the remote methods associative array
    for K in "${!REMOTE_METHODS[@]}"
    do
    	# Check to see if selector/value exists
    	if ! grep -rq "${REMOTE_METHODS[$K]}" /etc/rsyslog.*; then
            APPEND_LINE=$(sed -rn "/^\S+\s+\${LOCATIONS[$K]}$/p" /etc/rsyslog.conf)
    		# Make sure we have a line to insert after, otherwise append to end
    		if [[ ! -z ${APPEND_LINE} ]]; then
    			# Add selector to file
    			sed -r -i "0,/^(\S+\s+\/var\/log\/secure$)/s//\1\n${K} \/var\/log\/secure/" /etc/rsyslog.conf
    		else
    			echo "${K} ${LOCATIONS[$K]}" >> /etc/rsyslog.conf
    		fi
    	fi
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Set facts'
      ansible.builtin.set_fact:
        conf_files:
        - /etc/rsyslog.conf
        remote_methods:
        - selector: auth.*
          regexp: ^.*auth\.\*.*$
          location: /var/log/secure
        - selector: authpriv.*
          regexp: ^.*authpriv\.\*.*$
          location: /var/log/secure
        - selector: daemon.*
          regexp: ^.*daemon\.\*.*$
          location: /var/log/messages
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Ensure rsyslog.conf
        exists'
      ansible.builtin.file:
        path: '{{ conf_files.0 }}'
        state: touch
        access_time: preserve
        modification_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Gather conf.d files'
      ansible.builtin.find:
        patterns:
        - '*.conf'
        paths:
        - /etc/rsyslog.d
      register: rsyslogd
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Set conf file(s)'
      ansible.builtin.set_fact:
        conf_files: '{{ conf_files + [item.path] }}'
      loop: '{{ rsyslogd.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslogd.matched > 0
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Check for existing
        values'
      ansible.builtin.lineinfile:
        path: '{{ item.1 }}'
        regexp: '{{ item.0.regexp }}'
        state: absent
      check_mode: true
      changed_when: false
      register: remote_method_values
      loop: '{{ remote_methods|product(conf_files)|list }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

    - name: 'Ensure remote access methods are monitored in Rsyslog: Configure'
      ansible.builtin.lineinfile:
        path: /etc/rsyslog.conf
        line: '{{ item.item.0.selector }} {{ item.item.0.location }}'
        insertafter: ^.*\/var\/log\/secure.*$
        create: true
      loop: '{{ remote_method_values.results }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - item.found == 0
      tags:
      - DISA-STIG-RHEL-09-652030
      - NIST-800-53-AC-17(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_remote_access_monitoring

Group systemd-journald Group contains 1 rule
[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 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, Red Hat Enterprise Linux 9 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.2.1.1
stigref | SV-257783r991562_rule

Remediation script ⇲

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

    service enable systemd-journald

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-211040
      - 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:
      - DISA-STIG-RHEL-09-211040
      - NIST-800-53-SC-24
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-journald_enabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["systemd-journald"]

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
ism | 0988, 1405
stigref | SV-258143r1045283_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - rsyslog_legacy_remote_listen_files | length > 0
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - rsyslog_rainer_remote_listen_files | length > 0
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - rsyslog_listen_legacy_comment is changed or rsyslog_listen_rainer_comment is changed
      tags:
      - DISA-STIG-RHEL-09-652025
      - 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

Group Rsyslog Logs Sent To Remote Host Group contains 1 rule

[ref] If system logs are to be useful in detecting malicious activities, it is necessary to send logs to a remote server. An intruder who has compromised the root account on a system may delete the log entries which indicate that the system was attacked before they are seen by an administrator.
However, it is recommended that logs be stored on the local host in addition to being sent to the loghost, especially if `rsyslog` has been configured to use the UDP protocol to send messages over a network. UDP does not guarantee reliable delivery, and moderately busy sites will lose log messages occasionally, especially in periods of high traffic which may be the result of an attack. In addition, remote `rsyslog` messages are not authenticated in any way by default, so it is easy for an attacker to introduce spurious messages to the central log server. Also, some problems cause loss of network connectivity, which will prevent the sending of messages to the central server. For all of these reasons, it is better to store log messages both centrally and on each host, so that they can be correlated if necessary.

#### Rule Ensure Logs Sent To Remote Host [ref]

To configure rsyslog to send logs to a remote log server, open `/etc/rsyslog.conf` and read and understand the last section of the file, which describes the multiple directives necessary to activate remote logging. Along with these other directives, the system can be configured to forward its logs to a particular log server by adding or correcting one of the following lines, substituting `logcollector` appropriately. The choice of protocol depends on the environment of the system; although TCP and RELP provide more reliable message delivery, they may not be supported in all environments.
To use UDP for log message delivery:

    *.* @logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="udp")

To use TCP for log message delivery:

    *.* @@logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="tcp")

To use RELP for log message delivery:

    *.* :omrelp:logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="relp")

There must be a resolvable DNS CNAME or Alias record set to "logcollector" for logs to be sent correctly to the centralized logging utility.
Warning: It is important to configure queues in case the client is sending log messages to a remote server. If queues are not configured, the system will stop functioning when the connection to the remote server is not available. Please consult Rsyslog documentation for more information about configuration of queues. The example configuration which should go into `/etc/rsyslog.conf` can look like the following lines:

    $ActionQueueType LinkedList
    $ActionQueueFileName queuefilename
    $ActionQueueMaxDiskSpace 1g
    $ActionQueueSaveOnShutdown on
    $ActionResumeRetryCount -1

Or if using Rainer Script syntax, it could be:

    *.* action(type="omfwd" queue.type="linkedlist" queue.filename="example_fwd" action.resumeRetryCount="-1" queue.saveOnShutdown="on" target="example.com" port="30514" protocol="tcp")

Rationale: | A log server (loghost) receives syslog messages from one or more systems. This data can be used as an additional log source in the event a system is compromised and its local logs are suspect. Forwarding log messages to a remote loghost also provides system administrators with a centralized place to view the status of multiple hosts within the enterprise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_remote_loghost

References:

cis-csc | 1, 13, 14, 15, 16, 2, 3, 5, 6
cobit5 | APO11.04, APO13.01, BAI03.05, BAI04.04, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(5)(ii)(B), 164.308(a)(5)(ii)(C), 164.308(a)(6)(ii), 164.308(a)(8), 164.310(d)(2)(iii), 164.312(b), 164.314(a)(2)(i)(C), 164.314(a)(2)(iii)
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 7.1, SR 7.2
iso27001-2013 | A.12.1.3, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.17.2.1
nerc-cip | CIP-003-8 R5.2, CIP-004-6 R3.3
nist | CM-6(a), AU-4(1), AU-9(2)
nist-csf | PR.DS-4, PR.PT-1
os-srg | SRG-OS-000479-GPOS-00224, SRG-OS-000480-GPOS-00227, SRG-OS-000342-GPOS-00133
anssi | R71
ism | 0988, 1405
stigref | SV-258149r1106462_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    rsyslog_remote_loghost_address='logcollector'

    # 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' <<< "^\*\.\*")

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

    # 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 "^\*\.\*\\>" "/etc/rsyslog.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^\*\.\*\\>.*/$escaped_formatted_output/gi" "/etc/rsyslog.conf"
    else
        if [[ -s "/etc/rsyslog.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/rsyslog.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/rsyslog.conf"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/rsyslog.conf" >> "/etc/rsyslog.conf"
        printf '%s\n' "$formatted_output" >> "/etc/rsyslog.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:
      - DISA-STIG-RHEL-09-652055
      - NIST-800-53-AU-4(1)
      - NIST-800-53-AU-9(2)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - rsyslog_remote_loghost
    - name: XCCDF Value rsyslog_remote_loghost_address # promote to variable
      set_fact:
        rsyslog_remote_loghost_address: !!str logcollector
      tags:
        - always

    - name: Set rsyslog remote loghost
      ansible.builtin.lineinfile:
        dest: /etc/rsyslog.conf
        regexp: ^\*\.\*
        line: '*.* @@{{ rsyslog_remote_loghost_address }}'
        create: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652055
      - NIST-800-53-AU-4(1)
      - NIST-800-53-AU-9(2)
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - rsyslog_remote_loghost

#### Rule Ensure rsyslog-gnutls is installed [ref]

TLS protocol support for rsyslog is installed. The `rsyslog-gnutls` package can be installed with the following command:

    $ sudo dnf install rsyslog-gnutls

Rationale: | The rsyslog-gnutls package provides Transport Layer Security (TLS) support for the rsyslog daemon, which enables secure remote logging.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsyslog-gnutls_installed

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000120-GPOS-00061
anssi | R71
stigref | SV-258141r1045280_rule

Remediation script ⇲

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

    dnf install rsyslog-gnutls

Remediation script ⇲

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

    package install rsyslog-gnutls

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "rsyslog-gnutls" ; then
        dnf install -y "rsyslog-gnutls"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_rsyslog-gnutls

    class install_rsyslog-gnutls {
      package { 'rsyslog-gnutls':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=rsyslog-gnutls

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-652015
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog-gnutls_installed

    - name: Ensure rsyslog-gnutls is installed
      ansible.builtin.package:
        name: rsyslog-gnutls
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652015
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog-gnutls_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "rsyslog-gnutls"
    version = "*"

#### Rule Ensure rsyslog is Installed [ref]

Rsyslog is installed by default. The `rsyslog` package can be installed with the following command:

     $ sudo dnf install rsyslog

Rationale: | The rsyslog package provides the rsyslog daemon, which provides system logging services.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsyslog_installed

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a)
nist-csf | PR.PT-1
os-srg | SRG-OS-000479-GPOS-00224, SRG-OS-000051-GPOS-00024, SRG-OS-000480-GPOS-00227
ism | 1409
stigref | SV-258140r1106460_rule

Remediation script ⇲

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

    dnf install rsyslog

Remediation script ⇲

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

    package install rsyslog

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "rsyslog" ; then
        dnf install -y "rsyslog"
    fi

    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 Anaconda snippet ⇲

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

    package --add=rsyslog

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-652010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-652010
      - 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 Red Hat Enterprise Linux 9. The `rsyslog` service can be enabled with the following command:

    $ sudo systemctl enable rsyslog.service

Rationale: | The `rsyslog` service must be running in order to provide logging services, which are essential to system administration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_rsyslog_enabled

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO13.01, BAI03.05, BAI04.04, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2, SR 7.1, SR 7.2
iso27001-2013 | A.12.1.3, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2, A.17.2.1
nist | CM-6(a), AU-4(1)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.DS-4, PR.PT-1
os-srg | SRG-OS-000480-GPOS-00227
ism | 1409
stigref | SV-258142r991589_rule

Remediation script ⇲

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

    service enable rsyslog

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-652020
      - 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:
      - DISA-STIG-RHEL-09-652020
      - 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: '"kernel-core" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["rsyslog"]

Group Network Configuration and Firewalls Group contains 13 groups and 37 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 firewalld Group contains 2 groups and 4 rules

[ref] The dynamic firewall daemon `firewalld` provides a dynamically managed firewall with support for network “zones” to assign a level of trust to a network and its associated connections and interfaces. It has support for IPv4 and IPv6 firewall settings. It supports Ethernet bridges and has a separation of runtime and permanent configuration options. It also has an interface for services or applications to add firewall rules directly.
A graphical configuration tool, `firewall-config`, is used to configure `firewalld`, which in turn uses `iptables` tool to communicate with `Netfilter` in the kernel which implements packet filtering.
The firewall service provided by `firewalld` is dynamic rather than static because changes to the configuration can be made at anytime and are immediately implemented. There is no need to save or apply the changes. No unintended disruption of existing network connections occurs as no part of the firewall has to be reloaded.

Group Inspect and Activate Default firewalld Rules Group contains 2 rules

[ref] Firewalls can be used to separate networks into different zones based on the level of trust the user has decided to place on the devices and traffic within that network. `NetworkManager` informs firewalld to which zone an interface belongs. An interface's assigned zone can be changed by `NetworkManager` or via the `firewall-config` tool.
The zone settings in `/etc/firewalld/` are a range of preset settings which can be quickly applied to a network interface. These are the zones provided by firewalld sorted according to the default trust level of the zones from untrusted to trusted:

- `drop`

  Any incoming network packets are dropped, there is no reply. Only outgoing network connections are possible.

- `block`

  Any incoming network connections are rejected with an `icmp-host-prohibited` message for IPv4 and `icmp6-adm-prohibited` for IPv6. Only network connections initiated from within the system are possible.

- `public`

  For use in public areas. You do not trust the other computers on the network to not harm your computer. Only selected incoming connections are accepted.

- `external`

  For use on external networks with masquerading enabled especially for routers. You do not trust the other computers on the network to not harm your computer. Only selected incoming connections are accepted.

- `dmz`

  For computers in your demilitarized zone that are publicly-accessible with limited access to your internal network. Only selected incoming connections are accepted.

- `work`

  For use in work areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.

- `home`

  For use in home areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.

- `internal`

  For use on internal networks. You mostly trust the other computers on the networks to not harm your computer. Only selected incoming connections are accepted.

- `trusted`

  All network connections are accepted.

It is possible to designate one of these zones to be the default zone. When interface connections are added to `NetworkManager`, they are assigned to the default zone. On installation, the default zone in firewalld is set to be the public zone.
To find out all the settings of a zone, for example the `public zone,` enter the following command as root:

    # firewall-cmd --zone=public --list-all

Example output of this command might look like the following:

    # firewall-cmd --zone=public --list-all
    public
      interfaces:
      services: mdns dhcpv6-client ssh
      ports:
      forward-ports:
      icmp-blocks: source-quench

To view the network zones currently active, enter the following command as root:

    # firewall-cmd --get-service

The following listing displays the result of this command on common Red Hat Enterprise Linux 9 system:

    # firewall-cmd --get-service
    amanda-client bacula bacula-client dhcp dhcpv6 dhcpv6-client dns ftp
    high-availability http https imaps ipp ipp-client ipsec kerberos kpasswd
    ldap ldaps libvirt libvirt-tls mdns mountd ms-wbt mysql nfs ntp openvpn
    pmcd pmproxy pmwebapi pmwebapis pop3s postgresql proxy-dhcp radius rpc-bind
    samba samba-client smtp ssh telnet tftp tftp-client transmission-client
    vnc-server wbem-https

Finally to view the network zones that will be active after the next firewalld service reload, enter the following command as root:

    # firewall-cmd --get-service --permanent

#### Rule Install firewalld Package [ref]

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

    $ sudo dnf install firewalld

Rationale:

"Firewalld" provides an easy and effective way to block/limit remote access to the system via ports, services, and protocols. 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, non-organization-controlled network. Remote access methods include, for example, dial-up, broadband, and wireless. Red Hat Enterprise Linux 9 functionality (e.g., SSH) 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 (e.g., servers, workstations, notebook computers, smartphones, and tablets)."

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

References:

nist | CM-6(a)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000096-GPOS-00050, SRG-OS-000297-GPOS-00115, SRG-OS-000298-GPOS-00116, SRG-OS-000480-GPOS-00227, SRG-OS-000480-GPOS-00232
ism | 1409
pcidss4 | 1.2.1, 1.2
bsi | SYS.1.1.A19
cis | 4.1.2
stigref | SV-257935r1044994_rule

Remediation script ⇲

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

    dnf install firewalld

Remediation script ⇲

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

    package install firewalld

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "firewalld" ; then
        dnf install -y "firewalld"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_firewalld

    class install_firewalld {
      package { 'firewalld':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=firewalld

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-251010
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_firewalld_installed

    - name: Ensure firewalld is installed
      ansible.builtin.package:
        name: firewalld
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251010
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_firewalld_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Verify firewalld Enabled [ref]

The `firewalld` service can be enabled with the following command:

    $ sudo systemctl enable firewalld.service

Rationale: | Access control methods provide the ability to enhance system security posture by restricting services and known good IP addresses and address ranges. This prevents connections from unknown hosts and protocols.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_firewalld_enabled

References:

cis-csc | 11, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.1.3, 3.4.7
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4
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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000096-GPOS-00050, SRG-OS-000297-GPOS-00115, SRG-OS-000480-GPOS-00227, SRG-OS-000480-GPOS-00231, SRG-OS-000480-GPOS-00232
bsi | SYS.1.6.A5, SYS.1.6.A21, SYS.1.1.A19
ism | 1409
pcidss4 | 1.2.1, 1.2
cis | 4.1.2
stigref | SV-257936r1044995_rule

Remediation script ⇲

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

    service enable firewalld

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q firewalld; }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'firewalld.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'firewalld.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'firewalld.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_firewalld

    class enable_firewalld {
      service {'firewalld':
        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:
      - DISA-STIG-RHEL-09-251015
      - NIST-800-171-3.1.3
      - NIST-800-171-3.4.7
      - NIST-800-53-AC-4
      - NIST-800-53-CA-3(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_firewalld_enabled

    - name: Verify firewalld Enabled - Enable service firewalld
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Verify firewalld Enabled - Enable Service firewalld
        ansible.builtin.systemd:
          name: firewalld
          enabled: true
          state: started
          masked: false
        when:
        - '"firewalld" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251015
      - NIST-800-171-3.1.3
      - NIST-800-171-3.4.7
      - NIST-800-53-AC-4
      - NIST-800-53-CA-3(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_firewalld_enabled
      - special_service_block
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"firewalld" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["firewalld"]

Group Strengthen the Default Ruleset Group contains 1 rule

[ref] The default rules can be strengthened. The system scripts that activate the firewall rules expect them to be defined in configuration files under the `/etc/firewalld/services` and `/etc/firewalld/zones` directories.
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 `firewall-cmd` program to load in rules under the `/etc/firewalld/services` and `/etc/firewalld/zones` directories.
Instructions apply to both unless otherwise noted. Language and address conventions for regular firewalld rules are used throughout this section.
Warning: The program `firewall-config` allows additional services to penetrate the default firewall rules and automatically adjusts the `firewalld` ruleset(s).

#### Rule Firewalld Must Employ a Deny-all, Allow-by-exception Policy for Allowing Connections to Other Systems [ref]

Red Hat Enterprise Linux 9 incorporates the "firewalld" daemon, which allows for many different configurations. One of these configurations is zones. Zones can be utilized to a deny-all, allow-by-exception approach. The default "drop" zone will drop all incoming network packets unless it is explicitly allowed by the configuration file or is related to an outgoing network connection.
Rationale: | Failure to restrict network connectivity only to authorized systems permits inbound connections from malicious systems. It also permits outbound connections that may facilitate exfiltration of data.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_configured_firewalld_default_deny

References:

nist | AC-17 (1)
os-srg | SRG-OS-000297-GPOS-00115
stigref | SV-257937r1106310_rule

#### Rule Configure Firewalld to Use the Nftables Backend [ref]

Firewalld can be configured with many backends, such as nftables.
Rationale: | Nftables is modern kernel module for controlling network connections coming into a system. Utilizing the limit statement in "nftables" can help to mitigate DoS attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_firewalld-backend

References:

nist | SC-5
os-srg | SRG-OS-000420-GPOS-00186
stigref | SV-257939r1044997_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q firewalld; }; then

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

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

    cp "/etc/firewalld/firewalld.conf" "/etc/firewalld/firewalld.conf.bak"
    # Insert before the line matching the regex '^#\s*FirewallBackend'.
    line_number="$(LC_ALL=C grep -n "^#\s*FirewallBackend" "/etc/firewalld/firewalld.conf.bak" | LC_ALL=C sed 's/:.*//g')"
    if [ -z "$line_number" ]; then
        # There was no match of '^#\s*FirewallBackend', insert at
        # the end of the file.
        printf '%s\n' "FirewallBackend=nftables" >> "/etc/firewalld/firewalld.conf"
    else
        head -n "$(( line_number - 1 ))" "/etc/firewalld/firewalld.conf.bak" > "/etc/firewalld/firewalld.conf"
        printf '%s\n' "FirewallBackend=nftables" >> "/etc/firewalld/firewalld.conf"
        tail -n "+$(( line_number ))" "/etc/firewalld/firewalld.conf.bak" >> "/etc/firewalld/firewalld.conf"
    fi
    # Clean up after ourselves.
    rm "/etc/firewalld/firewalld.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:
      - DISA-STIG-RHEL-09-251030
      - NIST-800-53-SC-5
      - firewalld-backend
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Setting unquoted shell-style assignment of 'FirewallBackend' to 'nftables'
        in '/etc/firewalld/firewalld.conf'
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/firewalld/firewalld.conf
          create: true
          regexp: (?i)^\s*FirewallBackend=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/firewalld/firewalld.conf
        ansible.builtin.lineinfile:
          path: /etc/firewalld/firewalld.conf
          create: true
          regexp: (?i)^\s*FirewallBackend=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/firewalld/firewalld.conf
        ansible.builtin.lineinfile:
          path: /etc/firewalld/firewalld.conf
          create: true
          regexp: (?i)^\s*FirewallBackend=
          line: FirewallBackend=nftables
          state: present
          insertbefore: ^# FirewallBackend
          validate: /usr/bin/bash -n %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"firewalld" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251030
      - NIST-800-53-SC-5
      - firewalld-backend
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group IPSec Support Group contains 2 rules
[ref] Support for Internet Protocol Security (IPsec) is provided with Libreswan.

#### Rule Install libreswan Package [ref]

The libreswan package provides an implementation of IPsec and IKE, which permits the creation of secure tunnels over untrusted networks. The `libreswan` package can be installed with the following command:

    $ sudo dnf install libreswan

Rationale: | Providing the ability for remote users or systems to initiate a secure VPN connection protects information when it is transmitted over a wide area network.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_libreswan_installed

References:

cis-csc | 12, 15, 3, 5, 8
cobit5 | APO13.01, DSS01.04, DSS05.02, DSS05.03, DSS05.04
isa-62443-2009 | 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8
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.4, A.11.2.6, A.13.1.1, A.13.2.1, A.14.1.3, A.15.1.1, A.15.2.1, A.6.2.1, A.6.2.2
nist | CM-6(a)
nist-csf | PR.AC-3, PR.MA-2, PR.PT-4
pcidss | Req-4.1
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000120-GPOS-00061
stigref | SV-257954r1106315_rule

Remediation script ⇲

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

    dnf install libreswan

Remediation script ⇲

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

    package install libreswan

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "libreswan" ; then
        dnf install -y "libreswan"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_libreswan

    class install_libreswan {
      package { 'libreswan':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=libreswan

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-252065
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-4.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_libreswan_installed

    - name: Ensure libreswan is installed
      ansible.builtin.package:
        name: libreswan
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252065
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-4.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_libreswan_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Verify Any Configured IPSec Tunnel Connections [ref]

Libreswan provides an implementation of IPsec and IKE, which permits the creation of secure tunnels over untrusted networks. As such, IPsec can be used to circumvent certain network requirements such as filtering. Verify that if any IPsec connection (`conn`) configured in `/etc/ipsec.conf` and `/etc/ipsec.d` exists is an approved organizational connection.
Warning: Automatic remediation of this control is not available due to the unique requirements of each system.

Rationale: | IP tunneling mechanisms can be used to bypass network filtering.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_libreswan_approved_tunnels

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
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.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 | AC-17(a), MA-4(6), CM-6(a), AC-4, SC-8
nist-csf | DE.AE-1, ID.AM-3, PR.AC-5, PR.DS-5, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257950r1045006_rule

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
stigref | SV-257971r1106444_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254010
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254010
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254010
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.all.accept_ra%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_all_accept_ra.conf
            overwrite: true

#### 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
stigref | SV-257972r1106446_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254015
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254015
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254015
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.all.accept_redirects%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_all_accept_redirects.conf
            overwrite: true

#### 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
stigref | SV-257973r1106448_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254020
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254020
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254020
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.all.accept_source_route%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_all_accept_source_route.conf
            overwrite: true

#### 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
stigref | SV-257974r1106450_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254025
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254025
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254025
      - 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
stigref | SV-257975r1106452_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254030
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254030
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254030
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.default.accept_ra%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_default_accept_ra.conf
            overwrite: true

#### 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
stigref | SV-257976r1106454_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254035
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254035
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254035
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.default.accept_redirects%20%3D%200%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_default_accept_redirects.conf
            overwrite: true

#### Rule Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces by Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_source_route` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_source_route=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_source_route = 0

Rationale:

Source-routed packets allow the source of the packet to suggest routers forward the packet along a different path than configured on the router, which can be used to bypass network security measures. This requirement applies only to the forwarding of source-routerd traffic, such as when IPv6 forwarding is enabled and the system is functioning as a router. Accepting source-routed packets in the IPv6 protocol has few legitimate uses. It should be disabled unless it is absolutely required.

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

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 4, 6, 8, 9
cobit5 | APO01.06, APO13.01, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), CM-6(b), CM-6.1(iv)
nist-csf | DE.AE-1, ID.AM-3, PR.AC-5, PR.DS-5, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R13
pcidss4 | 1.4.2, 1.4
cis | 3.3.8
stigref | SV-257977r1106456_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-254040
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254040
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-254040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-254040
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv6.conf.default.accept_source_route%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv6_conf_default_accept_source_route.conf
            overwrite: true

Group Kernel Parameters Which Affect Networking Group contains 2 groups and 14 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 12 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
stigref | SV-257958r1106319_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253015
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253015
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253015
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253015
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.all.accept_redirects%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_all_accept_redirects.conf
            overwrite: true

#### 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
stigref | SV-257959r1102024_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253020
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253020
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253020
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253020
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.all.accept_source_route%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_all_accept_source_route.conf
            overwrite: true

#### Rule Disable Kernel Parameter for IPv4 Forwarding on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.forwarding` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.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.ipv4.conf.all.forwarding = 0

Warning: There might be cases when certain applications can systematically override this option. One such case is Libvirt; a toolkit for managing of virtualization platforms. By default, Libvirt requires IP forwarding to be enabled to facilitate network communication between the virtualization host and guest machines. It enables IP forwarding after every reboot.

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_ipv4_conf_all_forwarding

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257970r1106442_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of net.ipv4.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; 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.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.ipv4.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_ipv4_conf_all_forwarding_value='0'

    #
    # Set runtime for net.ipv4.conf.all.forwarding
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.forwarding="$sysctl_net_ipv4_conf_all_forwarding_value"
    fi

    #
    # If net.ipv4.conf.all.forwarding present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.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.ipv4.conf.all.forwarding")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_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.ipv4.conf.all.forwarding\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding
    - name: XCCDF Value sysctl_net_ipv4_conf_all_forwarding_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_forwarding_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for IPv4 Forwarding 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding

    - name: Disable Kernel Parameter for IPv4 Forwarding on all IPv4 Interfaces - Find
        all files that contain net.ipv4.conf.all.forwarding
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.forwarding\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding

    - name: Disable Kernel Parameter for IPv4 Forwarding on all IPv4 Interfaces - Find
        all files that set net.ipv4.conf.all.forwarding to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.forwarding\s*=\s*{{ sysctl_net_ipv4_conf_all_forwarding_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding

    - name: Disable Kernel Parameter for IPv4 Forwarding on all IPv4 Interfaces - Comment
        out any occurrences of net.ipv4.conf.all.forwarding from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.forwarding
        replace: '#net.ipv4.conf.all.forwarding'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding

    - name: Disable Kernel Parameter for IPv4 Forwarding on all IPv4 Interfaces - Ensure
        sysctl net.ipv4.conf.all.forwarding is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.forwarding
        value: '{{ sysctl_net_ipv4_conf_all_forwarding_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253075
      - NIST-800-53-CM-6(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_forwarding

#### 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
stigref | SV-257960r1106321_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253025
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253025
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253025
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253025
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.all.log_martians%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_all_log_martians.conf
            overwrite: true

#### Rule Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.rp_filter` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.rp_filter=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.rp_filter = 1

Rationale: | Enabling reverse path filtering drops packets with source addresses that should not have been able to be received on the interface they were received on. It should not be used on systems which are routers for complicated networks, but is helpful for end hosts and routers serving small networks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_rp_filter

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 2, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4
cis | 3.3.7
stigref | SV-257962r1106437_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253035
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253035
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253035
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253035
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.all.rp_filter%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_all_rp_filter.conf
            overwrite: true

#### Rule Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.default.accept_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.accept_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.accept_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages modify the host's route table and are unauthenticated. An illicit ICMP redirect message could result in a man-in-the-middle attack. This feature of the IPv4 protocol has few legitimate uses. It should be disabled unless absolutely required.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_accept_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4
cis | 3.3.5
stigref | SV-257963r1106328_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253040
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253040
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253040
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.default.accept_redirects%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_default_accept_redirects.conf
            overwrite: true

#### 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
stigref | SV-257964r1106438_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253045
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253045
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253045
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253045
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253045
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253045
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.default.accept_source_route%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_default_accept_source_route.conf
            overwrite: true

#### 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
stigref | SV-257961r1106323_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253030
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253030
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253030
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253030
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.default.log_martians%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_default_log_martians.conf
            overwrite: true

#### 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
stigref | SV-257965r1106333_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253050
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253050
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253050
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253050
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253050
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253050
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.default.rp_filter%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_default_rp_filter.conf
            overwrite: true

#### 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
pcidss4 | 1.4.2, 1.4
cis | 3.3.4
stigref | SV-257966r1106440_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253055
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253055
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253055
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253055
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253055
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253055
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.icmp_echo_ignore_broadcasts%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_icmp_echo_ignore_broadcasts.conf
            overwrite: true

#### Rule Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.icmp_ignore_bogus_error_responses` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.icmp_ignore_bogus_error_responses = 1

Rationale: | Ignoring bogus ICMP error responses reduces log size, although some activity would not be logged.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_icmp_ignore_bogus_error_responses

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 7, 8, 9
cobit5 | APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.05, DSS05.07, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.9.1.2
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5
nist-csf | DE.CM-1, PR.DS-4, PR.IP-1, PR.PT-3
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.2, 1.4
cis | 3.3.3
stigref | SV-257967r1106337_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-253060
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253060
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253060
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253060
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-253060
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-253060
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.icmp_ignore_bogus_error_responses%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_icmp_ignore_bogus_error_responses.conf
            overwrite: true

#### Rule Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces [ref]

To set the runtime status of the `net.ipv4.tcp_syncookies` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.tcp_syncookies=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.tcp_syncookies = 1

Rationale:

A TCP SYN flood attack can cause a denial of service by filling a system's TCP connection table with connections in the SYN_RCVD state. Syncookies can be used to track a connection when a subsequent ACK is received, verifying the initiator is attempting a valid connection and is not a flood source. This feature is activated when a flood condition is detected, and enables the system to continue servicing valid connection requests.

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

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 2, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), SC-5(1), SC-5(2), SC-5(3)(a), CM-6(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.PT-4
pcidss | Req-1.4.1
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000420-GPOS-00186, SRG-OS-000142-GPOS-00071
anssi | R12
pcidss4 | 1.4.3, 1.4
cis | 3.3.10
stigref | SV-257957r1106317_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253010
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253010
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253010
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.tcp_syncookies%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_tcp_syncookies.conf
            overwrite: true

Group Network Parameters for Hosts Only Group contains 2 rules
[ref] If the system is not going to be used as a router, then setting certain kernel parameters ensure that the host will not perform routing of network traffic.

#### Rule Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.send_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.send_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.send_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages contain information from the system's route table possibly revealing portions of the network topology. The ability to send ICMP redirects is only appropriate for systems acting as routers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_send_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.5, 1.4
cis | 3.3.2
stigref | SV-257968r1106339_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253065
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253065
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253065
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253065
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253065
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253065
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.all.send_redirects%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_all_send_redirects.conf
            overwrite: true

#### Rule Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.send_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.send_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.send_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages contain information from the system's route table possibly revealing portions of the network topology. The ability to send ICMP redirects is only appropriate for systems acting as routers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_send_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.5, 1.4
cis | 3.3.2
stigref | SV-257969r991589_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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
      - DISA-STIG-RHEL-09-253070
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253070
      - 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:
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-253070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - DISA-STIG-RHEL-09-253070
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.ipv4.conf.default.send_redirects%3D0%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_ipv4_conf_default_send_redirects.conf
            overwrite: true

Group Uncommon Network Protocols Group contains 5 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 ATM Support [ref]

The Asynchronous Transfer Mode (ATM) is a protocol operating on network, data link, and physical layers, based on virtual circuits and virtual paths. To configure the system to prevent the `atm` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/atm.conf`:

    install atm /bin/false

This entry will cause a non-zero return value during a `atm` 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 atm /bin/true

Rationale: | Disabling ATM protects the system against exploitation of any flaws in its implementation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_atm_disabled

References:

nist | AC-18
os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
stigref | SV-257804r1044853_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if LC_ALL=C grep -q -m 1 "^install atm" /etc/modprobe.d/atm.conf ; then

    	sed -i 's#^install atm.*#install atm /bin/false#g' /etc/modprobe.d/atm.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/atm.conf
    	echo "install atm /bin/false" >> /etc/modprobe.d/atm.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist atm$" /etc/modprobe.d/atm.conf ; then
    	echo "blacklist atm" >> /etc/modprobe.d/atm.conf
    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:
      - DISA-STIG-RHEL-09-213045
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_atm_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'atm' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/atm.conf
        regexp: install\s+atm
        line: install atm /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213045
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_atm_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'atm' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/atm.conf
        regexp: ^blacklist atm$
        line: blacklist atm
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213045
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_atm_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20atm%20/bin/false%0Ablacklist%20atm%0A
            mode: 0644
            path: /etc/modprobe.d/atm.conf
            overwrite: true

#### Rule Disable CAN Support [ref]

The Controller Area Network (CAN) is a serial communications protocol which was initially developed for automotive and is now also used in marine, industrial, and medical applications. To configure the system to prevent the `can` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/can.conf`:

    install can /bin/false

This entry will cause a non-zero return value during a `can` 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 can /bin/true

Rationale: | Disabling CAN protects the system against exploitation of any flaws in its implementation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_can_disabled

References:

nist | AC-18
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000480-GPOS-00227
stigref | SV-257805r1044856_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if LC_ALL=C grep -q -m 1 "^install can" /etc/modprobe.d/can.conf ; then

    	sed -i 's#^install can.*#install can /bin/false#g' /etc/modprobe.d/can.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/can.conf
    	echo "install can /bin/false" >> /etc/modprobe.d/can.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist can$" /etc/modprobe.d/can.conf ; then
    	echo "blacklist can" >> /etc/modprobe.d/can.conf
    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:
      - DISA-STIG-RHEL-09-213050
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_can_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'can' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/can.conf
        regexp: install\s+can
        line: install can /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213050
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_can_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'can' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/can.conf
        regexp: ^blacklist can$
        line: blacklist can
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213050
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_can_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20can%20/bin/false%0Ablacklist%20can%0A
            mode: 0644
            path: /etc/modprobe.d/can.conf
            overwrite: true

#### Rule Disable IEEE 1394 (FireWire) Support [ref]

The IEEE 1394 (FireWire) is a serial bus standard for high-speed real-time communication. To configure the system to prevent the `firewire-core` kernel module from being loaded, add the following line to the file `/etc/modprobe.d/firewire-core.conf`:

    install firewire-core /bin/false

This entry will cause a non-zero return value during a `firewire-core` 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 firewire-core /bin/true

Rationale: | Disabling FireWire protects the system against exploitation of any flaws in its implementation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_firewire-core_disabled

References:

nist | AC-18
os-srg | SRG-OS-000095-GPOS-00049
bsi | SYS.1.1.A5
stigref | SV-257806r1044859_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if LC_ALL=C grep -q -m 1 "^install firewire-core" /etc/modprobe.d/firewire-core.conf ; then

    	sed -i 's#^install firewire-core.*#install firewire-core /bin/false#g' /etc/modprobe.d/firewire-core.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/firewire-core.conf
    	echo "install firewire-core /bin/false" >> /etc/modprobe.d/firewire-core.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist firewire-core$" /etc/modprobe.d/firewire-core.conf ; then
    	echo "blacklist firewire-core" >> /etc/modprobe.d/firewire-core.conf
    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:
      - DISA-STIG-RHEL-09-213055
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_firewire-core_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'firewire-core' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/firewire-core.conf
        regexp: install\s+firewire-core
        line: install firewire-core /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213055
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_firewire-core_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'firewire-core' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/firewire-core.conf
        regexp: ^blacklist firewire-core$
        line: blacklist firewire-core
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213055
      - NIST-800-53-AC-18
      - disable_strategy
      - kernel_module_firewire-core_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20firewire-core%20/bin/false%0Ablacklist%20firewire-core%0A
            mode: 0644
            path: /etc/modprobe.d/firewire-core.conf
            overwrite: true

#### 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
pcidss4 | 1.4.2, 1.4
cis | 3.2.4
stigref | SV-257807r1044862_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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

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
      - DISA-STIG-RHEL-09-213060
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - kernel_module_sctp_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'sctp' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/sctp.conf
        regexp: install\s+sctp
        line: install sctp /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1
      - DISA-STIG-RHEL-09-213060
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - kernel_module_sctp_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'sctp' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/sctp.conf
        regexp: ^blacklist sctp$
        line: blacklist sctp
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1
      - DISA-STIG-RHEL-09-213060
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - kernel_module_sctp_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20sctp%20/bin/false%0Ablacklist%20sctp%0A
            mode: 0644
            path: /etc/modprobe.d/sctp.conf
            overwrite: true

#### 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
stigref | SV-257808r1044865_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-213065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_tipc_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'tipc' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/tipc.conf
        regexp: install\s+tipc
        line: install tipc /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_tipc_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'tipc' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/tipc.conf
        regexp: ^blacklist tipc$
        line: blacklist tipc
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_tipc_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20tipc%20/bin/false%0Ablacklist%20tipc%0A
            mode: 0644
            path: /etc/modprobe.d/tipc.conf
            overwrite: true

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 Kernel Module [ref]

The kernel's module loading system can be configured to prevent loading of the Bluetooth module. Add the following to the appropriate `/etc/modprobe.d` configuration file to prevent the loading of the Bluetooth module:

    install bluetooth /bin/true

Rationale: | If Bluetooth functionality must be disabled, preventing the kernel from loading the kernel module provides an additional safeguard against its activation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_module_bluetooth_disabled

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cjis | 5.13.1.3
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
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000095-GPOS-00049, SRG-OS-000300-GPOS-00118
bsi | SYS.1.1.A6
stigref | SV-258039r1045131_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if LC_ALL=C grep -q -m 1 "^install bluetooth" /etc/modprobe.d/bluetooth.conf ; then

    	sed -i 's#^install bluetooth.*#install bluetooth /bin/false#g' /etc/modprobe.d/bluetooth.conf
    else
    	echo -e "\n# Disable per security requirements" >> /etc/modprobe.d/bluetooth.conf
    	echo "install bluetooth /bin/false" >> /etc/modprobe.d/bluetooth.conf
    fi

    if ! LC_ALL=C grep -q -m 1 "^blacklist bluetooth$" /etc/modprobe.d/bluetooth.conf ; then
    	echo "blacklist bluetooth" >> /etc/modprobe.d/bluetooth.conf
    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.13.1.3
      - DISA-STIG-RHEL-09-291035
      - 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
      - kernel_module_bluetooth_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'bluetooth' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/bluetooth.conf
        regexp: install\s+bluetooth
        line: install bluetooth /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.13.1.3
      - DISA-STIG-RHEL-09-291035
      - 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
      - kernel_module_bluetooth_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'bluetooth' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/bluetooth.conf
        regexp: ^blacklist bluetooth$
        line: blacklist bluetooth
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.13.1.3
      - DISA-STIG-RHEL-09-291035
      - 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
      - kernel_module_bluetooth_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20bluetooth%20/bin/false%0Ablacklist%20bluetooth%0A
            mode: 0644
            path: /etc/modprobe.d/bluetooth.conf
            overwrite: true

#### 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
ism | 1315, 1319
pcidss4 | 1.3.3, 1.3
bsi | SYS.1.1.A6
cis | 3.1.2
stigref | SV-258040r991568_rule

Remediation Shell script ⇲

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

    if ! rpm -q --quiet "NetworkManager" ; then
        dnf install -y "NetworkManager"
    fi

    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:
      - DISA-STIG-RHEL-09-291040
      - 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:
      - DISA-STIG-RHEL-09-291040
      - 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:
      - DISA-STIG-RHEL-09-291040
      - 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:
      - DISA-STIG-RHEL-09-291040
      - 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

Group Network Manager Group contains 1 rule
[ref] The NetworkManager daemon configures a variety of network connections. This section discusses how to configure NetworkManager.

#### Rule NetworkManager DNS Mode Must Be Must Configured [ref]

The DNS processing mode in NetworkManager describes how DNS is processed on the system. Depending the mode some changes the system's DNS may not be respected.
Rationale: | To ensure that DNS resolver settings are respected, a DNS mode in NetworkManager must be configured.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_networkmanager_dns_mode

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257949r1014841_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q NetworkManager; then

    var_networkmanager_dns_mode='default'

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/NetworkManager/conf.d/complianceascode_hardening.conf /etc/NetworkManager/conf.d/*.conf /etc/NetworkManager/NetworkManager.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[main\]([^\n\[]*\n+)+?[[:space:]]*dns" "$f"; then
            if ! grep -qPz "dns=$var_networkmanager_dns_mode" "$f"; then

                sed -i "s/dns[^(\n)]*/dns=$var_networkmanager_dns_mode/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[main\]" "$f"; then

                sed -i "/[[:space:]]*\[main\]/a dns=$var_networkmanager_dns_mode" "$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 "/etc/NetworkManager/conf.d/complianceascode_hardening.conf /etc/NetworkManager/conf.d/*.conf /etc/NetworkManager/NetworkManager.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[main]\ndns=$var_networkmanager_dns_mode" >> "$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:
      - DISA-STIG-RHEL-09-252040
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - networkmanager_dns_mode
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_networkmanager_dns_mode # promote to variable
      set_fact:
        var_networkmanager_dns_mode: !!str default
      tags:
        - always

    - name: NetworkManager DNS Mode Must Be Must Configured - Search for a section in
        files
      ansible.builtin.find:
        paths: '{{item.path}}'
        patterns: '{{item.pattern}}'
        contains: ^\s*\[main\]
        read_whole_file: true
        use_regex: true
      register: systemd_dropin_files_with_section
      loop:
      - path: '{{ ''/etc/NetworkManager/NetworkManager.conf'' | dirname }}'
        pattern: '{{ ''/etc/NetworkManager/NetworkManager.conf'' | basename | regex_escape
          }}'
      - path: /etc/NetworkManager/conf.d
        pattern: .*\.conf
      when: '"NetworkManager" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252040
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - networkmanager_dns_mode
      - no_reboot_needed
      - restrict_strategy

    - name: NetworkManager DNS Mode Must Be Must Configured - Count number of files which
        contain the correct section
      ansible.builtin.set_fact:
        count_of_systemd_dropin_files_with_section: '{{systemd_dropin_files_with_section.results
          | map(attribute=''matched'') | list | map(''int'') | sum}}'
      when: '"NetworkManager" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252040
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - networkmanager_dns_mode
      - no_reboot_needed
      - restrict_strategy

    - name: NetworkManager DNS Mode Must Be Must Configured - Add missing configuration
        to correct section
      community.general.ini_file:
        path: '{{item}}'
        section: main
        option: dns
        value: '{{var_networkmanager_dns_mode}}'
        state: present
        no_extra_spaces: true
      when:
      - '"NetworkManager" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int > 0
      loop: '{{systemd_dropin_files_with_section.results | sum(attribute=''files'', start=[])
        | map(attribute=''path'') | list }}'
      tags:
      - DISA-STIG-RHEL-09-252040
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - networkmanager_dns_mode
      - no_reboot_needed
      - restrict_strategy

    - name: NetworkManager DNS Mode Must Be Must Configured - Add configuration to new
        remediation file
      community.general.ini_file:
        path: /etc/NetworkManager/conf.d/complianceascode_hardening.conf
        section: main
        option: dns
        value: '{{var_networkmanager_dns_mode}}'
        state: present
        no_extra_spaces: true
        create: true
      when:
      - '"NetworkManager" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int == 0
      tags:
      - DISA-STIG-RHEL-09-252040
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - networkmanager_dns_mode
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure Multiple DNS Servers in /etc/resolv.conf [ref]

Determine whether the system is using local or DNS name resolution with the following command:

    $ sudo grep hosts /etc/nsswitch.conf
    hosts: files dns

If the DNS entry is missing from the host's line in the "/etc/nsswitch.conf" file, the "/etc/resolv.conf" file must be empty. Verify the "/etc/resolv.conf" file is empty with the following command:

    $ sudo ls -al /etc/resolv.conf
    -rw-r--r-- 1 root root 0 Aug 19 08:31 resolv.conf

If the DNS entry is found on the host's line of the "/etc/nsswitch.conf" file, then verify the following:
Multiple Domain Name System (DNS) Servers should be configured in `/etc/resolv.conf`. This provides redundant name resolution services in the event that a domain server crashes. To configure the system to contain as least `2` DNS servers, add a corresponding `nameserver ip_address` entry in `/etc/resolv.conf` for each DNS server where ip_address is the IP address of a valid DNS server. For example:

    search example.com
    nameserver 192.168.0.1
    nameserver 192.168.0.2

Warning: This rule doesn't come with a remediation, the IP addresses of local authoritative name servers need to be added by the administrator.

Rationale: | To provide availability for name resolution services, multiple redundant name servers are mandated. A failure in name resolution could lead to the failure of security functions requiring name resolution, which may include time synchronization, centralized authentication, and remote system logging.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_network_configure_name_resolution

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 | SC-20(a), CM-6(a)
nist-csf | PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257948r1045004_rule

#### Rule Ensure System is Not Acting as a Network Sniffer [ref]

The system should not be acting as a network sniffer, which can capture all traffic on the network to which it is connected. Run the following to determine if any interface is running in promiscuous mode:

    $ ip link | grep PROMISC

Promiscuous mode of an interface can be disabled with the following command:

    $ sudo ip link set dev device_name multicast off promisc off

Rationale:

Network interfaces in promiscuous mode allow for the capture of all network traffic visible to the system. If unauthorized individuals can access these applications, it may allow them to collect information such as logon IDs, passwords, and key exchanges between systems.
If the system is being used to perform a network troubleshooting function, the use of these tools must be documented with the Information Systems Security Manager (ISSM) and restricted to only authorized personnel.

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

References:

cis-csc | 1, 11, 14, 3, 9
cobit5 | APO11.06, APO12.06, BAI03.10, BAI09.01, BAI09.02, BAI09.03, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.05, DSS04.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.2.3.4, 4.3.3.3.7, 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.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 7.6, SR 7.8
iso27001-2013 | A.11.1.2, A.11.2.4, A.11.2.5, A.11.2.6, 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.16.1.6, A.8.1.1, A.8.1.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a), CM-7(2), MA-3
nist-csf | DE.DP-5, ID.AM-1, PR.IP-1, PR.MA-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
ism | 1409
pcidss4 | 1.4.5, 1.4
stigref | SV-257941r991589_rule

Remediation Shell script ⇲

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

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

    for interface in $(ip -o link show | cut -d ":" -f 2); do
        ip link set dev $interface multicast off promisc off
    done

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

Remediation Ansible snippet ⇲

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

    - name: Ensure System is Not Acting as a Network Sniffer - Gather network interfaces
      ansible.builtin.command:
        cmd: ip -o link show
      register: network_interfaces
      when: ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      tags:
      - DISA-STIG-RHEL-09-251040
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(2)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MA-3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - low_complexity
      - low_disruption
      - medium_severity
      - network_sniffer_disabled
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure System is Not Acting as a Network Sniffer - Disable promiscuous mode
      ansible.builtin.command:
        cmd: ip link set dev {{ (item.split(':')[1] | trim).split('@')[0] }} multicast
          off promisc off
      loop: '{{ network_interfaces.stdout_lines }}'
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - network_interfaces.stdout_lines is defined and item.split(':') | length >= 3
      tags:
      - DISA-STIG-RHEL-09-251040
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(2)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MA-3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - low_complexity
      - low_disruption
      - medium_severity
      - network_sniffer_disabled
      - no_reboot_needed
      - restrict_strategy

Group File Permissions and Masks Group contains 11 groups and 91 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 Red Hat Enterprise Linux 9 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 4 groups and 46 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 24 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.4
stigref | SV-257901r991589_rule

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:
      - DISA-STIG-RHEL-09-232105
      - 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:
      - DISA-STIG-RHEL-09-232105
      - 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:
      - DISA-STIG-RHEL-09-232105
      - 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 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_groupowner_backup_etc_gshadow

References:

nist | AC-6 (1)
pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
bsi | SYS.1.3.A14
cis | 7.1.8
stigref | SV-257905r991589_rule

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/gshadow-" | grep -E -w -q "0"; 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: '0'
      tags:
      - DISA-STIG-RHEL-09-232125
      - 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:
      - DISA-STIG-RHEL-09-232125
      - 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:
      - DISA-STIG-RHEL-09-232125
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.2
stigref | SV-257909r991589_rule

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:
      - DISA-STIG-RHEL-09-232145
      - 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:
      - DISA-STIG-RHEL-09-232145
      - 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:
      - DISA-STIG-RHEL-09-232145
      - 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 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_groupowner_backup_etc_shadow

References:

pcidss | Req-8.7
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.6
stigref | SV-257913r991589_rule

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/shadow-" | grep -E -w -q "0"; 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: '0'
      tags:
      - DISA-STIG-RHEL-09-232165
      - 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:
      - DISA-STIG-RHEL-09-232165
      - 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:
      - DISA-STIG-RHEL-09-232165
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.3
stigref | SV-257899r991589_rule

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
      - DISA-STIG-RHEL-09-232095
      - 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
      - DISA-STIG-RHEL-09-232095
      - 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
      - DISA-STIG-RHEL-09-232095
      - 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 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_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
bsi | SYS.1.3.A14
cis | 7.1.7
stigref | SV-257903r991589_rule

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/gshadow" | grep -E -w -q "0"; 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: '0'
      tags:
      - DISA-STIG-RHEL-09-232115
      - 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:
      - DISA-STIG-RHEL-09-232115
      - 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:
      - DISA-STIG-RHEL-09-232115
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns passwd File [ref]

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

    $ sudo chgrp root /etc/passwd

Rationale: | The `/etc/passwd` file contains information about the users that are configured on the system. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.1
stigref | SV-257907r991589_rule

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
      - DISA-STIG-RHEL-09-232135
      - 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
      - DISA-STIG-RHEL-09-232135
      - 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
      - DISA-STIG-RHEL-09-232135
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns shadow File [ref]

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

    $ sudo chgrp root /etc/shadow

Rationale: | The `/etc/shadow` file stores password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.5
stigref | SV-257911r991589_rule

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/shadow" | grep -E -w -q "0"; 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: '0'
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-232155
      - 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
      - DISA-STIG-RHEL-09-232155
      - 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
      - DISA-STIG-RHEL-09-232155
      - 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 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.4
stigref | SV-257900r991589_rule

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:
      - DISA-STIG-RHEL-09-232100
      - 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:
      - DISA-STIG-RHEL-09-232100
      - 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:
      - DISA-STIG-RHEL-09-232100
      - 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
bsi | SYS.1.3.A14
cis | 7.1.8
stigref | SV-257904r991589_rule

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:
      - DISA-STIG-RHEL-09-232120
      - 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:
      - DISA-STIG-RHEL-09-232120
      - 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:
      - DISA-STIG-RHEL-09-232120
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.2
stigref | SV-257908r991589_rule

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:
      - DISA-STIG-RHEL-09-232140
      - 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:
      - DISA-STIG-RHEL-09-232140
      - 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:
      - DISA-STIG-RHEL-09-232140
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.6
stigref | SV-257912r991589_rule

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:
      - DISA-STIG-RHEL-09-232160
      - 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:
      - DISA-STIG-RHEL-09-232160
      - 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:
      - DISA-STIG-RHEL-09-232160
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.3
stigref | SV-257898r991589_rule

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
      - DISA-STIG-RHEL-09-232090
      - 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
      - DISA-STIG-RHEL-09-232090
      - 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
      - DISA-STIG-RHEL-09-232090
      - 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
bsi | SYS.1.3.A14
cis | 7.1.7
stigref | SV-257902r991589_rule

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:
      - DISA-STIG-RHEL-09-232110
      - 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:
      - DISA-STIG-RHEL-09-232110
      - 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:
      - DISA-STIG-RHEL-09-232110
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns passwd File [ref]

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

    $ sudo chown root /etc/passwd

Rationale: | The `/etc/passwd` file contains information about the users that are configured on the system. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.1
stigref | SV-257906r991589_rule

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
      - DISA-STIG-RHEL-09-232130
      - 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
      - DISA-STIG-RHEL-09-232130
      - 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
      - DISA-STIG-RHEL-09-232130
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns shadow File [ref]

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

    $ sudo chown root /etc/shadow

Rationale: | The `/etc/shadow` file contains the list of local system accounts and stores password hashes. Protection of this file is critical for system security. Failure to give ownership of this file to root provides the designated owner with access to sensitive information which could weaken the system security posture.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.5
stigref | SV-257910r991589_rule

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
      - DISA-STIG-RHEL-09-232150
      - 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
      - DISA-STIG-RHEL-09-232150
      - 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
      - DISA-STIG-RHEL-09-232150
      - 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 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.4
stigref | SV-257892r991589_rule

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:
      - DISA-STIG-RHEL-09-232060
      - 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:
      - DISA-STIG-RHEL-09-232060
      - 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 0000 /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
bsi | SYS.1.3.A14
cis | 7.1.8
stigref | SV-257894r991589_rule

Remediation Shell script ⇲

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

    chmod u-xwrs,g-xwrs,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:
      - DISA-STIG-RHEL-09-232070
      - 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-xwrs,g-xwrs,o-xwrt on /etc/gshadow-
      ansible.builtin.file:
        path: /etc/gshadow-
        mode: u-xwrs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232070
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.2
stigref | SV-257896r991589_rule

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:
      - DISA-STIG-RHEL-09-232080
      - 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:
      - DISA-STIG-RHEL-09-232080
      - 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 0000 /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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.6
stigref | SV-257897r991589_rule

Remediation Shell script ⇲

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

    chmod u-xwrs,g-xwrs,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:
      - DISA-STIG-RHEL-09-232085
      - 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-xwrs,g-xwrs,o-xwrt on /etc/shadow-
      ansible.builtin.file:
        path: /etc/shadow-
        mode: u-xwrs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232085
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.3
stigref | SV-257891r991589_rule

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
      - DISA-STIG-RHEL-09-232055
      - 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
      - DISA-STIG-RHEL-09-232055
      - 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 0000 /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
bsi | SYS.1.3.A14
cis | 7.1.7
stigref | SV-257893r991589_rule

Remediation Shell script ⇲

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

    chmod u-xwrs,g-xwrs,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:
      - DISA-STIG-RHEL-09-232065
      - 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-xwrs,g-xwrs,o-xwrt on /etc/gshadow
      ansible.builtin.file:
        path: /etc/gshadow
        mode: u-xwrs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232065
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on passwd File [ref]

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

    $ sudo chmod 0644 /etc/passwd

Rationale: | If the `/etc/passwd` file is writable by a group-owner or the world the risk of its compromise is increased. The file contains the list of accounts on the system and associated information, and protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.1
stigref | SV-257895r991589_rule

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
      - DISA-STIG-RHEL-09-232075
      - 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
      - DISA-STIG-RHEL-09-232075
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on shadow File [ref]

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

    $ sudo chmod 0000 /etc/shadow

Rationale: | The `/etc/shadow` file contains the list of local system accounts and stores password hashes. Protection of this file is critical for system security. Failure to give ownership of this file to root provides the designated owner with access to sensitive information which could weaken the system security posture.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.5
stigref | SV-257934r991589_rule

Remediation Shell script ⇲

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

    chmod u-xwrs,g-xwrs,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
      - DISA-STIG-RHEL-09-232270
      - 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-xwrs,g-xwrs,o-xwrt on /etc/shadow
      ansible.builtin.file:
        path: /etc/shadow
        mode: u-xwrs,g-xwrs,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - DISA-STIG-RHEL-09-232270
      - 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

Group Verify Permissions on Files within /var/log Directory Group contains 6 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 Directory [ref]

To properly set the group owner of `/var/log`, run the command:

    $ sudo chgrp root /var/log

Rationale: | The `/var/log` directory contains files with 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

References:

os-srg | SRG-OS-000206-GPOS-00084
app-srg-ctr | SRG-APP-000118-CTR-000240
stigref | SV-257915r1044971_rule

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
    find -P /var/log/ -maxdepth 0 -type d  ! -group 0 -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_groupowner_var_log_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_var_log_newgroup: '0'
      tags:
      - DISA-STIG-RHEL-09-232175
      - configure_strategy
      - file_groupowner_var_log
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /var/log/
      ansible.builtin.file:
        path: /var/log/
        follow: false
        state: directory
        group: '{{ file_groupowner_var_log_newgroup }}'
      tags:
      - DISA-STIG-RHEL-09-232175
      - configure_strategy
      - file_groupowner_var_log
      - 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
stigref | SV-257917r1101914_rule

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:
      - DISA-STIG-RHEL-09-232185
      - 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:
      - DISA-STIG-RHEL-09-232185
      - 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:
      - DISA-STIG-RHEL-09-232185
      - configure_strategy
      - file_groupowner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /var/log Directory [ref]

To properly set the owner of `/var/log`, run the command:

    $ sudo chown root /var/log

Rationale: | The `/var/log` directory contains files with 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

References:

os-srg | SRG-OS-000206-GPOS-00084
app-srg-ctr | SRG-APP-000118-CTR-000240
stigref | SV-257914r1044969_rule

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 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_owner_var_log_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_var_log_newown: '0'
      tags:
      - DISA-STIG-RHEL-09-232170
      - configure_strategy
      - file_owner_var_log
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /var/log/
      ansible.builtin.file:
        path: /var/log/
        follow: false
        state: directory
        owner: '{{ file_owner_var_log_newown }}'
      tags:
      - DISA-STIG-RHEL-09-232170
      - configure_strategy
      - file_owner_var_log
      - 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
stigref | SV-257916r1101916_rule

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:
      - DISA-STIG-RHEL-09-232180
      - 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:
      - DISA-STIG-RHEL-09-232180
      - 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:
      - DISA-STIG-RHEL-09-232180
      - configure_strategy
      - file_owner_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /var/log Directory [ref]

To properly set the permissions of `/var/log`, run the command:

    $ sudo chmod 0755 /var/log

Rationale: | The `/var/log` directory contains files with 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

References:

os-srg | SRG-OS-000206-GPOS-00084
app-srg-ctr | SRG-APP-000118-CTR-000240
stigref | SV-257885r1044953_rule

Remediation Shell script ⇲

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

    find -H /var/log/ -maxdepth 0 -perm /u+s,g+ws,o+wt -type d -exec chmod u-s,g-ws,o-wt {} \;

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 0 -perm /u+s,g+ws,o+wt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232025
      - configure_strategy
      - file_permissions_var_log
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /var/log/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-ws,o-wt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232025
      - configure_strategy
      - file_permissions_var_log
      - 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
stigref | SV-257886r1044955_rule

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:
      - DISA-STIG-RHEL-09-232030
      - 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:
      - DISA-STIG-RHEL-09-232030
      - configure_strategy
      - file_permissions_var_log_messages
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Verify File Permissions Within Some Important Directories Group contains 9 rules
[ref] Some directories contain files whose confidentiality or integrity is notably important and may also be susceptible to misconfiguration over time, particularly if unpackaged software is installed. As such, an argument exists to verify that files' permissions within these directories remain configured correctly and restrictively.

#### Rule Verify that Shared Library Directories Have Root Group Ownership [ref]

System-wide shared library files, which are linked to executables during process load time or run time, are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

Kernel modules, which can be added to the kernel during runtime, are also stored in `/lib/modules`. All files in these directories should be group-owned by the `root` user. If the directories, is found to be owned by a user other than root correct its ownership with the following command:

    $ sudo chgrp root DIR

Rationale: | Files from shared library directories are loaded into the address space of processes (including privileged ones) or of the kernel itself at runtime. Proper ownership of library directories is necessary to protect the integrity of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_group_ownership_library_dirs

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
stigref | SV-257923r1044991_rule

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
    find -P /lib/  -type d  ! -group 0 -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /lib64/  -type d  ! -group 0 -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /usr/lib/  -type d  ! -group 0 -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /usr/lib64/  -type d  ! -group 0 -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the dir_group_ownership_library_dirs_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        dir_group_ownership_library_dirs_newgroup: '0'
      tags:
      - DISA-STIG-RHEL-09-232215
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_group_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /lib/ recursively
      ansible.builtin.file:
        path: /lib/
        follow: false
        state: directory
        recurse: true
        group: '{{ dir_group_ownership_library_dirs_newgroup }}'
      tags:
      - DISA-STIG-RHEL-09-232215
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_group_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /lib64/ recursively
      ansible.builtin.file:
        path: /lib64/
        follow: false
        state: directory
        recurse: true
        group: '{{ dir_group_ownership_library_dirs_newgroup }}'
      tags:
      - DISA-STIG-RHEL-09-232215
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_group_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /usr/lib/ recursively
      ansible.builtin.file:
        path: /usr/lib/
        follow: false
        state: directory
        recurse: true
        group: '{{ dir_group_ownership_library_dirs_newgroup }}'
      tags:
      - DISA-STIG-RHEL-09-232215
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_group_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /usr/lib64/ recursively
      ansible.builtin.file:
        path: /usr/lib64/
        follow: false
        state: directory
        recurse: true
        group: '{{ dir_group_ownership_library_dirs_newgroup }}'
      tags:
      - DISA-STIG-RHEL-09-232215
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_group_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify that Shared Library Directories Have Root Ownership [ref]

System-wide shared library files, which are linked to executables during process load time or run time, are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

Kernel modules, which can be added to the kernel during runtime, are also stored in `/lib/modules`. All files in these directories should be owned by the `root` user. If the directories, is found to be owned by a user other than root correct its ownership with the following command:

    $ sudo chown root DIR

Rationale: | Files from shared library directories are loaded into the address space of processes (including privileged ones) or of the kernel itself at runtime. Proper ownership of library directories is necessary to protect the integrity of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_ownership_library_dirs

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
stigref | SV-257922r1044988_rule

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 /lib/  -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;
    find -P /lib64/  -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;
    find -P /usr/lib/  -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;
    find -P /usr/lib64/  -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the dir_ownership_library_dirs_newown variable if represented by uid
      ansible.builtin.set_fact:
        dir_ownership_library_dirs_newown: '0'
      tags:
      - DISA-STIG-RHEL-09-232210
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /lib/ recursively
      ansible.builtin.file:
        path: /lib/
        follow: false
        state: directory
        recurse: true
        owner: '{{ dir_ownership_library_dirs_newown }}'
      tags:
      - DISA-STIG-RHEL-09-232210
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /lib64/ recursively
      ansible.builtin.file:
        path: /lib64/
        follow: false
        state: directory
        recurse: true
        owner: '{{ dir_ownership_library_dirs_newown }}'
      tags:
      - DISA-STIG-RHEL-09-232210
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /usr/lib/ recursively
      ansible.builtin.file:
        path: /usr/lib/
        follow: false
        state: directory
        recurse: true
        owner: '{{ dir_ownership_library_dirs_newown }}'
      tags:
      - DISA-STIG-RHEL-09-232210
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /usr/lib64/ recursively
      ansible.builtin.file:
        path: /usr/lib64/
        follow: false
        state: directory
        recurse: true
        owner: '{{ dir_ownership_library_dirs_newown }}'
      tags:
      - DISA-STIG-RHEL-09-232210
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify that Shared Library Directories Have Restrictive Permissions [ref]

System-wide shared library directories, which contain are linked to executables during process load time or run time, are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

Kernel modules, which can be added to the kernel during runtime, are stored in `/lib/modules`. All sub-directories in these directories should not be group-writable or world-writable. If any file in these directories is found to be group-writable or world-writable, correct its permission with the following command:

    $ sudo chmod go-w DIR

Rationale:

If the operating system were to allow any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

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

References:

nerc-cip | CIP-003-8 R6
nist | CM-5, CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
stigref | SV-257883r991560_rule

Remediation Shell script ⇲

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

    find -H /lib/  -perm /g+w,o+w -type d -exec chmod g-w,o-w {} \;

    find -H /lib64/  -perm /g+w,o+w -type d -exec chmod g-w,o-w {} \;

    find -H /usr/lib/  -perm /g+w,o+w -type d -exec chmod g-w,o-w {} \;

    find -H /usr/lib64/  -perm /g+w,o+w -type d -exec chmod g-w,o-w {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /lib/ file(s) recursively
      ansible.builtin.command: 'find -P /lib/  -perm /g+w,o+w  -type d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /lib/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /lib64/ file(s) recursively
      ansible.builtin.command: 'find -P /lib64/  -perm /g+w,o+w  -type d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /lib64/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib/ file(s) recursively
      ansible.builtin.command: 'find -P /usr/lib/  -perm /g+w,o+w  -type d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /usr/lib/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib64/ file(s) recursively
      ansible.builtin.command: 'find -P /usr/lib64/  -perm /g+w,o+w  -type d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /usr/lib64/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232015
      - NIST-800-53-CM-5
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - dir_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify that system commands files are group owned by root or a system account [ref]

System commands files are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/sbin
    /usr/local/bin
    /usr/local/sbin

All files in these directories should be owned by the `root` group, or a system account. If the directory, or any file in these directories, is found to be owned by a group other than root or a a system account correct its ownership with the following command:

    $ sudo chgrp root FILE

Rationale:

If the operating system allows any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

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

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50
stigref | SV-257919r1044979_rule

Remediation Shell script ⇲

    find -P /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin \! -group root -type f -exec chgrp root '{}' \; || true

Remediation Ansible snippet ⇲

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

    - name: Verify that system commands files are group owned by root or a system account
        - Find system command files with incorrect group ownership
      ansible.builtin.find:
        paths: '{{ item }}'
        file_type: file
        follow: false
        recurse: false
      register: system_command_files_found
      with_items:
      - /bin
      - /sbin
      - /usr/bin
      - /usr/sbin
      - /usr/local/bin
      - /usr/local/sbin
      changed_when: false
      tags:
      - DISA-STIG-RHEL-09-232195
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - file_groupownership_system_commands_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that system commands files are group owned by root or a system account
        - Set group ownership to root for system command files
      ansible.builtin.file:
        path: '{{ item.path }}'
        group: root
      with_items: '{{ system_command_files_found.results | map(attribute=''files'') |
        flatten | rejectattr(''gr_name'', ''equalto'', ''root'') | list }}'
      tags:
      - DISA-STIG-RHEL-09-232195
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - file_groupownership_system_commands_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that System Executables Have Root Ownership [ref]

System executables are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/libexec
    /usr/local/bin
    /usr/local/sbin
    /usr/sbin

All files in these directories should be owned by the `root` user. If any file FILE in these directories is found to be owned by a user other than root, correct its ownership with the following command:

    $ sudo chown root FILE

Rationale: | System binaries are executed by privileged users as well as system services, and restrictive permissions are necessary to ensure that their execution of these programs cannot be co-opted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_binary_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-5(6), CM-5(6).1, CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50
ism | 1409
stigref | SV-257918r1044977_rule

Remediation Shell script ⇲

    find /bin/ /usr/bin/ /usr/local/bin/ /sbin/ /usr/sbin/ /usr/local/sbin/ /usr/libexec \! -user root -execdir chown root {} \;

Remediation Ansible snippet ⇲

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

    - name: Read list of system executables without root ownership
      ansible.builtin.command: find /bin/ /usr/bin/ /usr/local/bin/ /sbin/ /usr/sbin/
        /usr/local/sbin/ /usr/libexec \! -user root
      register: no_root_system_executables
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232190
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - file_ownership_binary_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set ownership to root of system executables
      ansible.builtin.file:
        path: '{{ item }}'
        owner: root
      with_items: '{{ no_root_system_executables.stdout_lines }}'
      when: no_root_system_executables.stdout_lines | length > 0
      tags:
      - DISA-STIG-RHEL-09-232190
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - file_ownership_binary_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that Shared Library Files Have Root Ownership [ref]

System-wide shared library files, which are linked to executables during process load time or run time, are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

Kernel modules, which can be added to the kernel during runtime, are also stored in `/lib/modules`. All files in these directories should be owned by the `root` user. If the directory, or any file in these directories, is found to be owned by a user other than root correct its ownership with the following command:

    $ sudo chown root FILE

Rationale: | Files from shared library directories are loaded into the address space of processes (including privileged ones) or of the kernel itself at runtime. Proper ownership is necessary to protect the integrity of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_library_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-5(6), CM-5(6).1, CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
ism | 1409
stigref | SV-257920r1101926_rule

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 /lib/  -type f  ! -user 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chown --no-dereference "$newown" {} \;

    find -P /lib64/  -type f  ! -user 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chown --no-dereference "$newown" {} \;

    find -P /usr/lib/  -type f  ! -user 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chown --no-dereference "$newown" {} \;

    find -P /usr/lib64/  -type f  ! -user 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chown --no-dereference "$newown" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the file_ownership_library_dirs_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_ownership_library_dirs_newown: '0'
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /lib/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /lib/  -type f  ! -user 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /lib/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_library_dirs_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /lib64/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /lib64/  -type f  ! -user 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /lib64/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_library_dirs_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /usr/lib/  -type f  ! -user 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /usr/lib/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_library_dirs_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib64/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /usr/lib64/  -type f  ! -user 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /usr/lib64/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_library_dirs_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232200
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_ownership_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify that System Executables Have Restrictive Permissions [ref]

System executables are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/libexec
    /usr/local/bin
    /usr/local/sbin
    /usr/sbin

All files in these directories should not be group-writable or world-writable. If any file FILE in these directories is found to be group-writable or world-writable, correct its permission with the following command:

    $ sudo chmod go-w FILE

Rationale: | System binaries are executed by privileged users, as well as system services, and restrictive permissions are necessary to ensure execution of these programs cannot be co-opted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_binary_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-5(6), CM-5(6).1, CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50
ism | 1409
stigref | SV-257882r991560_rule

Remediation Shell script ⇲

    DIRS="/bin /usr/bin /usr/local/bin /sbin /usr/sbin /usr/local/sbin /usr/libexec"
    for dirPath in $DIRS; do
    	find "$dirPath" -perm /022 -exec chmod go-w '{}' \;
    done

Remediation Ansible snippet ⇲

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

    - name: Read list of world and group writable system executables
      ansible.builtin.command: find -L /bin /usr/bin /usr/local/bin /sbin /usr/sbin /usr/local/sbin
        /usr/libexec -perm /022 \( -type l -o -type f \)
      register: world_writable_library_files
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232010
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - file_permissions_binary_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Remove world/group writability of system executables
      ansible.builtin.file:
        path: '{{ item }}'
        mode: go-w
        state: file
      with_items: '{{ world_writable_library_files.stdout_lines }}'
      when: world_writable_library_files.stdout_lines | length > 0
      tags:
      - DISA-STIG-RHEL-09-232010
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - file_permissions_binary_dirs
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that Shared Library Files Have Restrictive Permissions [ref]

System-wide shared library files, which are linked to executables during process load time or run time, are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

Kernel modules, which can be added to the kernel during runtime, are stored in `/lib/modules`. All files in these directories should not be group-writable or world-writable. If any file in these directories is found to be group-writable or world-writable, correct its permission with the following command:

    $ sudo chmod go-w FILE

Rationale: | Files from shared library directories are loaded into the address space of processes (including privileged ones) or of the kernel itself at runtime. Restrictive permissions are necessary to protect the integrity of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_library_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), CM-5(6), CM-5(6).1, AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
ism | 1409
stigref | SV-257884r1106306_rule

Remediation Shell script ⇲

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

    find -P /lib/  -perm /g+w,o+w  -type f -regextype posix-extended -regex '^.*\.so.*$' -exec chmod g-w,o-w {} \;

    find -P /lib64/  -perm /g+w,o+w  -type f -regextype posix-extended -regex '^.*\.so.*$' -exec chmod g-w,o-w {} \;

    find -P /usr/lib/  -perm /g+w,o+w  -type f -regextype posix-extended -regex '^.*\.so.*$' -exec chmod g-w,o-w {} \;

    find -P /usr/lib64/  -perm /g+w,o+w  -type f -regextype posix-extended -regex '^.*\.so.*$' -exec chmod g-w,o-w {} \;

Remediation Ansible snippet ⇲

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

    - name: Find /lib/ file(s) recursively
      ansible.builtin.command: find -P /lib/  -perm /g+w,o+w  -type f -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /lib/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /lib64/ file(s) recursively
      ansible.builtin.command: find -P /lib64/  -perm /g+w,o+w  -type f -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /lib64/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib/ file(s) recursively
      ansible.builtin.command: find -P /usr/lib/  -perm /g+w,o+w  -type f -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /usr/lib/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /usr/lib64/ file(s) recursively
      ansible.builtin.command: find -P /usr/lib64/  -perm /g+w,o+w  -type f -regextype
        posix-extended -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /usr/lib64/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: g-w,o-w
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232020
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_library_dirs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify the system-wide library files in directories "/lib", "/lib64", "/usr/lib/" and "/usr/lib64" are group-owned by root. [ref]

System-wide library files are stored in the following directories by default:

    /lib
    /lib64
    /usr/lib
    /usr/lib64

All system-wide shared library files should be protected from unauthorised access. If any of these files is not group-owned by root, correct its group-owner with the following command:

    $ sudo chgrp root FILE

Rationale:

If the operating system were to allow any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

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

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
stigref | SV-257921r1106308_rule

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
    find -P /lib/  -type f  ! -group 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /lib64/  -type f  ! -group 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /usr/lib/  -type f  ! -group 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chgrp --no-dereference "$newgroup" {} \;
    find -P /usr/lib64/  -type f  ! -group 0 -regextype posix-extended -regex '^.*\.so.*$' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

Remediation Ansible snippet ⇲

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

    - name: Set the root_permissions_syslibrary_files_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        root_permissions_syslibrary_files_newgroup: '0'
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Find /lib/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /lib/  -type f  ! -group 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Ensure group owner on /lib/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ root_permissions_syslibrary_files_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Find /lib64/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /lib64/  -type f  ! -group 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Ensure group owner on /lib64/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ root_permissions_syslibrary_files_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Find /usr/lib/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /usr/lib/  -type f  ! -group 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Ensure group owner on /usr/lib/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ root_permissions_syslibrary_files_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Find /usr/lib64/ file(s) matching ^.*\.so.*$ recursively
      ansible.builtin.command: find -P /usr/lib64/  -type f  ! -group 0 -regextype posix-extended
        -regex "^.*\.so.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

    - name: Ensure group owner on /usr/lib64/ file(s) matching ^.*\.so.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ root_permissions_syslibrary_files_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-232205
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - root_permissions_syslibrary_files

Group rootfiles Group contains 1 rule
[ref] Configure the rootfiles package so the root user's files are correctly secured.

#### Rule Ensure rootfiles tmpfile.d is Configured Correctly [ref]

To set the mode of the root user initialization file `/root/.bash_profile`, ensure the following lines are is included in a file ending in `.conf` under `/etc/tmpfiles.d/`.

        C /root/.bash_logout   600 root root - /usr/share/rootfiles/.bash_logout
        C /root/.bash_profile  600 root root - /usr/share/rootfiles/.bash_profile
        C /root/.bashrc        600 root root - /usr/share/rootfiles/.bashrc
        C /root/.cshrc         600 root root - /usr/share/rootfiles/.cshrc
        C /root/.tcshrc        600 root root - /usr/share/rootfiles/.tcshrc

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_rootfiles_configured

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257889r1044959_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q rootfiles; then

    find "/etc/tmpfiles.d/" -name "*.conf" -print0 | xargs -0 sed -i  "/C[[:space:]]*\/root\/.bash_logout/d"
        find "/etc/tmpfiles.d/" -name "*.conf" -print0 | xargs -0 sed -i  "/C[[:space:]]*\/root\/.bash_profile/d"
        find "/etc/tmpfiles.d/" -name "*.conf" -print0 | xargs -0 sed -i  "/C[[:space:]]*\/root\/.bashrc/d"
        find "/etc/tmpfiles.d/" -name "*.conf" -print0 | xargs -0 sed -i  "/C[[:space:]]*\/root\/.cshrc/d"
        find "/etc/tmpfiles.d/" -name "*.conf" -print0 | xargs -0 sed -i  "/C[[:space:]]*\/root\/.tcshrc/d"

    cat << 'EOF' > /etc/tmpfiles.d/rootfiles.conf
    C /root/.bash_logout 600 root root - /usr/share/rootfiles/.bash_logout
    C /root/.bash_profile 600 root root - /usr/share/rootfiles/.bash_profile
    C /root/.bashrc 600 root root - /usr/share/rootfiles/.bashrc
    C /root/.cshrc 600 root root - /usr/share/rootfiles/.cshrc
    C /root/.tcshrc 600 root root - /usr/share/rootfiles/.tcshrc

    EOF

    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:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Find configuration files
      ansible.builtin.find:
        paths: /etc/tmpfiles.d/
        file_type: file
        patterns: '*.conf'
      register: rootfiles_configured_bash_logout_found_files
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Remove existing configuration
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^C\s+/root/\.bash_logout.+$
        state: absent
      loop: '{{ rootfiles_configured_bash_logout_found_files.files }}'
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly
      ansible.builtin.lineinfile:
        path: /etc/tmpfiles.d/rootfiles.conf
        create: true
        regexp: (?i)/usr/share/rootfiles/.bash_logout
        line: C /root/.bash_logout 600 root root - /usr/share/rootfiles/.bash_logout
        state: present
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Find configuration files
      ansible.builtin.find:
        paths: /etc/tmpfiles.d/
        file_type: file
        patterns: '*.conf'
      register: rootfiles_configured_bash_profile_found_files
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Remove existing configuration
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^C\s+/root/\.bash_profile.+$
        state: absent
      loop: '{{ rootfiles_configured_bash_profile_found_files.files }}'
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly
      ansible.builtin.lineinfile:
        path: /etc/tmpfiles.d/rootfiles.conf
        create: true
        regexp: (?i)/usr/share/rootfiles/.bash_profile
        line: C /root/.bash_profile 600 root root - /usr/share/rootfiles/.bash_profile
        state: present
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Find configuration files
      ansible.builtin.find:
        paths: /etc/tmpfiles.d/
        file_type: file
        patterns: '*.conf'
      register: rootfiles_configured_bashrc_found_files
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Remove existing configuration
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^C\s+/root/\.bashrc.+$
        state: absent
      loop: '{{ rootfiles_configured_bashrc_found_files.files }}'
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly
      ansible.builtin.lineinfile:
        path: /etc/tmpfiles.d/rootfiles.conf
        create: true
        regexp: (?i)/usr/share/rootfiles/.bashrc
        line: C /root/.bashrc 600 root root - /usr/share/rootfiles/.bashrc
        state: present
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Find configuration files
      ansible.builtin.find:
        paths: /etc/tmpfiles.d/
        file_type: file
        patterns: '*.conf'
      register: rootfiles_configured_cshrc_found_files
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Remove existing configuration
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^C\s+/root/\.cshrc.+$
        state: absent
      loop: '{{ rootfiles_configured_cshrc_found_files.files }}'
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly
      ansible.builtin.lineinfile:
        path: /etc/tmpfiles.d/rootfiles.conf
        create: true
        regexp: (?i)/usr/share/rootfiles/.cshrc
        line: C /root/.cshrc 600 root root - /usr/share/rootfiles/.cshrc
        state: present
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Find configuration files
      ansible.builtin.find:
        paths: /etc/tmpfiles.d/
        file_type: file
        patterns: '*.conf'
      register: rootfiles_configured_tcshrc_found_files
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly - Remove existing configuration
      ansible.builtin.lineinfile:
        path: '{{ item.path }}'
        regexp: ^C\s+/root/\.tcshrc.+$
        state: absent
      loop: '{{ rootfiles_configured_tcshrc_found_files.files }}'
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

    - name: Ensure rootfiles tmpfile.d is Configured Correctly
      ansible.builtin.lineinfile:
        path: /etc/tmpfiles.d/rootfiles.conf
        create: true
        regexp: (?i)/usr/share/rootfiles/.tcshrc
        line: C /root/.tcshrc 600 root root - /usr/share/rootfiles/.tcshrc
        state: present
      when: '"rootfiles" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232045
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - rootfiles_configured

#### Rule Ensure All World-Writable Directories Are Owned by root User [ref]

All directories in local partitions which are world-writable should be owned by root. If any world-writable directories are not owned by root, this should be investigated. Following this, the files should be deleted or assigned to root user.
Rationale: | Allowing a user account to own a world-writable directory is undesirable because it allows the owner of that directory to remove or replace any files that may be placed in the directory by other users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_perms_world_writable_root_owned

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000138-GPOS-00069
anssi | R54
stigref | SV-257928r1044992_rule

Remediation Shell script ⇲

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

    # At least under containerized env /proc can have files w/o possilibity to
    # modify even as root. And touching /proc is not good idea anyways.
    find / -path /proc -prune -o \
        -not -fstype afs -not -fstype autofs -not -fstype ceph -not -fstype cifs -not -fstype smb3 \
        -not -fstype smbfs -not -fstype sshfs -not -fstype ncpfs -not -fstype ncp -not -fstype nfs \
        -not -fstype nfs4 -not -fstype gfs -not -fstype gfs2 -not -fstype glusterfs -not -fstype gpfs \
        -not -fstype pvfs2 -not -fstype ocfs2 -not -fstype lustre -not -fstype davfs \
        -not -fstype fuse.sshfs -type d -perm -0002 -uid +0 -exec chown root {} \;

Remediation Ansible snippet ⇲

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

    - name: Ensure All World-Writable Directories Are Owned by root User - Define Excluded
        (Non-Local) File Systems and Paths
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
        excluded_paths:
        - dev
        - proc
        - run
        - sys
        search_paths: []
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Find Relevant
        Root Directories Ignoring Pre-Defined Excluded Paths
      ansible.builtin.find:
        paths: /
        file_type: directory
        excludes: '{{ excluded_paths }}'
        hidden: true
        recurse: false
      register: result_relevant_root_dirs
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Include Relevant
        Root Directories in a List of Paths to be Searched
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.path]) }}'
      loop: '{{ result_relevant_root_dirs.files }}'
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Increment Search
        Paths List with Local Partitions Mount Points
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.mount]) }}'
      loop: '{{ ansible_mounts }}'
      when:
      - item.fstype not in excluded_fstypes
      - item.mount != '/'
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Increment Search
        Paths List with Local NFS File System Targets
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.device.split('':'')[1]]) }}'
      loop: '{{ ansible_mounts }}'
      when: item.device is search("localhost:")
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Define Rule
        Specific Facts
      ansible.builtin.set_fact:
        world_writable_dirs: []
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Find All Uncompliant
        Directories in Local File Systems
      ansible.builtin.command:
        cmd: find {{ item }} -xdev -type d -perm -0002 -uid +0
      loop: '{{ search_paths }}'
      changed_when: false
      register: result_found_dirs
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Create List
        of World Writable Directories Not Owned by root
      ansible.builtin.set_fact:
        world_writable_dirs: '{{ world_writable_dirs | union(item.stdout_lines) | list
          }}'
      loop: '{{ result_found_dirs.results }}'
      when: item is not skipped
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Ensure root
        Ownership on Local World Writable Directories
      ansible.builtin.file:
        path: '{{ item }}'
        owner: root
      loop: '{{ world_writable_dirs }}'
      tags:
      - DISA-STIG-RHEL-09-232240
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that All World-Writable Directories Have Sticky Bits Set [ref]

When the so-called 'sticky bit' is set on a directory, only the owner of a given file may remove that file from the directory. Without the sticky bit, any user with write access to a directory may remove any file in the directory. Setting the sticky bit prevents users from removing each other's files. In cases where there is no reason for a directory to be world-writable, a better solution is to remove that permission rather than to set the sticky bit. However, if a directory is used by a particular application, consult that application's documentation instead of blindly changing modes.
To set the sticky bit on a world-writable directory DIR, run the following command:

    $ sudo chmod +t DIR

Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of directories present on the system. It is not a problem in most cases, but especially systems with a large number of directories can be affected. See `https://access.redhat.com/articles/6999111`.
Warning: Please note that there might be cases where the rule remediation cannot fix directory permissions. This can happen for example when running on a system with some immutable parts. These immutable parts cannot be remediated because they are read-only. Example of such directories can be OStree deployments located at `/sysroot/ostree/deploy`. In such case, it is needed to make modifications to the underlying ostree snapshot and this is out of scope of regular rule remediation.

Rationale:

Failing to set the sticky bit on public directories allows unauthorized users to delete files in the directory structure.
The only authorized public directories are those temporary directories supplied with the system, or those designed to be temporary file repositories. The setting is normally reserved for directories used by the system, by users for temporary file storage (such as `/tmp`), and for directories requiring global read/write access.

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

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000138-GPOS-00069
anssi | R54
ism | 1409
pcidss4 | 2.2.6, 2.2
cis | 7.1.11
stigref | SV-257929r1117267_rule

Remediation Shell script ⇲

    df --local -P | awk '{if (NR!=1) print $6}' \
    | xargs -I '$6' find '$6' -xdev -type d \
    \( -perm -0002 -a ! -perm -1000 \) 2>/dev/null \
    -exec chmod a+t {} +

Remediation Ansible snippet ⇲

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

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Define Excluded
        (Non-Local) File Systems and Paths
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
        excluded_paths:
        - dev
        - proc
        - run
        - sys
        search_paths: []
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Find Relevant
        Root Directories Ignoring Pre-Defined Excluded Paths
      ansible.builtin.find:
        paths: /
        file_type: directory
        excludes: '{{ excluded_paths }}'
        hidden: true
        recurse: false
      register: result_relevant_root_dirs
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Include
        Relevant Root Directories in a List of Paths to be Searched
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.path]) }}'
      loop: '{{ result_relevant_root_dirs.files }}'
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Increment
        Search Paths List with Local Partitions Mount Points
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.mount]) }}'
      loop: '{{ ansible_mounts }}'
      when:
      - item.fstype not in excluded_fstypes
      - item.mount != '/'
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Increment
        Search Paths List with Local NFS File System Targets
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.device.split('':'')[1]]) }}'
      loop: '{{ ansible_mounts }}'
      when: item.device is search("localhost:")
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Define Rule
        Specific Facts
      ansible.builtin.set_fact:
        world_writable_dirs: []
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Find All
        Uncompliant Directories in Local File Systems
      ansible.builtin.command:
        cmd: find {{ item }} -xdev -type d ( -perm -0002 -a ! -perm -1000 )
      loop: '{{ search_paths }}'
      changed_when: false
      register: result_found_dirs
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Create List
        of World Writable Directories Without Sticky Bit
      ansible.builtin.set_fact:
        world_writable_dirs: '{{ world_writable_dirs | union(item.stdout_lines) | list
          }}'
      loop: '{{ result_found_dirs.results }}'
      when: result_found_dirs is not skipped and item is not skipped
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Verify that All World-Writable Directories Have Sticky Bits Set - Ensure Sticky
        Bit is Set on Local World Writable Directories
      ansible.builtin.file:
        path: '{{ item }}'
        mode: a+t
      loop: '{{ world_writable_dirs }}'
      tags:
      - DISA-STIG-RHEL-09-232245
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - dir_perms_world_writable_sticky_bits
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure All Files Are Owned by a Group [ref]

If any file is not group-owned by a valid defined group, the cause of the lack of group-ownership must be investigated. Following this, those files should be deleted or assigned to an appropriate group. The groups need to be defined in `/etc/group` or in `/usr/lib/group` if `nss-altfiles` are configured to be used in `/etc/nsswitch.conf`. Locate the mount points related to local devices by the following command:

    $ findmnt -n -l -k -it $(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)

For all mount points listed by the previous command, it is necessary to search for files which do not belong to a valid group using the following command:

    $ sudo find MOUNTPOINT -xdev -nogroup 2>/dev/null

Warning: This rule only considers local groups as valid groups. If you have your groups defined outside `/etc/group` or `/usr/lib/group`, the rule won't consider those.
Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of files present on the system. It is not a problem in most cases, but especially systems with a large number of files can be affected. See `https://access.redhat.com/articles/6999111`.

Rationale:

Unowned files do not directly imply a security problem, but they are generally a sign that something is amiss. They may be caused by an intruder, by incorrect software installation or draft software removal, or by failure to remove all files belonging to a deleted account, or other similar cases. The files should be repaired so they will not cause problems when accounts are created in the future, and the cause should be discovered and addressed.

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

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.06, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.18.1.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R53
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 7.1.12
stigref | SV-257930r991589_rule

#### Rule Ensure All Files Are Owned by a User [ref]

If any files are not owned by a user, then the cause of their lack of ownership should be investigated. Following this, the files should be deleted or assigned to an appropriate user. Locate the mount points related to local devices by the following command:

    $ findmnt -n -l -k -it $(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)

For all mount points listed by the previous command, it is necessary to search for files which do not belong to a valid user using the following command:

    $ sudo find MOUNTPOINT -xdev -nouser 2>/dev/null

Warning: For this rule to evaluate centralized user accounts, `getent` must be working properly so that running the command

    getent passwd

returns a list of all users in your organization. If using the System Security Services Daemon (SSSD),

    enumerate = true

must be configured in your organization's domain to return a complete list of users
Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of files present on the system. It is not a problem in most cases, but especially systems with a large number of files can be affected. See `https://access.redhat.com/articles/6999111`.

Rationale:

Unowned files do not directly imply a security problem, but they are generally a sign that something is amiss. They may be caused by an intruder, by incorrect software installation or draft software removal, or by failure to remove all files belonging to a deleted account, or other similar cases. The files should be repaired so they will not cause problems when accounts are created in the future, and the cause should be discovered and addressed.

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

References:

cis-csc | 11, 12, 13, 14, 15, 16, 18, 3, 5, 9
cobit5 | APO01.06, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.03, DSS06.06
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.AC-6, PR.DS-5, PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R53
pcidss4 | 2.2.6, 2.2
cis | 7.1.12
stigref | SV-257931r991589_rule

#### Rule Enable Kernel Parameter to Enforce DAC on Hardlinks [ref]

To set the runtime status of the `fs.protected_hardlinks` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_hardlinks=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_hardlinks = 1

Rationale: | By enabling this kernel parameter, users can no longer create soft or hard links to files which they do not own. Disallowing such hardlinks mitigate vulnerabilities based on insecure file system accessed by privileged programs, avoiding an exploitation vector exploiting unsafe use of `open()` or `creat()`.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_protected_hardlinks

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000324-GPOS-00125
anssi | R14
stigref | SV-257801r1106279_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of fs.protected_hardlinks from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_hardlinks
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w fs.protected_hardlinks="1"
    fi

    #
    # If fs.protected_hardlinks present in /etc/sysctl.conf, change value to "1"
    #	else, add "fs.protected_hardlinks = 1" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^fs.protected_hardlinks")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^fs.protected_hardlinks\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_hardlinks\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Find all files that
        contain fs.protected_hardlinks
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_hardlinks\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Find all files that
        set fs.protected_hardlinks to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_hardlinks\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Comment out any occurrences
        of fs.protected_hardlinks from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_hardlinks
        replace: '#fs.protected_hardlinks'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Ensure sysctl fs.protected_hardlinks
        is set to 1
      ansible.posix.sysctl:
        name: fs.protected_hardlinks
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213030
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,fs.protected_hardlinks%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_fs_protected_hardlinks.conf
            overwrite: true

#### Rule Enable Kernel Parameter to Enforce DAC on Symlinks [ref]

To set the runtime status of the `fs.protected_symlinks` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_symlinks=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_symlinks = 1

Rationale:

By enabling this kernel parameter, symbolic links are permitted to be followed only when outside a sticky world-writable directory, or when the UID of the link and follower match, or when the directory owner matches the symlink's owner. Disallowing such symlinks helps mitigate vulnerabilities based on insecure file system accessed by privileged programs, avoiding an exploitation vector exploiting unsafe use of `open()` or `creat()`.

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

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000324-GPOS-00125
anssi | R14
stigref | SV-257802r1106282_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of fs.protected_symlinks from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_symlinks
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w fs.protected_symlinks="1"
    fi

    #
    # If fs.protected_symlinks present in /etc/sysctl.conf, change value to "1"
    #	else, add "fs.protected_symlinks = 1" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^fs.protected_symlinks")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^fs.protected_symlinks\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_symlinks\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Find all files that contain
        fs.protected_symlinks
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_symlinks\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Find all files that set
        fs.protected_symlinks to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_symlinks\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Comment out any occurrences
        of fs.protected_symlinks from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_symlinks
        replace: '#fs.protected_symlinks'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Ensure sysctl fs.protected_symlinks
        is set to 1
      ansible.posix.sysctl:
        name: fs.protected_symlinks
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213035
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,fs.protected_symlinks%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_fs_protected_symlinks.conf
            overwrite: true

Group Restrict Dynamic Mounting and Unmounting of Filesystems Group contains 3 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 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
bsi | SYS.1.1.A5, SYS.1.3.A3
cis | 2.1.1
stigref | SV-257849r1044928_rule

Remediation script ⇲

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

    service disable autofs

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q autofs && rpm --quiet -q kernel-core ); then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" stop 'autofs.service'
    fi
    "$SYSTEMCTL_EXEC" disable 'autofs.service'
    "$SYSTEMCTL_EXEC" mask 'autofs.service'
    # Disable socket activation if we have a unit file for it
    if "$SYSTEMCTL_EXEC" -q list-unit-files autofs.socket; then
        if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
          "$SYSTEMCTL_EXEC" stop 'autofs.socket'
        fi
        "$SYSTEMCTL_EXEC" mask 'autofs.socket'
    fi
    # The service may not be running because it has been started and failed,
    # so let's reset the state so OVAL checks pass.
    # Service should be 'inactive', not 'failed' after reboot though.
    "$SYSTEMCTL_EXEC" reset-failed 'autofs.service' || true

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

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:
      - DISA-STIG-RHEL-09-231040
      - 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:
      - DISA-STIG-RHEL-09-231040
      - 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 "kernel-core" in ansible_facts.packages
        )

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: autofs.service
            enabled: false
            mask: true
          - name: autofs.socket
            enabled: false
            mask: true

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
stigref | SV-257880r1044951_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231195
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_cramfs_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'cramfs' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/cramfs.conf
        regexp: install\s+cramfs
        line: install cramfs /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-231195
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_cramfs_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

    - name: Ensure kernel module 'cramfs' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/cramfs.conf
        regexp: ^blacklist cramfs$
        line: blacklist cramfs
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-231195
      - NIST-800-171-3.4.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - kernel_module_cramfs_disabled
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20cramfs%20/bin/false%0Ablacklist%20cramfs%0A
            mode: 0644
            path: /etc/modprobe.d/cramfs.conf
            overwrite: true

#### 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
pcidss4 | 3.4.2, 3.4
bsi | SYS.1.1.A5, SYS.1.3.A3
cis | 1.1.1.8
stigref | SV-258034r1051267_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-291010
      - NIST-800-171-3.1.21
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - disable_strategy
      - kernel_module_usb-storage_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'usb-storage' is disabled
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/usb-storage.conf
        regexp: install\s+usb-storage
        line: install usb-storage /bin/false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-291010
      - NIST-800-171-3.1.21
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - disable_strategy
      - kernel_module_usb-storage_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

    - name: Ensure kernel module 'usb-storage' is blacklisted
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/modprobe.d/usb-storage.conf
        regexp: ^blacklist usb-storage$
        line: blacklist usb-storage
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-291010
      - NIST-800-171-3.1.21
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - PCI-DSSv4-3.4
      - PCI-DSSv4-3.4.2
      - disable_strategy
      - kernel_module_usb-storage_disabled
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,install%20usb-storage%20/bin/false%0Ablacklist%20usb-storage%0A
            mode: 0644
            path: /etc/modprobe.d/usb-storage.conf
            overwrite: true

Group Restrict Partition Mount Options Group contains 26 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 nosuid Option to /boot/efi [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/boot/efi`. The SUID and SGID permissions should not be required on the boot partition. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/boot/efi`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from boot partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_boot_efi_nosuid

References:

nist | CM-6(b), CM-6.1(iv)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257862r1051265_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 "/boot/efi" > /dev/null || findmnt --fstab "/boot/efi" > /dev/null; }; then

    function perform_remediation {

            # the mount point /boot/efi has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/boot/efi")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/boot/efi' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /boot/efi in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /boot/efi)"

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

        if mkdir -p "/boot/efi"; then
            if mountpoint -q "/boot/efi"; then
                mount -o remount --target "/boot/efi"
            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:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot/efi: Check information associated to mountpoint'
      command: findmnt --fstab '/boot/efi'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel-core" 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"] ) )
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot/efi: 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-core" 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"] ) )
      - '"/boot/efi" 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:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot/efi: If /boot/efi not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /boot/efi
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel-core" 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"] ) )
      - '"/boot/efi" 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:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot/efi: Make sure nosuid option is part of the to
        /boot/efi options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel-core" 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"] ) )
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot/efi: Ensure /boot/efi is mounted with nosuid option'
      mount:
        path: /boot/efi
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel-core" 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"] ) )
      - '"/boot/efi" 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:
      - DISA-STIG-RHEL-09-231105
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_efi_nosuid
      - no_reboot_needed

#### Rule Add nodev Option to /boot [ref]

The `nodev` mount option can be used to prevent device files from being created in `/boot`. 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 `/boot`.
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_boot_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
stigref | SV-257860r1044940_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /boot has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/boot")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/boot' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /boot in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /boot)"

        # If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
        if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
            # runtime opts without some automatic kernel/userspace-added defaults
            previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                        | sed -E "s/(rw|defaults|seclabel|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 " /boot  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 "/boot"; then
            if mountpoint -q "/boot"; then
                mount -o remount --target "/boot"
            fi
        fi
    }

    perform_remediation

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

Remediation Anaconda snippet ⇲

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

    part /boot --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /boot: Check information associated to mountpoint'
      command: findmnt --fstab '/boot'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /boot: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /boot: If /boot not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /boot
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /boot: Make sure nodev option is part of the to /boot
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nodev''
          }) }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

    - name: 'Add nodev Option to /boot: Ensure /boot is mounted with nodev option'
      mount:
        path: /boot
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231095
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nodev
      - no_reboot_needed

#### Rule Add nosuid Option to /boot [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/boot`. The SUID and SGID permissions should not be required on the boot partition. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/boot`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from boot partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_boot_nosuid

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28
stigref | SV-257861r1044941_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /boot has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/boot")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/boot' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /boot in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /boot)"

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

        if mkdir -p "/boot"; then
            if mountpoint -q "/boot"; then
                mount -o remount --target "/boot"
            fi
        fi
    }

    perform_remediation

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

Remediation Anaconda snippet ⇲

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

    part /boot --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Check information associated to mountpoint'
      command: findmnt --fstab '/boot'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: If /boot not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /boot
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Make sure nosuid option is part of the to /boot
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Ensure /boot is mounted with nosuid option'
      mount:
        path: /boot
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231100
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

#### Rule Add 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
ism | 1409
cis | 1.1.2.2.2
stigref | SV-257863r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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:
      - DISA-STIG-RHEL-09-231110
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231110
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231110
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231110
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231110
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231110
      - 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
ism | 1409
cis | 1.1.2.2.4
stigref | SV-257864r1106304_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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:
      - DISA-STIG-RHEL-09-231115
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231115
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231115
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231115
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231115
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231115
      - 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
ism | 1409
cis | 1.1.2.2.3
stigref | SV-257865r1044946_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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:
      - DISA-STIG-RHEL-09-231120
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231120
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231120
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231120
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231120
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231120
      - 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
stigref | SV-257850r1044930_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /home --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231045
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231045
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231045
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231045
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231045
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231045
      - configure_strategy
      - high_disruption
      - low_complexity
      - mount_option_home_nodev
      - no_reboot_needed
      - unknown_severity

#### Rule Add noexec Option to /home [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/home`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/home`.
Rationale: | The `/home` directory contains data of individual users. Binaries in this directory should not be considered as trusted and users should not be able to execute them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_home_noexec

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
anssi | R28
stigref | SV-257852r991589_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /home has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/home")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/home' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /home in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /home)"

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

        if mkdir -p "/home"; then
            if mountpoint -q "/home"; then
                mount -o remount --target "/home"
            fi
        fi
    }

    perform_remediation

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

Remediation Anaconda snippet ⇲

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

    part /home --mountoptions="noexec"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Check information associated to mountpoint'
      command: findmnt --fstab '/home'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: If /home not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /home
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Make sure noexec option is part of the to /home
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Ensure /home is mounted with noexec option'
      mount:
        path: /home
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - DISA-STIG-RHEL-09-231055
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /home [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/home`. The SUID and SGID permissions should not be required in these user data directories. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/home`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from user home directory partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_home_nosuid

References:

cis-csc | 11, 13, 14, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS05.06, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28
cis | 1.1.2.3.3
stigref | SV-257851r1044932_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /home --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231050
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231050
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231050
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231050
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231050
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231050
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

#### Rule Add nodev Option to Non-Root Local Partitions [ref]

The `nodev` mount option prevents files from being interpreted as character or block devices. Legitimate character and block devices should exist only in the `/dev` directory on the root partition or within chroot jails built for system services. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of any non-root local partitions.
Rationale: | The `nodev` mount option prevents files from being interpreted as character or block devices. The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails, for which it is not advised to set `nodev` on these filesystems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nodev_nonroot_local_partitions

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28
stigref | SV-257881r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    MOUNT_OPTION="nodev"
    # Create array of local non-root partitions
    readarray -t partitions_records < <(findmnt --mtab --raw --evaluate | grep "^/\w" | grep -v "^/proc" | grep "\s/dev/\w")

    # Create array of polyinstantiated directories, in case one of them is found in mtab
    readarray -t polyinstantiated_dirs < \
        <(grep -oP "^\s*[^#\s]+\s+\S+" /etc/security/namespace.conf | grep -oP "(?<=\s)\S+?(?=/?\$)")

    # Define excluded non-local file systems
    excluded_fstypes=(
        afs
        autofs
        ceph
        cifs
        smb3
        smbfs
        sshfs
        ncpfs
        ncp
        nfs
        nfs4
        gfs
        gfs2
        glusterfs
        gpfs
        pvfs2
        ocfs2
        lustre
        davfs
        fuse.sshfs
    )

    for partition_record in "${partitions_records[@]}"; do
        # Get all important information for fstab
        mount_point="$(echo "${partition_record}" | cut -d " " -f1)"
        device="$(echo "${partition_record}" | cut -d " " -f2)"
        device_type="$(echo "${partition_record}" | cut -d " " -f3)"

        # Skip polyinstantiated directories
        if printf '%s\0' "${polyinstantiated_dirs[@]}" | grep -qxzF "$mount_point"; then
            continue
        fi

        # Skip any non-local filesystem
        for excluded_fstype in "${excluded_fstypes[@]}"; do
            if [[ "$device_type" == "$excluded_fstype" ]]; then
                # jump out of both loops and move to next partition_record
                continue 2
            fi
        done

        # If we reach here, it's a local, non-root partition that isn't excluded.
        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" $mount_point)"

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

    # Remediate unmounted /etc/fstab entries
    sed -i -E '/nodev/! s;^\s*(/dev/\S+|UUID=\S+)\s+(/\w\S*)\s+(\S+)\s+(\S+)(.*)$;\1 \2 \3 \4,nodev \5;' /etc/fstab

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231200
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Refresh facts'
      ansible.builtin.setup:
        gather_subset: mounts
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231200
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Define excluded (non-local)
        file systems'
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231200
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Ensure non-root local partitions
        are mounted with nodev option'
      ansible.posix.mount:
        path: '{{ item.mount }}'
        src: '{{ item.device }}'
        opts: '{{ item.options }},nodev'
        state: mounted
        fstype: '{{ item.fstype }}'
      when:
      - ( not ( "kernel-core" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - item.mount is match('/\w')
      - item.options is not search('nodev')
      - item.fstype not in excluded_fstypes
      with_items:
      - '{{ ansible_facts.mounts }}'
      tags:
      - DISA-STIG-RHEL-09-231200
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Ensure non-root local partitions
        are present with nodev option in /etc/fstab'
      ansible.builtin.replace:
        path: /etc/fstab
        regexp: ^\s*(?!#)(/dev/\S+|UUID=\S+)\s+(/\w\S*)\s+(\S+)\s+(?!.*\bnodev\b)(\S+)(.*)$
        replace: \1 \2 \3 \4,nodev \5
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231200
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

#### Rule Add nodev Option to Removable Media Partitions [ref]

The `nodev` mount option prevents files from being interpreted as character or block devices. Legitimate character and block devices should exist only in the `/dev` directory on the root partition or within chroot jails built for system services. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of any removable media partitions.
Rationale: | The only legitimate location for device files is the `/dev` directory located on the root partition. An exception to this is chroot jails, and it is not advised to set `nodev` on partitions which contain their root filesystems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nodev_removable_partitions

References:

cis-csc | 11, 12, 13, 14, 16, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.06, 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, 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.6, A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.7.1.1, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2, A.9.2.1
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.AC-3, PR.AC-6, PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257858r991589_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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

    var_removable_partition='/dev/cdrom'

    device_regex="^\s*$var_removable_partition\s\+"
    mount_option="nodev"

    if grep -q $device_regex /etc/fstab ; then
        previous_opts=$(grep $device_regex /etc/fstab | awk '{print $4}')
        sed -i "s|\($device_regex.*$previous_opts\)|\1,$mount_option|" /etc/fstab
    else
        echo "Not remediating, because there is no record of $var_removable_partition in /etc/fstab" >&2
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231085
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_removable_partitions
      - no_reboot_needed
    - name: XCCDF Value var_removable_partition # promote to variable
      set_fact:
        var_removable_partition: !!str /dev/cdrom
      tags:
        - always

    - name: Ensure permission nodev are set on var_removable_partition
      ansible.builtin.lineinfile:
        path: /etc/fstab
        regexp: ^\s*({{ var_removable_partition }})\s+([^\s]*)\s+([^\s]*)\s+([^\s]*)(.*)$
        backrefs: true
        line: \1 \2 \3 \4,nodev \5
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231085
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_removable_partitions
      - no_reboot_needed

#### Rule Add noexec Option to Removable Media Partitions [ref]

The `noexec` mount option prevents the direct execution of binaries on the mounted filesystem. Preventing the direct execution of binaries from removable media (such as a USB key) provides a defense against malicious software that may be present on such untrusted media. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of any removable media partitions.

Rationale: | Allowing users to execute binaries from removable media such as USB keys exposes the system to potential compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_noexec_removable_partitions

References:

cis-csc | 11, 12, 13, 14, 16, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.06, 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, 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.6, A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.7.1.1, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2, A.9.2.1
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.AC-3, PR.AC-6, PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257857r991589_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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

    var_removable_partition='/dev/cdrom'

    device_regex="^\s*$var_removable_partition\s\+"
    mount_option="noexec"

    if grep -q $device_regex /etc/fstab ; then
        previous_opts=$(grep $device_regex /etc/fstab | awk '{print $4}')
        sed -i "s|\($device_regex.*$previous_opts\)|\1,$mount_option|" /etc/fstab
    else
        echo "Not remediating, because there is no record of $var_removable_partition in /etc/fstab" >&2
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231080
      - 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_noexec_removable_partitions
      - no_reboot_needed
    - name: XCCDF Value var_removable_partition # promote to variable
      set_fact:
        var_removable_partition: !!str /dev/cdrom
      tags:
        - always

    - name: Ensure permission noexec are set on var_removable_partition
      ansible.builtin.lineinfile:
        path: /etc/fstab
        regexp: ^\s*({{ var_removable_partition }})\s+([^\s]*)\s+([^\s]*)\s+([^\s]*)(.*)$
        backrefs: true
        line: \1 \2 \3 \4,noexec \5
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231080
      - 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_noexec_removable_partitions
      - no_reboot_needed

#### Rule Add nosuid Option to Removable Media Partitions [ref]

The `nosuid` mount option prevents set-user-identifier (SUID) and set-group-identifier (SGID) permissions from taking effect. These permissions allow users to execute binaries with the same permissions as the owner and group of the file respectively. Users should not be allowed to introduce SUID and SGID files into the system via partitions mounted from removable media. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of any removable media partitions.

Rationale: | The presence of SUID and SGID executables should be tightly controlled. Allowing users to introduce SUID or SGID binaries from partitions mounted off of removable media would allow them to introduce their own highly-privileged programs.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nosuid_removable_partitions

References:

cis-csc | 11, 12, 13, 14, 15, 16, 18, 3, 5, 8, 9
cobit5 | APO01.06, APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.06, 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.11.2.6, A.11.2.9, 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.6.2.1, A.6.2.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.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
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.AC-3, PR.AC-4, PR.AC-6, PR.DS-5, PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257859r991589_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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

    var_removable_partition='/dev/cdrom'

    device_regex="^\s*$var_removable_partition\s\+"
    mount_option="nosuid"

    if grep -q $device_regex /etc/fstab ; then
        previous_opts=$(grep $device_regex /etc/fstab | awk '{print $4}')
        sed -i "s|\($device_regex.*$previous_opts\)|\1,$mount_option|" /etc/fstab
    else
        echo "Not remediating, because there is no record of $var_removable_partition in /etc/fstab" >&2
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231090
      - 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_nosuid_removable_partitions
      - no_reboot_needed
    - name: XCCDF Value var_removable_partition # promote to variable
      set_fact:
        var_removable_partition: !!str /dev/cdrom
      tags:
        - always

    - name: Ensure permission nosuid are set on var_removable_partition
      ansible.builtin.lineinfile:
        path: /etc/fstab
        regexp: ^\s*({{ var_removable_partition }})\s+([^\s]*)\s+([^\s]*)\s+([^\s]*)(.*)$
        backrefs: true
        line: \1 \2 \3 \4,nosuid \5
      when: ( not ( "kernel-core" 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:
      - DISA-STIG-RHEL-09-231090
      - 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_nosuid_removable_partitions
      - 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
stigref | SV-257866r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /tmp --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231125
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231125
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231125
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231125
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231125
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231125
      - 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
stigref | SV-257867r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /tmp --mountoptions="noexec"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231130
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231130
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231130
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231130
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231130
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231130
      - 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
stigref | SV-257868r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /tmp --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231135
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231135
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231135
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231135
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231135
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231135
      - 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
stigref | SV-257873r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log/audit --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231160
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231160
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231160
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231160
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231160
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231160
      - 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
stigref | SV-257874r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log/audit --mountoptions="noexec"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231165
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231165
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231165
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231165
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231165
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231165
      - 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
stigref | SV-257875r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log/audit --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231170
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231170
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231170
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231170
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231170
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231170
      - 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
stigref | SV-257870r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231145
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231145
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231145
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231145
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231145
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231145
      - 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
stigref | SV-257871r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log --mountoptions="noexec"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231150
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231150
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231150
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231150
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231150
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231150
      - 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
stigref | SV-257872r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/log --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231155
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231155
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231155
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231155
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231155
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231155
      - 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
stigref | SV-257869r1102009_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231140
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231140
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231140
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231140
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231140
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231140
      - 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 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
stigref | SV-257876r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/tmp --mountoptions="nodev"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231175
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231175
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231175
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231175
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231175
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231175
      - 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
stigref | SV-257877r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/tmp --mountoptions="noexec"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231180
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231180
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231180
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231180
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231180
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231180
      - 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
stigref | SV-257878r958804_rule

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel-core ;} && { 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 Anaconda snippet ⇲

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

    part /var/tmp --mountoptions="nosuid"

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231185
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231185
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231185
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231185
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231185
      - 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-core" 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:
      - DISA-STIG-RHEL-09-231185
      - 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 3 groups and 16 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 4 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 acquiring, saving, and processing core dumps [ref]

The `systemd-coredump.socket` unit is a socket activation of the `systemd-coredump@.service` which processes core dumps. By masking the unit, core dump processing is disabled.
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_service_systemd-coredump_disabled

References:

nist | SC-7(10)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257815r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SOCKET_NAME="systemd-coredump.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:
      - DISA-STIG-RHEL-09-213100
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-coredump_disabled

    - name: Disable acquiring, saving, and processing core dumps - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213100
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-coredump_disabled

    - name: Disable acquiring, saving, and processing core dumps - Ensure systemd-coredump.socket
        is Masked
      ansible.builtin.systemd:
        name: systemd-coredump.socket
        state: stopped
        enabled: false
        masked: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_systemd_unit_files.stdout_lines is search("systemd-coredump.socket")
      tags:
      - DISA-STIG-RHEL-09-213100
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_systemd-coredump_disabled

#### Rule Disable core dump backtraces [ref]

The `ProcessSizeMax` option in `[Coredump]` section of `/etc/systemd/coredump.conf` or in a drop-in file under `/etc/systemd/coredump.conf.d/` specifies the maximum size in bytes of a core which will be processed. Core dumps exceeding this size may be stored, but the backtrace will not be generated.
Warning: If the `/etc/systemd/coredump.conf` file or a drop-in file under `/etc/systemd/coredump.conf.d/` does not already contain the `[Coredump]` section, the value will not be configured correctly.

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 or system operators trying to debug problems. Enabling core dumps on production systems is not recommended, however there may be overriding operational requirements to enable advanced debugging. Permitting temporary enablement of core dumps during such situations should be reviewed through local needs and policy.

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

References:

nist | CM-6
pcidss | Req-3.2
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 3.3.1.1, 3.3.1, 3.3
cis | 1.5.3
stigref | SV-257812r1051005_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q systemd; }; then

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/systemd/coredump.conf.d/complianceascode_hardening.conf /etc/systemd/coredump.conf.d/*.conf /etc/systemd/coredump.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Coredump\]([^\n\[]*\n+)+?[[:space:]]*ProcessSizeMax" "$f"; then
            if ! grep -qPz "ProcessSizeMax=0" "$f"; then

                sed -i "s/ProcessSizeMax[^(\n)]*/ProcessSizeMax=0/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Coredump\]" "$f"; then

                sed -i "/[[:space:]]*\[Coredump\]/a ProcessSizeMax=0" "$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 "/etc/systemd/coredump.conf.d/complianceascode_hardening.conf /etc/systemd/coredump.conf.d/*.conf /etc/systemd/coredump.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Coredump]\nProcessSizeMax=0" >> "$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:
      - DISA-STIG-RHEL-09-213085
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_backtraces
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable core dump backtraces - Search for a section in files
      ansible.builtin.find:
        paths: '{{item.path}}'
        patterns: '{{item.pattern}}'
        contains: ^\s*\[Coredump\]
        read_whole_file: true
        use_regex: true
      register: systemd_dropin_files_with_section
      loop:
      - path: '{{ ''/etc/systemd/coredump.conf'' | dirname }}'
        pattern: '{{ ''/etc/systemd/coredump.conf'' | basename | regex_escape }}'
      - path: /etc/systemd/coredump.conf.d
        pattern: .*\.conf
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213085
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_backtraces
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable core dump backtraces - Count number of files which contain the correct
        section
      ansible.builtin.set_fact:
        count_of_systemd_dropin_files_with_section: '{{systemd_dropin_files_with_section.results
          | map(attribute=''matched'') | list | map(''int'') | sum}}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213085
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_backtraces
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable core dump backtraces - Add missing configuration to correct section
      community.general.ini_file:
        path: '{{item}}'
        section: Coredump
        option: ProcessSizeMax
        value: '0'
        state: present
        no_extra_spaces: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int > 0
      loop: '{{systemd_dropin_files_with_section.results | sum(attribute=''files'', start=[])
        | map(attribute=''path'') | list }}'
      tags:
      - DISA-STIG-RHEL-09-213085
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_backtraces
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable core dump backtraces - Add configuration to new remediation file
      community.general.ini_file:
        path: /etc/systemd/coredump.conf.d/complianceascode_hardening.conf
        section: Coredump
        option: ProcessSizeMax
        value: '0'
        state: present
        no_extra_spaces: true
        create: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int == 0
      tags:
      - DISA-STIG-RHEL-09-213085
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_backtraces
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,%23%20%20This%20file%20is%20part%20of%20systemd.%0A%23%0A%23%20%20systemd%20is%20free%20software%3B%20you%20can%20redistribute%20it%20and/or%20modify%20it%0A%23%20%20under%20the%20terms%20of%20the%20GNU%20Lesser%20General%20Public%20License%20as%20published%20by%0A%23%20%20the%20Free%20Software%20Foundation%3B%20either%20version%202.1%20of%20the%20License%2C%20or%0A%23%20%20%28at%20your%20option%29%20any%20later%20version.%0A%23%0A%23%20Entries%20in%20this%20file%20show%20the%20compile%20time%20defaults.%0A%23%20You%20can%20change%20settings%20by%20editing%20this%20file.%0A%23%20Defaults%20can%20be%20restored%20by%20simply%20deleting%20this%20file.%0A%23%0A%23%20See%20coredump.conf%285%29%20for%20details.%0A%0A%5BCoredump%5D%0A%23Storage%3Dexternal%0A%23Compress%3Dyes%0A%23ProcessSizeMax%3D2G%0A%23ExternalSizeMax%3D2G%0A%23JournalSizeMax%3D767M%0A%23MaxUse%3D%0A%23KeepFree%3D%0AStorage%3Dnone%0AProcessSizeMax%3D0%0A
            mode: 0644
            path: /etc/systemd/coredump.conf
            overwrite: true

#### Rule Disable storing core dump [ref]

The `Storage` option in `[Coredump]` section of `/etc/systemd/coredump.conf` or a drop-in file in `/etc/systemd/coredump.conf.d/*.conf` can be set to `none` to disable storing core dumps permanently. Warning: If the `/etc/systemd/coredump.conf` file or a drop-in file under `/etc/systemd/coredump.conf.d/` does not already contain the `[Coredump]` section, the value will not be configured correctly.

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 or system operators trying to debug problems. Enabling core dumps on production systems is not recommended, however there may be overriding operational requirements to enable advanced debugging. Permitting temporary enablement of core dumps during such situations should be reviewed through local needs and policy.

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

References:

nist | CM-6
pcidss | Req-3.2
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 3.3.1.1, 3.3.1, 3.3
cis | 1.5.4
stigref | SV-257813r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q systemd; }; then

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/systemd/coredump.conf.d/complianceascode_hardening.conf /etc/systemd/coredump.conf.d/*.conf /etc/systemd/coredump.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[Coredump\]([^\n\[]*\n+)+?[[:space:]]*Storage" "$f"; then
            if ! grep -qPz "Storage=none" "$f"; then

                sed -i "s/Storage[^(\n)]*/Storage=none/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[Coredump\]" "$f"; then

                sed -i "/[[:space:]]*\[Coredump\]/a Storage=none" "$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 "/etc/systemd/coredump.conf.d/complianceascode_hardening.conf /etc/systemd/coredump.conf.d/*.conf /etc/systemd/coredump.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[Coredump]\nStorage=none" >> "$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:
      - DISA-STIG-RHEL-09-213090
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable storing core dump - Search for a section in files
      ansible.builtin.find:
        paths: '{{item.path}}'
        patterns: '{{item.pattern}}'
        contains: ^\s*\[Coredump\]
        read_whole_file: true
        use_regex: true
      register: systemd_dropin_files_with_section
      loop:
      - path: '{{ ''/etc/systemd/coredump.conf'' | dirname }}'
        pattern: '{{ ''/etc/systemd/coredump.conf'' | basename | regex_escape }}'
      - path: /etc/systemd/coredump.conf.d
        pattern: .*\.conf
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213090
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable storing core dump - Count number of files which contain the correct
        section
      ansible.builtin.set_fact:
        count_of_systemd_dropin_files_with_section: '{{systemd_dropin_files_with_section.results
          | map(attribute=''matched'') | list | map(''int'') | sum}}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213090
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable storing core dump - Add missing configuration to correct section
      community.general.ini_file:
        path: '{{item}}'
        section: Coredump
        option: Storage
        value: none
        state: present
        no_extra_spaces: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int > 0
      loop: '{{systemd_dropin_files_with_section.results | sum(attribute=''files'', start=[])
        | map(attribute=''path'') | list }}'
      tags:
      - DISA-STIG-RHEL-09-213090
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable storing core dump - Add configuration to new remediation file
      community.general.ini_file:
        path: /etc/systemd/coredump.conf.d/complianceascode_hardening.conf
        section: Coredump
        option: Storage
        value: none
        state: present
        no_extra_spaces: true
        create: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"systemd" in ansible_facts.packages'
      - count_of_systemd_dropin_files_with_section | int == 0
      tags:
      - DISA-STIG-RHEL-09-213090
      - NIST-800-53-CM-6
      - PCI-DSS-Req-3.2
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - coredump_disable_storage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,%23%20%20This%20file%20is%20part%20of%20systemd.%0A%23%0A%23%20%20systemd%20is%20free%20software%3B%20you%20can%20redistribute%20it%20and/or%20modify%20it%0A%23%20%20under%20the%20terms%20of%20the%20GNU%20Lesser%20General%20Public%20License%20as%20published%20by%0A%23%20%20the%20Free%20Software%20Foundation%3B%20either%20version%202.1%20of%20the%20License%2C%20or%0A%23%20%20%28at%20your%20option%29%20any%20later%20version.%0A%23%0A%23%20Entries%20in%20this%20file%20show%20the%20compile%20time%20defaults.%0A%23%20You%20can%20change%20settings%20by%20editing%20this%20file.%0A%23%20Defaults%20can%20be%20restored%20by%20simply%20deleting%20this%20file.%0A%23%0A%23%20See%20coredump.conf%285%29%20for%20details.%0A%0A%5BCoredump%5D%0A%23Storage%3Dexternal%0A%23Compress%3Dyes%0A%23ProcessSizeMax%3D2G%0A%23ExternalSizeMax%3D2G%0A%23JournalSizeMax%3D767M%0A%23MaxUse%3D%0A%23KeepFree%3D%0AStorage%3Dnone%0AProcessSizeMax%3D0%0A
            mode: 0644
            path: /etc/systemd/coredump.conf
            overwrite: true

#### 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
pcidss4 | 3.3.1.1, 3.3.1, 3.3
stigref | SV-257814r991589_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q pam; }; 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:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - invalid_dropins | length > 0
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not (valid_dropins.matched | default(0) > 0)
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not core_limit_valid
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"pam" in ansible_facts.packages'
      - not core_limit_valid
      tags:
      - DISA-STIG-RHEL-09-213095
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,%2A%20%20%20%20%20hard%20%20%20core%20%20%20%200
            mode: 0644
            path: /etc/security/limits.d/75-disable_users_coredumps.conf
            overwrite: true

Group Enable ExecShield Group contains 3 rules

[ref] ExecShield describes kernel features that provide protection against exploitation of memory corruption errors such as buffer overflows. These features include random placement of the stack and other memory regions, prevention of execution in memory that should only hold data, and special handling of text buffers. These protections are enabled by default on 32-bit systems and controlled through `sysctl` variables `kernel.exec-shield` and `kernel.randomize_va_space`. On the latest 64-bit systems, `kernel.exec-shield` cannot be enabled or disabled with `sysctl`.

#### Rule Enable ExecShield via sysctl [ref]

By default on Red Hat Enterprise Linux 9 64-bit systems, ExecShield is enabled and can only be disabled if the hardware does not support ExecShield or is disabled in `/etc/default/grub`.

Rationale:

ExecShield uses the segmentation feature on all x86 systems to prevent execution in memory higher than a certain address. It writes an address as a limit in the code segment descriptor, to control where code can be executed, on a per-process basis. When the kernel places a process's memory regions such as the stack and heap higher than this address, the hardware prevents execution in that address range. This is enabled by default on the latest Red Hat and Fedora systems if supported by the hardware.

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

References:

cis-csc | 12, 15, 8
cobit5 | APO13.01, DSS05.02
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)
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 | SC-39, CM-6(a)
nist-csf | PR.PT-4
os-srg | SRG-OS-000433-GPOS-00192
ism | 1409
stigref | SV-257817r1069383_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if ( rpm --quiet -q kernel-core && ( grep -sqE "^.*\.x86_64$" /proc/sys/kernel/osrelease || grep -sqE "^x86_64$" /proc/sys/kernel/arch; ) ); then

    grubby --update-kernel=ALL --remove-args=noexec

    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:
      - DISA-STIG-RHEL-09-213110
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-39
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - sysctl_kernel_exec_shield

    - name: Check if noexec argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when: ( "kernel-core" in ansible_facts.packages and ansible_architecture == "x86_64"
        )
      tags:
      - DISA-STIG-RHEL-09-213110
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-39
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - sysctl_kernel_exec_shield

    - name: Check if noexec argument is present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when: ( "kernel-core" in ansible_facts.packages and ansible_architecture == "x86_64"
        )
      tags:
      - DISA-STIG-RHEL-09-213110
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-39
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - sysctl_kernel_exec_shield

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --remove-args="noexec"
      when:
      - ( "kernel-core" in ansible_facts.packages and ansible_architecture == "x86_64"
        )
      - (grubby_info.stdout is search('noexec')) or ((etc_default_grub['content'] | b64decode)
        is search('noexec'))
      tags:
      - DISA-STIG-RHEL-09-213110
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-39
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - sysctl_kernel_exec_shield

#### Rule Restrict Exposed Kernel Pointer Addresses Access [ref]

To set the runtime status of the `kernel.kptr_restrict` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.kptr_restrict=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.kptr_restrict = 1

Rationale:

Exposing kernel pointers (through procfs or `seq_printf()`) exposes kernel writeable structures which may contain functions pointers. If a write vulnerability occurs in the kernel, allowing write access to any of this structure, the kernel can be compromised. This option disallow any program without the CAP_SYSLOG capability to get the addresses of kernel pointers by replacing them with 0.

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

References:

nerc-cip | CIP-002-5 R1.1, CIP-002-5 R1.2, CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 4.1, CIP-004-6 4.2, CIP-004-6 R2.2.3, CIP-004-6 R2.2.4, CIP-004-6 R2.3, CIP-004-6 R4, CIP-005-6 R1, CIP-005-6 R1.1, CIP-005-6 R1.2, CIP-007-3 R3, CIP-007-3 R3.1, CIP-007-3 R5.1, CIP-007-3 R5.1.2, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3, CIP-007-3 R8.4, CIP-009-6 R.1.1, CIP-009-6 R4
nist | SC-30, SC-30(2), SC-30(5), CM-6(a)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000433-GPOS-00192, SRG-OS-000480-GPOS-00227
anssi | R9
ism | 1409
stigref | SV-257800r1117266_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.kptr_restrict from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_kernel_kptr_restrict_value='1'

    #
    # Set runtime for kernel.kptr_restrict
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.kptr_restrict="$sysctl_kernel_kptr_restrict_value"
    fi

    #
    # If kernel.kptr_restrict present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "kernel.kptr_restrict = value" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^kernel.kptr_restrict")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^kernel.kptr_restrict\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.kptr_restrict\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict
    - name: XCCDF Value sysctl_kernel_kptr_restrict_value # promote to variable
      set_fact:
        sysctl_kernel_kptr_restrict_value: !!str 1
      tags:
        - always

    - name: Restrict Exposed Kernel Pointer Addresses Access - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Find all files that contain
        kernel.kptr_restrict
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kptr_restrict\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Find all files that set
        kernel.kptr_restrict to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kptr_restrict\s*=\s*{{ sysctl_kernel_kptr_restrict_value }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Comment out any occurrences
        of kernel.kptr_restrict from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.kptr_restrict
        replace: '#kernel.kptr_restrict'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Ensure sysctl kernel.kptr_restrict
        is set
      ansible.posix.sysctl:
        name: kernel.kptr_restrict
        value: '{{ sysctl_kernel_kptr_restrict_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213025
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.kptr_restrict%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_kptr_restrict.conf
            overwrite: true

#### Rule Enable Randomized Layout of Virtual Address Space [ref]

To set the runtime status of the `kernel.randomize_va_space` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.randomize_va_space=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.randomize_va_space = 2

Rationale: | Address space layout randomization (ASLR) makes it more difficult for an attacker to predict the location of attack code they have introduced into a process's address space during an attempt at exploitation. Additionally, ASLR makes it more difficult for an attacker to know the location of existing code in order to re-purpose it using return oriented programming (ROP) techniques.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_randomize_va_space

References:

cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3), 164.308(a)(4), 164.310(b), 164.310(c), 164.312(a), 164.312(e)
nerc-cip | CIP-002-5 R1.1, CIP-002-5 R1.2, CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 4.1, CIP-004-6 4.2, CIP-004-6 R2.2.3, CIP-004-6 R2.2.4, CIP-004-6 R2.3, CIP-004-6 R4, CIP-005-6 R1, CIP-005-6 R1.1, CIP-005-6 R1.2, CIP-007-3 R3, CIP-007-3 R3.1, CIP-007-3 R5.1, CIP-007-3 R5.1.2, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3, CIP-007-3 R8.4, CIP-009-6 R.1.1, CIP-009-6 R4
nist | SC-30, SC-30(2), CM-6(a)
pcidss | Req-2.2.1
os-srg | SRG-OS-000433-GPOS-00193, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000450-CTR-001105
anssi | R9
ism | 1409
pcidss4 | 3.3.1.1, 3.3.1, 3.3
cis | 1.5.1
stigref | SV-257809r1106288_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213070
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213070
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213070
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213070
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.randomize_va_space%3D2%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_randomize_va_space.conf
            overwrite: true

Group Memory Poisoning Group contains 1 rule
[ref] Memory Poisoning consists of writing a special value to uninitialized or freed memory. Poisoning can be used as a mechanism to prevent leak of information and detection of corrupted memory.

#### Rule Enable page allocator poisoning [ref]

To enable poisoning of free pages, add the argument `page_poison=1` to the default GRUB 2 command line for the Linux operating system. To ensure that `page_poison=1` is added as a kernel command line argument to newly installed kernels, add `page_poison=1` to the default Grub2 command line for Linux operating systems. Modify the line within `/etc/default/grub` as shown below:

    GRUB_CMDLINE_LINUX="... page_poison=1 ..."

Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --args="page_poison=1"

If the system is distributed as a bootable container image, GRUB2 can't be configured using the method described above, but the following method needs to be used instead. The kernel arguments should be set in `/usr/lib/bootc/kargs.d` in a TOML file that has the following form:

    # /usr/lib/bootc/kargs.d/10-example.toml
    kargs = ["page_poison=1"]

For more details on configuring kernel arguments in bootable container images, please refer to Bootc documentation.

Rationale: | Poisoning writes an arbitrary value to freed pages, so any modification or reference to that page after being freed or before being initialized will be detected and prevented. This prevents many types of use-after-free vulnerabilities at little performance cost. Also prevents leak of data and detection of corrupted memory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_page_poison_argument

References:

nist | CM-6(a)
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000134-GPOS-00068
anssi | R8
stigref | SV-257793r1044843_rule

Remediation script ⇲

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

    bootloader page_poison=1

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q grub2-common; }; then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "page_poison" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"page_poison=[^\"]*\"(.*]\s*)/\1\"page_poison=1\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"page_poison=1\"]" >> "$KARGS_DIR/10-page_poison.toml"
        fi
    else

        grubby --update-kernel=ALL --args=page_poison=1

    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:
      - DISA-STIG-RHEL-09-212040
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if page_poison argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212040
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check if page_poison argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-212040
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /sbin/grubby --update-kernel=ALL --args="page_poison=1"
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - (grubby_info.stdout is not search('page_poison=1')) or ((etc_default_grub['content']
        | b64decode) is not search('page_poison=1'))
      tags:
      - DISA-STIG-RHEL-09-212040
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "page_poison=1"

#### Rule Disable storing core dumps [ref]

To set the runtime status of the `kernel.core_pattern` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.core_pattern=|/bin/false

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.core_pattern = |/bin/false

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_sysctl_kernel_core_pattern

References:

nist | SC-7(10)
os-srg | SRG-OS-000480-GPOS-00227
pcidss4 | 3.3.1.1, 3.3.1, 3.3
stigref | SV-257803r1106429_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.core_pattern from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/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.core_pattern.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.core_pattern" 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.core_pattern
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.core_pattern="|/bin/false"
    fi

    #
    # If kernel.core_pattern present in /etc/sysctl.conf, change value to "|/bin/false"
    #	else, add "kernel.core_pattern = |/bin/false" 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.core_pattern")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "|/bin/false"

    # 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.core_pattern\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.core_pattern\\>.*/$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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

    - name: Disable storing core dumps - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

    - name: Disable storing core dumps - Find all files that contain kernel.core_pattern
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.core_pattern\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

    - name: Disable storing core dumps - Find all files that set kernel.core_pattern to
        correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.core_pattern\s*=\s*\|/bin/false$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

    - name: Disable storing core dumps - Comment out any occurrences of kernel.core_pattern
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.core_pattern
        replace: '#kernel.core_pattern'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

    - name: Disable storing core dumps - Ensure sysctl kernel.core_pattern is set to |/bin/false
      ansible.posix.sysctl:
        name: kernel.core_pattern
        value: '|/bin/false'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213040
      - NIST-800-53-SC-7(10)
      - 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_core_pattern

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.core_pattern%20%3D%20%7C/bin/false%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_core_pattern.conf
            overwrite: true

#### Rule Restrict Access to Kernel Message Buffer [ref]

To set the runtime status of the `kernel.dmesg_restrict` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.dmesg_restrict=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.dmesg_restrict = 1

Rationale: | Unprivileged access to the kernel syslog can expose sensitive kernel address information.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_dmesg_restrict

References:

cui | 3.1.5
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3), 164.308(a)(4), 164.310(b), 164.310(c), 164.312(a), 164.312(e)
nist | SI-11(a), SI-11(b)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000138-GPOS-00069
app-srg-ctr | SRG-APP-000243-CTR-000600
anssi | R9
ism | 1546
stigref | SV-257797r1117266_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.dmesg_restrict from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.dmesg_restrict
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.dmesg_restrict="1"
    fi

    #
    # If kernel.dmesg_restrict present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.dmesg_restrict = 1" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^kernel.dmesg_restrict")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^kernel.dmesg_restrict\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.dmesg_restrict\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Find all files that contain kernel.dmesg_restrict
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.dmesg_restrict\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Find all files that set kernel.dmesg_restrict
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.dmesg_restrict\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Comment out any occurrences of
        kernel.dmesg_restrict from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.dmesg_restrict
        replace: '#kernel.dmesg_restrict'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Ensure sysctl kernel.dmesg_restrict
        is set to 1
      ansible.posix.sysctl:
        name: kernel.dmesg_restrict
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213010
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.dmesg_restrict%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_dmesg_restrict.conf
            overwrite: true

#### Rule Disable Kernel Image Loading [ref]

To set the runtime status of the `kernel.kexec_load_disabled` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.kexec_load_disabled=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.kexec_load_disabled = 1

Rationale: | Disabling kexec_load allows greater control of the kernel memory. It makes it impossible to load another kernel image after it has been disabled.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_kexec_load_disabled

References:

nist | CM-6
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000366-GPOS-00153
ism | 1409
stigref | SV-257799r1106273_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.kexec_load_disabled from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/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.kexec_load_disabled.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.kexec_load_disabled" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.kexec_load_disabled
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.kexec_load_disabled="1"
    fi

    #
    # If kernel.kexec_load_disabled present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.kexec_load_disabled = 1" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^kernel.kexec_load_disabled")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^kernel.kexec_load_disabled\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.kexec_load_disabled\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

    - name: Disable Kernel Image Loading - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

    - name: Disable Kernel Image Loading - Find all files that contain kernel.kexec_load_disabled
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kexec_load_disabled\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

    - name: Disable Kernel Image Loading - Find all files that set kernel.kexec_load_disabled
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kexec_load_disabled\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

    - name: Disable Kernel Image Loading - Comment out any occurrences of kernel.kexec_load_disabled
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.kexec_load_disabled
        replace: '#kernel.kexec_load_disabled'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

    - name: Disable Kernel Image Loading - Ensure sysctl kernel.kexec_load_disabled is
        set to 1
      ansible.posix.sysctl:
        name: kernel.kexec_load_disabled
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213020
      - NIST-800-53-CM-6
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kexec_load_disabled

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.kexec_load_disabled%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_kexec_load_disabled.conf
            overwrite: true

#### Rule Disallow kernel profiling by unprivileged users [ref]

To set the runtime status of the `kernel.perf_event_paranoid` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.perf_event_paranoid=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.perf_event_paranoid = 2

Rationale: | Kernel profiling can reveal sensitive information about kernel behaviour.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_perf_event_paranoid

References:

nist | AC-6
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000138-GPOS-00069
app-srg-ctr | SRG-APP-000243-CTR-000600
anssi | R9
stigref | SV-257798r1117266_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.perf_event_paranoid from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.perf_event_paranoid
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.perf_event_paranoid="2"
    fi

    #
    # If kernel.perf_event_paranoid present in /etc/sysctl.conf, change value to "2"
    #	else, add "kernel.perf_event_paranoid = 2" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^kernel.perf_event_paranoid")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^kernel.perf_event_paranoid\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.perf_event_paranoid\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Find all files that contain
        kernel.perf_event_paranoid
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_paranoid\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Find all files that set
        kernel.perf_event_paranoid to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_paranoid\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Comment out any occurrences
        of kernel.perf_event_paranoid from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.perf_event_paranoid
        replace: '#kernel.perf_event_paranoid'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Ensure sysctl kernel.perf_event_paranoid
        is set to 2
      ansible.posix.sysctl:
        name: kernel.perf_event_paranoid
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213015
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.perf_event_paranoid%3D2%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_perf_event_paranoid.conf
            overwrite: true

#### Rule Disable Access to Network bpf() Syscall From Unprivileged Processes [ref]

To set the runtime status of the `kernel.unprivileged_bpf_disabled` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.unprivileged_bpf_disabled=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.unprivileged_bpf_disabled = 1

Rationale: | Loading and accessing the packet filters programs and maps using the bpf() syscall has the potential of revealing sensitive information about the kernel state.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_unprivileged_bpf_disabled

References:

nist | AC-6, SC-7(10)
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000480-GPOS-00227
anssi | R9
ism | 1409
stigref | SV-257810r1117266_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of kernel.unprivileged_bpf_disabled from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

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

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.unprivileged_bpf_disabled
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w kernel.unprivileged_bpf_disabled="1"
    fi

    #
    # If kernel.unprivileged_bpf_disabled present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.unprivileged_bpf_disabled = 1" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^kernel.unprivileged_bpf_disabled")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^kernel.unprivileged_bpf_disabled\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.unprivileged_bpf_disabled\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Set
        fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Find
        all files that contain kernel.unprivileged_bpf_disabled
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.unprivileged_bpf_disabled\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Find
        all files that set kernel.unprivileged_bpf_disabled to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.unprivileged_bpf_disabled\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Comment
        out any occurrences of kernel.unprivileged_bpf_disabled from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.unprivileged_bpf_disabled
        replace: '#kernel.unprivileged_bpf_disabled'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Ensure
        sysctl kernel.unprivileged_bpf_disabled is set to 1
      ansible.posix.sysctl:
        name: kernel.unprivileged_bpf_disabled
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213075
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.unprivileged_bpf_disabled%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_unprivileged_bpf_disabled.conf
            overwrite: true

#### Rule Restrict usage of ptrace to descendant processes [ref]

To set the runtime status of the `kernel.yama.ptrace_scope` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.yama.ptrace_scope=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.yama.ptrace_scope = 1

Rationale: | Unrestricted usage of ptrace allows compromised binaries to run ptrace on another processes of the user. Like this, the attacker can steal sensitive information from the target processes (e.g. SSH sessions, web browser, ...) without any additional assistance from the user (i.e. without resorting to phishing).
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_yama_ptrace_scope

References:

nist | SC-7(10)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000480-GPOS-00227
anssi | R11
ism | 1409
cis | 1.5.2
stigref | SV-257811r1117266_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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; 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 ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-213080
      - 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/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213080
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213080
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213080
      - 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:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-213080
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-213080
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,kernel.yama.ptrace_scope%3D1%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_kernel_yama_ptrace_scope.conf
            overwrite: true

#### Rule Harden the operation of the BPF just-in-time compiler [ref]

To set the runtime status of the `net.core.bpf_jit_harden` kernel parameter, run the following command:

    $ sudo sysctl -w net.core.bpf_jit_harden=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.core.bpf_jit_harden = 2

Rationale: | When hardened, the extended Berkeley Packet Filter just-in-time compiler will randomize any kernel addresses in the BPF programs and maps, and will not expose the JIT addresses in `/proc/kallsyms`.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_core_bpf_jit_harden

References:

nist | CM-6, SC-7(10)
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
ism | 1409
stigref | SV-257942r1106314_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    # Comment out any occurrences of net.core.bpf_jit_harden from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.core.bpf_jit_harden.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.core.bpf_jit_harden" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.core.bpf_jit_harden
    #
    if ! { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; then
        /sbin/sysctl -q -n -w net.core.bpf_jit_harden="2"
    fi

    #
    # If net.core.bpf_jit_harden present in /etc/sysctl.conf, change value to "2"
    #	else, add "net.core.bpf_jit_harden = 2" to /etc/sysctl.conf
    #

    # Strip any search characters in the key arg so that the key can be replaced without
    # adding any search characters to the config file.
    stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "^net.core.bpf_jit_harden")

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

    # If the key exists, change it. Otherwise, add it to the config_file.
    # We search for the key string followed by a word boundary (matched by \>),
    # so if we search for 'setting', 'setting2' won't match.
    if LC_ALL=C grep -q -m 1 -i -e "^net.core.bpf_jit_harden\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.core.bpf_jit_harden\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "${SYSCONFIG_FILE}" >> "${SYSCONFIG_FILE}"
        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:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Find all files that
        contain net.core.bpf_jit_harden
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.core.bpf_jit_harden\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Find all files that
        set net.core.bpf_jit_harden to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.core.bpf_jit_harden\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Comment out any occurrences
        of net.core.bpf_jit_harden from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.core.bpf_jit_harden
        replace: '#net.core.bpf_jit_harden'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Ensure sysctl net.core.bpf_jit_harden
        is set to 2
      ansible.posix.sysctl:
        name: net.core.bpf_jit_harden
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251045
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,net.core.bpf_jit_harden%3D2%0A
            mode: 0644
            path: /etc/sysctl.d/75-sysctl_net_core_bpf_jit_harden.conf
            overwrite: true

#### Rule Disable the use of user namespaces [ref]

To set the runtime status of the `user.max_user_namespaces` kernel parameter, run the following command:

    $ sudo sysctl -w user.max_user_namespaces=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    user.max_user_namespaces = 0

When containers are deployed on the machine, the value should be set to large non-zero value.
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 to host Linux Containers, it is expected that `user.max_user_namespaces` will be enabled. Note that this rule deliberately does not have remediations attached. Use the `sysctl_user_max_user_namespaces` if you want to utilize remediation for this rule.

Rationale:

It is detrimental for operating systems to provide, or install by default, functionality exceeding requirements or system objectives. These unnecessary capabilities or services are often overlooked and therefore may remain unsecured. They increase the risk to the platform by providing additional attack vectors. User namespaces are used primarily for Linux containers. The value 0 disallows the use of user namespaces.

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

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257816r1106435_rule

Group SELinux Group contains 6 rules

[ref] SELinux is a feature of the Linux kernel which can be used to guard against misconfigured or compromised programs. SELinux enforces the idea that programs should be limited in what files they can access and what actions they can take.
The default SELinux policy, as configured on Red Hat Enterprise Linux 9, has been sufficiently developed and debugged that it should be usable on almost any system with minimal configuration and a small amount of system administrator training. This policy prevents system services - including most of the common network-visible services such as mail servers, FTP servers, and DNS servers - from accessing files which those services have no valid reason to access. This action alone prevents a huge amount of possible damage from network attacks against services, from trojaned software, and so forth.
This guide recommends that SELinux be enabled using the default (targeted) policy on every Red Hat Enterprise Linux 9 system, unless that system has unusual requirements which make a stronger policy appropriate.

#### Rule Install policycoreutils-python-utils package [ref]

The `policycoreutils-python-utils` package can be installed with the following command:

    $ sudo dnf install policycoreutils-python-utils

Rationale: | This package is required to operate and manage an SELinux environment and its policies. It provides utilities such as semanage, audit2allow, audit2why, chcat and sandbox.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_policycoreutils-python-utils_installed

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258082r1045166_rule

Remediation script ⇲

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

    dnf install policycoreutils-python-utils

Remediation script ⇲

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

    package install policycoreutils-python-utils

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "policycoreutils-python-utils" ; then
        dnf install -y "policycoreutils-python-utils"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_policycoreutils-python-utils

    class install_policycoreutils-python-utils {
      package { 'policycoreutils-python-utils':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=policycoreutils-python-utils

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-431030
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_policycoreutils-python-utils_installed

    - name: Ensure policycoreutils-python-utils is installed
      ansible.builtin.package:
        name: policycoreutils-python-utils
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431030
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_policycoreutils-python-utils_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "policycoreutils-python-utils"
    version = "*"

#### Rule Install policycoreutils Package [ref]

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

    $ sudo dnf install policycoreutils

Rationale:

Security-enhanced Linux is a feature of the Linux kernel and a number of utilities with enhanced security functionality designed to add mandatory access controls to Linux. The Security-enhanced Linux kernel contains new architectural components originally developed to improve security of the Flask operating system. These architectural components provide general support for the enforcement of many kinds of mandatory access control policies, including those based on the concepts of Type Enforcement, Role-based Access Control, and Multi-level Security. `policycoreutils` contains the policy core utilities that are required for basic operation of an SELinux-enabled system. These utilities include `load_policy` to load SELinux policies, `setfiles` to label filesystems, `newrole` to switch roles, and so on.

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

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000134-GPOS-00068
stigref | SV-258081r1045164_rule

Remediation script ⇲

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

    dnf install policycoreutils

Remediation script ⇲

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

    package install policycoreutils

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "policycoreutils" ; then
        dnf install -y "policycoreutils"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_policycoreutils

    class install_policycoreutils {
      package { 'policycoreutils':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=policycoreutils

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-431025
      - enable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_policycoreutils_installed

    - name: Ensure policycoreutils is installed
      ansible.builtin.package:
        name: policycoreutils
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431025
      - enable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_policycoreutils_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Ensure No Device Files are Unlabeled by SELinux [ref]

Device files, which are used for communication with important system resources, should be labeled with proper SELinux types. If any device files carry the SELinux type `device_t` or `unlabeled_t`, report the bug so that policy can be corrected. Supply information about what the device is and what programs use it.
To check for incorrectly labeled device files, run following commands:

    $ sudo find /dev -context *:device_t:* \( -type c -o -type b \) -printf "%p %Z\n"

    $ sudo find /dev -context *:unlabeled_t:* \( -type c -o -type b \) -printf "%p %Z\n"

It should produce no output in a well-configured system.
Warning: Automatic remediation of this control is not available. The remediation can be achieved by amending SELinux policy.

Rationale: | If a device file carries the SELinux type `device_t` or `unlabeled_t`, then SELinux cannot properly restrict access to the device file.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_selinux_all_devicefiles_labeled

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO01.06, APO11.04, BAI01.06, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06, MEA02.01
cui | 3.1.2, 3.1.5, 3.7.2
isa-62443-2009 | 4.3.3.3.9, 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.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.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.10, SR 2.11, SR 2.12, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 2.8, SR 2.9, SR 5.2, SR 6.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.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.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.14.2.7, A.15.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), AC-3(3)(a), AC-6
nist-csf | DE.CM-1, DE.CM-7, PR.AC-4, PR.DS-5, PR.IP-1, PR.IP-3, PR.PT-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257932r1014838_rule

#### Rule Elevate The SELinux Context When An Administrator Calls The Sudo Command [ref]

Configure the operating system to elevate the SELinux context when an administrator calls the sudo command. Edit a file in the /etc/sudoers.d directory with the following command:

    sudo visudo -f /etc/sudoers.d/CUSTOM_FILE

Use the following example to build the CUSTOM_FILE in the /etc/sudoers.d directory to allow any administrator belonging to a designated sudoers admin group to elevate their SELinux context with the use of the sudo command:

    %wheel ALL=(ALL) TYPE=sysadm_t ROLE=sysadm_r ALL

Rationale:

Preventing non-privileged users from executing privileged functions mitigates the risk that unauthorized individuals or processes may gain unnecessary access to information or privileges.
Privileged functions include, for example, establishing accounts, performing system integrity checks, or administering cryptographic key management activities. Non-privileged users are individuals who do not possess appropriate authorizations. Circumventing intrusion detection and prevention mechanisms or malicious code protection mechanisms are examples of privileged functions that require protection from non-privileged users.

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

References:

nist | AC-3(4), AC-6(10)
os-srg | SRG-OS-000324-GPOS-00125
stigref | SV-272496r1082184_rule

#### Rule Configure SELinux Policy [ref]

The SELinux `targeted` policy is appropriate for general-purpose desktops and servers, as well as systems in many other roles. To configure the system to use this policy, add or correct the following line in `/etc/selinux/config`:

    SELINUXTYPE=targeted

Other policies, such as `mls`, provide additional security labeling and greater confinement but are not compatible with many general-purpose use cases.

Rationale:

Setting the SELinux policy to `targeted` or a more specialized policy ensures the system will confine processes that are likely to be targeted for exploitation, such as network or system services.
Note: During the development or debugging of SELinux modules, it is common to temporarily place non-production systems in `permissive` mode. In such temporary cases, SELinux policies should be developed, and once work is completed, the system should be reconfigured to `targeted`.

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

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, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.03, DSS06.06, MEA02.01
cui | 3.1.2, 3.7.2
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)
isa-62443-2009 | 4.2.3.4, 4.3.3.2.2, 4.3.3.3.9, 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.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4, 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.10, SR 2.11, SR 2.12, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, 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.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.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
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.2, CIP-003-8 R5.3, CIP-004-6 R2.2.3, CIP-004-6 R2.3, CIP-004-6 R3.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, CIP-007-3 R6.5
nist | AC-3, AC-3(3)(a), AU-9, SC-7(21)
nist-csf | DE.AE-1, ID.AM-3, PR.AC-4, PR.AC-5, PR.AC-6, PR.DS-5, PR.PT-1, PR.PT-3, PR.PT-4
ospp | FMT_MOF_EXT.1
os-srg | SRG-OS-000445-GPOS-00199
app-srg-ctr | SRG-APP-000233-CTR-000585
anssi | R46, R64
bsi | APP.4.4.A4, SYS.1.6.A3, SYS.1.6.A18, SYS.1.6.A21, SYS.1.1.A37, SYS.1.1.A31, SYS.1.3.A10
ism | 1409
pcidss4 | 1.2.6, 1.2
cis | 1.3.1.3
stigref | SV-258079r1045159_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_selinux_policy_name='targeted'

    if [ -e "/etc/selinux/config" ] ; then

        LC_ALL=C sed -i "/^SELINUXTYPE=/Id" "/etc/selinux/config"
    else
        touch "/etc/selinux/config"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/selinux/config"

    cp "/etc/selinux/config" "/etc/selinux/config.bak"
    # Insert at the end of the file
    printf '%s\n' "SELINUXTYPE=$var_selinux_policy_name" >> "/etc/selinux/config"
    # Clean up after ourselves.
    rm "/etc/selinux/config.bak"

    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:
      - DISA-STIG-RHEL-09-431015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - selinux_policytype
    - name: XCCDF Value var_selinux_policy_name # promote to variable
      set_fact:
        var_selinux_policy_name: !!str targeted
      tags:
        - always

    - name: Configure SELinux Policy
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUXTYPE=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/selinux/config
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUXTYPE=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/selinux/config
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUXTYPE=
          line: SELINUXTYPE={{ var_selinux_policy_name }}
          state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431015
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - selinux_policytype

#### Rule Ensure SELinux State is Enforcing [ref]

The SELinux state should be set to `enforcing` at system boot time. In the file `/etc/selinux/config`, add or correct the following line to configure the system to boot into enforcing mode:

    SELINUX=enforcing

Ensure that all files have correct SELinux labels by running:

    fixfiles onboot

Then reboot the system.

Rationale: | Setting the SELinux state to enforcing ensures SELinux is able to confine potentially compromised processes to the security policy, which is designed to prevent them from causing damage to the system or further elevating their privileges.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_selinux_state

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, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.03, DSS06.06, MEA02.01
cui | 3.1.2, 3.7.2
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)
isa-62443-2009 | 4.2.3.4, 4.3.3.2.2, 4.3.3.3.9, 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.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4, 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.10, SR 2.11, SR 2.12, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, 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.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.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
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.2, CIP-003-8 R5.3, CIP-004-6 R2.2.3, CIP-004-6 R2.3, CIP-004-6 R3.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, CIP-007-3 R6.5
nist | AC-3, AC-3(3)(a), AU-9, SC-7(21)
nist-csf | DE.AE-1, ID.AM-3, PR.AC-4, PR.AC-5, PR.AC-6, PR.DS-5, PR.PT-1, PR.PT-3, PR.PT-4
ospp | FMT_MOF_EXT.1
os-srg | SRG-OS-000445-GPOS-00199, SRG-OS-000134-GPOS-00068
anssi | R37, R79
bsi | APP.4.4.A4, SYS.1.6.A3, SYS.1.6.A18, SYS.1.6.A21, SYS.1.1.A37, SYS.1.1.A31, SYS.1.3.A10
ism | 1409
pcidss4 | 1.2.6, 1.2
cis | 1.3.1.5
stigref | SV-258078r958944_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_selinux_state='enforcing'

    if [ -e "/etc/selinux/config" ] ; then

        LC_ALL=C sed -i "/^SELINUX=/Id" "/etc/selinux/config"
    else
        touch "/etc/selinux/config"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/selinux/config"

    cp "/etc/selinux/config" "/etc/selinux/config.bak"
    # Insert at the end of the file
    printf '%s\n' "SELINUX=$var_selinux_state" >> "/etc/selinux/config"
    # Clean up after ourselves.
    rm "/etc/selinux/config.bak"

    fixfiles onboot

    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:
      - DISA-STIG-RHEL-09-431010
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - selinux_state
    - name: XCCDF Value var_selinux_state # promote to variable
      set_fact:
        var_selinux_state: !!str enforcing
      tags:
        - always

    - name: Ensure SELinux State is Enforcing - Check current SELinux state
      ansible.builtin.command:
        cmd: getenforce
      register: selinux_state
      check_mode: false
      changed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431010
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - selinux_state

    - name: Ensure SELinux State is Enforcing
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUX=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/selinux/config
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUX=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/selinux/config
        ansible.builtin.lineinfile:
          path: /etc/selinux/config
          create: true
          regexp: (?i)^SELINUX=
          line: SELINUX={{ var_selinux_state }}
          state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-431010
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - selinux_state

    - name: Ensure SELinux State is Enforcing - Mark system to relabel SELinux on next
        boot
      ansible.builtin.file:
        path: /.autorelabel
        state: touch
        access_time: preserve
        modification_time: preserve
      when:
      - '"kernel-core" in ansible_facts.packages'
      - selinux_state.stdout | lower != var_selinux_state
      tags:
      - DISA-STIG-RHEL-09-431010
      - NIST-800-171-3.1.2
      - NIST-800-171-3.7.2
      - NIST-800-53-AC-3
      - NIST-800-53-AC-3(3)(a)
      - NIST-800-53-AU-9
      - NIST-800-53-SC-7(21)
      - PCI-DSSv4-1.2
      - PCI-DSSv4-1.2.6
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - selinux_state

Group Services Group contains 25 groups and 95 rules

[ref] The best protection against vulnerable software is running less software. This section describes how to review the software which Red Hat Enterprise Linux 9 installs on a system and disable software which is not needed. It then enumerates the software packages installed on a default Red Hat Enterprise Linux 9 system and provides guidance about which ones can be safely disabled.
Red Hat Enterprise Linux 9 provides a convenient minimal install option that essentially installs the bare necessities for a functional system. When building Red Hat Enterprise Linux 9 systems, it is highly recommended to select the minimal packages and then build up the system from there.

Group Base Services Group contains 1 rule
[ref] This section addresses the base services that are installed on a Red Hat Enterprise Linux 9 default installation which are not covered in other sections. Some of these services listen on the network and should be treated with particular discretion. Other services are local system utilities that may or may not be extraneous. In general, system services should be disabled if not required.

#### Rule Disable KDump Kernel Crash Analyzer (kdump) [ref]

The `kdump` service provides a kernel crash dump analyzer. It uses the `kexec` system call to boot a secondary kernel ("capture" kernel) following a system crash, which can load information from the crashed kernel for analysis. The `kdump` service can be disabled with the following command:

    $ sudo systemctl mask --now kdump.service

Rationale: | Kernel core dumps may contain the full contents of system memory at the time of the crash. Kernel core dumps consume a considerable amount of disk space and may result in denial of service by exhausting the available space on the target file system partition. Unless the system is used for kernel development or testing, there is little need to run the kdump service.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_kdump_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
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)
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
ospp | FMT_SMF_EXT.1.1
os-srg | SRG-OS-000269-GPOS-00103, SRG-OS-000480-GPOS-00227
stigref | SV-257818r1044876_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" stop 'kdump.service'
    fi
    "$SYSTEMCTL_EXEC" disable 'kdump.service'
    "$SYSTEMCTL_EXEC" mask 'kdump.service'
    # Disable socket activation if we have a unit file for it
    if "$SYSTEMCTL_EXEC" -q list-unit-files kdump.socket; then
        if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
          "$SYSTEMCTL_EXEC" stop 'kdump.socket'
        fi
        "$SYSTEMCTL_EXEC" mask 'kdump.socket'
    fi
    # The service may not be running because it has been started and failed,
    # so let's reset the state so OVAL checks pass.
    # Service should be 'inactive', not 'failed' after reboot though.
    "$SYSTEMCTL_EXEC" reset-failed 'kdump.service' || true

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

Remediation Puppet snippet ⇲

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

    include disable_kdump

    class disable_kdump {
      service {'kdump':
        enable => false,
        ensure => 'stopped',
      }
    }

Remediation Anaconda snippet ⇲

    kdump --disable

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-213115
      - 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_kdump_disabled

    - name: Disable KDump Kernel Crash Analyzer (kdump) - Disable service kdump
      block:

      - name: Disable KDump Kernel Crash Analyzer (kdump) - 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 KDump Kernel Crash Analyzer (kdump) - Ensure kdump.service is Masked
        ansible.builtin.systemd:
          name: kdump.service
          state: stopped
          enabled: false
          masked: true
        when: service_exists.stdout_lines is search("kdump.service", multiline=True)

      - name: Unit Socket Exists - kdump.socket
        ansible.builtin.command: systemctl -q list-unit-files kdump.socket
        register: socket_file_exists
        changed_when: false
        failed_when: socket_file_exists.rc not in [0, 1]
        check_mode: false

      - name: Disable KDump Kernel Crash Analyzer (kdump) - Disable Socket kdump
        ansible.builtin.systemd:
          name: kdump.socket
          enabled: false
          state: stopped
          masked: true
        when: socket_file_exists.stdout_lines is search("kdump.socket", multiline=True)
      tags:
      - DISA-STIG-RHEL-09-213115
      - 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_kdump_disabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: kdump.service
            enabled: false
            mask: true
          - name: kdump.socket
            enabled: false
            mask: true

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    masked = ["kdump"]

Group Cron and At Daemons Group contains 20 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.

#### 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
pcidss4 | 2.2.6, 2.2
cis | 2.4.1.1
stigref | SV-257888r1069378_rule

Remediation script ⇲

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

    dnf install cronie

Remediation script ⇲

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

    package install cronie

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "cronie" ; then
        dnf install -y "cronie"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_cronie

    class install_cronie {
      package { 'cronie':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=cronie

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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 cronie is installed
      ansible.builtin.package:
        name: cronie
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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 = "cronie"
    version = "*"

#### 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.7
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.4
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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.deny [ref]

To properly set the group owner of `/etc/cron.deny`, run the command:

    $ sudo chgrp root /etc/cron.deny

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_deny

References:

nist | CM-6 b
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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.deny" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/cron.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:
      - DISA-STIG-RHEL-09-232235
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_groupowner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_cron_deny_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_cron_deny_newgroup: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_groupowner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/cron.deny
      ansible.builtin.stat:
        path: /etc/cron.deny
      register: file_exists
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_groupowner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/cron.deny
      ansible.builtin.file:
        path: /etc/cron.deny
        follow: false
        group: '{{ file_groupowner_cron_deny_newgroup }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232235
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_groupowner_cron_deny
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.3
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.6
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.5
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.2
stigref | SV-257927r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232235
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.7
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.4
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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.deny [ref]

To properly set the owner of `/etc/cron.deny`, run the command:

    $ sudo chown root /etc/cron.deny

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_deny

References:

nist | CM-6 b
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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.deny" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/cron.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:
      - DISA-STIG-RHEL-09-232230
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_owner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_cron_deny_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_cron_deny_newown: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_owner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/cron.deny
      ansible.builtin.stat:
        path: /etc/cron.deny
      register: file_exists
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_owner_cron_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/cron.deny
      ansible.builtin.file:
        path: /etc/cron.deny
        follow: false
        owner: '{{ file_owner_cron_deny_newown }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232230
      - NIST-800-53-CM-6 b
      - configure_strategy
      - file_owner_cron_deny
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.3
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.6
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.5
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.2
stigref | SV-257926r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-232230
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.7
stigref | SV-257888r1069378_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.4
stigref | SV-257888r1069378_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.3
stigref | SV-257888r1069378_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.6
stigref | SV-257888r1069378_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 2.4.1.5
stigref | SV-257888r1069378_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232040
      - 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

Group Application Whitelisting Daemon Group contains 3 rules
[ref] Fapolicyd (File Access Policy Daemon) implements application whitelisting to decide file access rights. Applications that are known via a reputation source are allowed access while unknown applications are not. The daemon makes use of the kernel's `fanotify` interface to determine file access rights.

#### Rule Install fapolicyd Package [ref]

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

    $ sudo dnf install fapolicyd

Rationale: | `fapolicyd` (File Access Policy Daemon) implements application whitelisting to decide file access rights.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_fapolicyd_installed

References:

nist | CM-6(a), SI-4(22)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000370-GPOS-00155, SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00230
ism | 1409
bsi | SYS.1.1.A31
stigref | SV-258089r1045179_rule

Remediation script ⇲

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

    dnf install fapolicyd

Remediation script ⇲

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

    package install fapolicyd

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "fapolicyd" ; then
        dnf install -y "fapolicyd"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_fapolicyd

    class install_fapolicyd {
      package { 'fapolicyd':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=fapolicyd

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-433010
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(22)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_fapolicyd_installed

    - name: Ensure fapolicyd is installed
      ansible.builtin.package:
        name: fapolicyd
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-433010
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(22)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_fapolicyd_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule Enable the File Access Policy Service [ref]

The File Access Policy service should be enabled. The `fapolicyd` service can be enabled with the following command:

    $ sudo systemctl enable fapolicyd.service

Rationale: | The `fapolicyd` service (File Access Policy Daemon) implements application whitelisting to decide file access rights.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_fapolicyd_enabled

References:

nist | CM-6(a), SI-4(22)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000370-GPOS-00155, SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00230
ism | 1409
bsi | SYS.1.1.A31
stigref | SV-258090r958808_rule

Remediation script ⇲

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

    service enable fapolicyd

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'fapolicyd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'fapolicyd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'fapolicyd.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_fapolicyd

    class enable_fapolicyd {
      service {'fapolicyd':
        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:
      - DISA-STIG-RHEL-09-433015
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(22)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_fapolicyd_enabled

    - name: Enable the File Access Policy Service - Enable service fapolicyd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable the File Access Policy Service - Enable Service fapolicyd
        ansible.builtin.systemd:
          name: fapolicyd
          enabled: true
          state: started
          masked: false
        when:
        - '"fapolicyd" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-433015
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(22)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_fapolicyd_enabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["fapolicyd"]

#### Rule Configure Fapolicy Module to Employ a Deny-all, Permit-by-exception Policy to Allow the Execution of Authorized Software Programs. [ref]

The Fapolicy module must be configured to employ a deny-all, permit-by-exception policy to allow the execution of authorized software programs and to prevent unauthorized software from running.

Rationale:

Utilizing a whitelist provides a configuration management method for allowing the execution of only authorized software. Using only authorized software decreases risk by limiting the number of potential vulnerabilities. Verification of whitelisted software occurs prior to execution or at system startup. Proceed with caution with enforcing the use of this daemon. Improper configuration may render the system non-functional. The "fapolicyd" API is not namespace aware and can cause issues when launching or running containers.

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

References:

nist | CM-7 (2), CM-7 (5) (b), CM-6 b
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000370-GPOS-00155, SRG-OS-000480-GPOS-00232
bsi | SYS.1.1.A31
stigref | SV-270180r1045182_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    cat > /etc/fapolicyd/rules.d/99-deny-everything.rules << EOF
    # Red Hat KCS 7003854 (https://access.redhat.com/solutions/7003854)
    deny perm=any all : all
    EOF

    chmod 644 /etc/fapolicyd/rules.d/99-deny-everything.rules
    chgrp fapolicyd /etc/fapolicyd/rules.d/99-deny-everything.rules

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

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

    cp "/etc/fapolicyd/fapolicyd.conf" "/etc/fapolicyd/fapolicyd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "permissive = 0" >> "/etc/fapolicyd/fapolicyd.conf"
    # Clean up after ourselves.
    rm "/etc/fapolicyd/fapolicyd.conf.bak"

    systemctl restart fapolicyd

    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:
      - DISA-STIG-RHEL-09-433016
      - NIST-800-53-CM-6 b
      - NIST-800-53-CM-7 (2)
      - NIST-800-53-CM-7 (5) (b)
      - fapolicy_default_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Fapolicy Module to Employ a Deny-all, Permit-by-exception Policy
        to Allow the Execution of Authorized Software Programs. - Gather the package facts
      ansible.builtin.package_facts:
        manager: auto
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-433016
      - NIST-800-53-CM-6 b
      - NIST-800-53-CM-7 (2)
      - NIST-800-53-CM-7 (5) (b)
      - fapolicy_default_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Fapolicy Module to Employ a Deny-all, Permit-by-exception Policy
        to Allow the Execution of Authorized Software Programs. - Ensure a Final Rule
        Denying Everything
      ansible.builtin.copy:
        content: |
          # Red Hat KCS 7003854 (https://access.redhat.com/solutions/7003854)
          deny perm=any all : all
        dest: /etc/fapolicyd/rules.d/99-deny-everything.rules
        owner: root
        group: fapolicyd
        mode: '0644'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"fapolicyd" in ansible_facts.packages'
      register: result_fapolicyd_final_rule
      tags:
      - DISA-STIG-RHEL-09-433016
      - NIST-800-53-CM-6 b
      - NIST-800-53-CM-7 (2)
      - NIST-800-53-CM-7 (5) (b)
      - fapolicy_default_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Fapolicy Module to Employ a Deny-all, Permit-by-exception Policy
        to Allow the Execution of Authorized Software Programs. - Ensure fapolicyd is
        Not Permissive
      ansible.builtin.lineinfile:
        path: /etc/fapolicyd/fapolicyd.conf
        regexp: ^(permissive\s*=).*$
        line: \1 0
        backrefs: true
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"fapolicyd" in ansible_facts.packages'
      register: result_fapolicyd_enforced
      tags:
      - DISA-STIG-RHEL-09-433016
      - NIST-800-53-CM-6 b
      - NIST-800-53-CM-7 (2)
      - NIST-800-53-CM-7 (5) (b)
      - fapolicy_default_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Fapolicy Module to Employ a Deny-all, Permit-by-exception Policy
        to Allow the Execution of Authorized Software Programs. - Restart fapolicyd If
        Permissive Mode or Final Rule is Changed
      ansible.builtin.service:
        name: fapolicyd
        state: restarted
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"fapolicyd" in ansible_facts.packages'
      - result_fapolicyd_final_rule is changed or result_fapolicyd_enforced is changed
      tags:
      - DISA-STIG-RHEL-09-433016
      - NIST-800-53-CM-6 b
      - NIST-800-53-CM-7 (2)
      - NIST-800-53-CM-7 (5) (b)
      - fapolicy_default_deny
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group FTP Server Group contains 1 group and 1 rule

[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 1 rule
[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:

     $ sudo dnf 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.7
stigref | SV-257826r1106299_rule

Remediation script ⇲

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

    dnf remove vsftpd

Remediation script ⇲

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

    package remove vsftpd

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!

    if rpm -q --quiet "vsftpd" ; then
    dnf remove -y --noautoremove "vsftpd"
    fi

Remediation Puppet snippet ⇲

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

    include remove_vsftpd

    class remove_vsftpd {
      package { 'vsftpd':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=vsftpd

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:
      - DISA-STIG-RHEL-09-215015
      - 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

Group Mail Server Software Group contains 4 groups and 6 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 Red Hat Enterprise Linux 9 permits selection of other mail server software (such as Sendmail), but Postfix is the default and is preferred. Postfix was coded with security in mind and can also be more effectively contained by SELinux as its modular design has resulted in separate processes performing specific actions. More information is available on its website, http://www.postfix.org.

Group Configure SMTP For Mail Clients Group contains 2 rules
[ref] This section discusses settings for Postfix in a submission-only e-mail configuration.

#### Rule Configure System to Forward All Mail For The Root Account [ref]

Make sure that mails delivered to root user are forwarded to a monitored email address. Make sure that the address change_me@localhost is a valid email address reachable from the system in question. Use the following command to configure the alias:

    $ sudo echo "root: change_me@localhost" >> /etc/aliases
    $ sudo newaliases

Rationale: | A number of system services utilize email messages sent to the root user to notify system administrators of active or impending issues. These messages must be forwarded to at least one monitored email address.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_postfix_client_configure_mail_alias

References:

nist | CM-6(a)
os-srg | SRG-OS-000046-GPOS-00022
anssi | R75
stigref | SV-258174r958424_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_postfix_root_mail_alias='change_me@localhost'

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

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

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

    if [ -f /usr/bin/newaliases ]; then
        newaliases
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-653125
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias
    - name: XCCDF Value var_postfix_root_mail_alias # promote to variable
      set_fact:
        var_postfix_root_mail_alias: !!str change_me@localhost
      tags:
        - always

    - name: Configure System to Forward All Mail For The Root Account - Make sure that
        "/etc/aliases" has a defined value for root
      ansible.builtin.lineinfile:
        path: /etc/aliases
        line: 'root: {{ var_postfix_root_mail_alias }}'
        regexp: ^(?:[rR][oO][oO][tT]|"[rR][oO][oO][tT]")\s*:\s*(.+)$
        create: true
        state: present
      register: aliases_root_mail_alias_changed
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653125
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

    - name: Configure System to Forward All Mail For The Root Account - Check if newaliases
        command is available
      ansible.builtin.stat:
        path: /usr/bin/newaliases
      register: result_newaliases_present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653125
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

    - name: Configure System to Forward All Mail For The Root Account - Update postfix
        aliases
      ansible.builtin.command:
        cmd: newaliases
      when:
      - '"kernel-core" in ansible_facts.packages'
      - aliases_root_mail_alias_changed is changed
      - result_newaliases_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-653125
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

#### Rule Configure System to Forward All Mail From Postmaster to The Root Account [ref]

Verify the administrators are notified in the event of an audit processing failure. Check that the "/etc/aliases" file has a defined value for "root".

    $ sudo grep "postmaster:\s*root$" /etc/aliases

    postmaster: root

Rationale:

It is critical for the appropriate personnel to be aware if a system is at risk of failing to process audit logs as required. Without this notification, the security personnel may be unaware of an impending failure of the audit capability, and system operation may be adversely affected. Audit processing failures include software/hardware errors, failures in the audit capturing mechanisms, and audit storage capacity being reached or exceeded.

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

References:

nist | AU-5(a), AU-5.1(ii)
os-srg | SRG-OS-000046-GPOS-00022
stigref | SV-257953r958424_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if [ -e "/etc/aliases" ] ; then

        LC_ALL=C sed -i "/^\s*postmaster\s*:\s*/Id" "/etc/aliases"
    else
        touch "/etc/aliases"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/aliases"

    cp "/etc/aliases" "/etc/aliases.bak"
    # Insert at the end of the file
    printf '%s\n' "postmaster: root" >> "/etc/aliases"
    # Clean up after ourselves.
    rm "/etc/aliases.bak"

    if [ -f /usr/bin/newaliases ]; then
        newaliases
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-252060
      - NIST-800-53-AU-5(a)
      - NIST-800-53-AU-5.1(ii)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias_postmaster

    - name: Configure System to Forward All Mail From Postmaster to The Root Account
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/aliases
          create: true
          regexp: (?i)^\s*postmaster\s*:\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/aliases
        ansible.builtin.lineinfile:
          path: /etc/aliases
          create: true
          regexp: (?i)^\s*postmaster\s*:\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/aliases
        ansible.builtin.lineinfile:
          path: /etc/aliases
          create: true
          regexp: (?i)^\s*postmaster\s*:\s*
          line: 'postmaster: root'
          state: present
        register: aliases_postmaster_changed
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252060
      - NIST-800-53-AU-5(a)
      - NIST-800-53-AU-5.1(ii)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias_postmaster

    - name: Configure System to Forward All Mail From Postmaster to The Root Account -
        Check if newaliases command is available
      ansible.builtin.stat:
        path: /usr/bin/newaliases
      register: result_newaliases_present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252060
      - NIST-800-53-AU-5(a)
      - NIST-800-53-AU-5.1(ii)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias_postmaster

    - name: Configure System to Forward All Mail From Postmaster to The Root Account -
        Update postfix aliases
      ansible.builtin.command:
        cmd: newaliases
      when:
      - '"kernel-core" in ansible_facts.packages'
      - result_newaliases_present.stat.exists
      - aliases_postmaster_changed is changed
      tags:
      - DISA-STIG-RHEL-09-252060
      - NIST-800-53-AU-5(a)
      - NIST-800-53-AU-5.1(ii)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias_postmaster

Group Configure Operating System to Protect Mail Server Group contains 2 groups and 1 rule
[ref] The guidance in this section is appropriate for any host which is operating as a site MTA, whether the mail server runs using Sendmail, Postfix, or some other software.
Group Configure Postfix if Necessary Group contains 1 group and 1 rule
[ref] Postfix stores its configuration files in the directory /etc/postfix by default. The primary configuration file is `/etc/postfix/main.cf`.
Group Control Mail Relaying Group contains 1 rule

[ref] Postfix's mail relay controls are implemented with the help of the smtpd recipient restrictions option, which controls the restrictions placed on the SMTP dialogue once the sender and recipient envelope addresses are known. The guidance in the following sections should be applied to all systems. If there are systems which must be allowed to relay mail, but which cannot be trusted to relay unconditionally, configure SMTP AUTH with SSL support.

#### Rule Prevent Unrestricted Mail Relaying [ref]

Modify the

    /etc/postfix/main.cf

file to restrict client connections to the local network with the following command:

    $ sudo postconf -e 'smtpd_client_restrictions = permit_mynetworks,reject'

Rationale: | If unrestricted mail relaying is permitted, unauthorized senders could use this host as a mail relay for the purpose of sending spam or other unauthorized activity.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_postfix_prevent_unrestricted_relay

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257951r1014843_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && rpm --quiet -q postfix; then

    if ! grep -q ^smtpd_client_restrictions /etc/postfix/main.cf; then
    	echo "smtpd_client_restrictions = permit_mynetworks,reject" >> /etc/postfix/main.cf
    else
    	sed -i "s/^smtpd_client_restrictions.*/smtpd_client_restrictions = permit_mynetworks,reject/g" /etc/postfix/main.cf
    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:
      - DISA-STIG-RHEL-09-252050
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_prevent_unrestricted_relay
      - restrict_strategy

    - name: Prevent Unrestricted Mail Relaying
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/postfix/main.cf
          create: true
          regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/postfix/main.cf
        ansible.builtin.lineinfile:
          path: /etc/postfix/main.cf
          create: true
          regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/postfix/main.cf
        ansible.builtin.lineinfile:
          path: /etc/postfix/main.cf
          create: true
          regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
          line: smtpd_client_restrictions = permit_mynetworks,reject
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"postfix" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252050
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_prevent_unrestricted_relay
      - restrict_strategy

#### Rule The Postfix package is installed [ref]

A mail server is required for sending emails. The `postfix` package can be installed with the following command:

    $ sudo dnf install postfix

Rationale: | Emails can be used to notify designated personnel about important system events such as failures or warnings.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_postfix_installed

References:

os-srg | SRG-OS-000046-GPOS-00022
stigref | SV-272488r1082178_rule

Remediation script ⇲

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

    dnf install postfix

Remediation script ⇲

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

    package install postfix

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "postfix" ; then
        dnf install -y "postfix"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_postfix

    class install_postfix {
      package { 'postfix':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=postfix

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-215101
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_postfix_installed

    - name: Ensure postfix is installed
      ansible.builtin.package:
        name: postfix
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-215101
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_postfix_installed

Remediation OSBuild Blueprint snippet ⇲

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

#### Rule The s-nail Package Is Installed [ref]

A mail server is required for sending emails. The `s-nail` package can be installed with the following command:

    $ sudo dnf install s-nail

Rationale: | Emails can be used to notify designated personnel about important system events such as failures or warnings.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_s-nail_installed

References:

nist | CM-3(5)
os-srg | SRG-OS-000363-GPOS-00150
stigref | SV-257842r1044916_rule

Remediation script ⇲

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

    dnf install s-nail

Remediation script ⇲

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

    package install s-nail

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "s-nail" ; then
        dnf install -y "s-nail"
    fi

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

Remediation Puppet snippet ⇲

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

    include install_s-nail

    class install_s-nail {
      package { 's-nail':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --add=s-nail

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-215095
      - NIST-800-53-CM-3(5)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_s-nail_installed

    - name: Ensure s-nail is installed
      ansible.builtin.package:
        name: s-nail
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-215095
      - NIST-800-53-CM-3(5)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_s-nail_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "s-nail"
    version = "*"

#### Rule Uninstall Sendmail Package [ref]

Sendmail is not the default mail transfer agent and is not installed by default. The `sendmail` package can be removed with the following command:

    $ sudo dnf remove sendmail

Rationale: | The sendmail software was not developed with security in mind and its design prevents it from being effectively contained by SELinux. Postfix should be used instead.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_sendmail_removed

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000095-GPOS-00049
anssi | R62
stigref | SV-257827r1044892_rule

Remediation script ⇲

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

    dnf remove sendmail

Remediation script ⇲

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

    package remove sendmail

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

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

    if rpm -q --quiet "sendmail" ; then
    dnf remove -y --noautoremove "sendmail"
    fi

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

Remediation Puppet snippet ⇲

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

    include remove_sendmail

    class remove_sendmail {
      package { 'sendmail':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=sendmail

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-215020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sendmail_removed

    - name: 'Uninstall Sendmail Package: Ensure sendmail is removed'
      ansible.builtin.package:
        name: sendmail
        state: absent
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-215020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sendmail_removed

Group NFS and RPC Group contains 2 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 Configure NFS Clients Group contains 1 group and 3 rules
[ref] The steps in this section are appropriate for systems which operate as NFS clients.
Group Mount Remote Filesystems with Restrictive Options Group contains 3 rules

[ref] Edit the file `/etc/fstab`. For each filesystem whose type (column 3) is `nfs` or `nfs4`, add the text `,nodev,nosuid` to the list of mount options in column 4. If appropriate, also add `,noexec`.
See the section titled "Restrict Partition Mount Options" for a description of the effects of these options. In general, execution of files mounted via NFS should be considered risky because of the possibility that an adversary could intercept the request and substitute a malicious file. Allowing setuid files to be executed from remote servers is particularly risky, both for this reason and because it requires the clients to extend root-level trust to the NFS server.

#### Rule Mount Remote Filesystems with nodev [ref]

Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of any NFS mounts.
Rationale: | Legitimate device files should only exist in the /dev directory. NFS mounts should not present device files to users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nodev_remote_filesystems

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
nist | CM-6(a), MP-2
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257854r1044934_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    vfstype_points=()
    readarray -t vfstype_points < <(grep -E "[[:space:]]nfs[4]?[[:space:]]" /etc/fstab | awk '{print $2}')

    for vfstype_point in "${vfstype_points[@]}"
    do
        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" ${vfstype_point//\\/\\\\})"

        # If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
        if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
            # runtime opts without some automatic kernel/userspace-added defaults
            previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                        | sed -E "s/(rw|defaults|seclabel|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="nfs4"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " ${vfstype_point//\\/\\\\} nfs4 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
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MP-2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nodev_remote_filesystems
      - no_reboot_needed

    - name: Get nfs and nfs4 mount points, that don't have nodev
      ansible.builtin.command: findmnt --fstab --types nfs,nfs4 -O nonodev -n -P
      register: points_register
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-231065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MP-2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nodev_remote_filesystems
      - no_reboot_needed

    - name: Add nodev to nfs and nfs4 mount points
      ansible.posix.mount:
        path: '{{ item | regex_search(''TARGET="([^"]+)"'',''\1'') | first }}'
        src: '{{ item | regex_search(''SOURCE="([^"]+)"'',''\1'') | first }}'
        fstype: '{{ item | regex_search(''FSTYPE="([^"]+)"'',''\1'') | first }}'
        state: present
        opts: '{{ item | regex_search(''OPTIONS="([^"]+)"'',''\1'') | first }},nodev'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - (points_register.stdout | length > 0) and '\\x09' not in item
      with_items: '{{ points_register.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-231065
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MP-2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nodev_remote_filesystems
      - no_reboot_needed

#### Rule Mount Remote Filesystems with noexec [ref]

Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of any NFS mounts.
Rationale: | The noexec mount option causes the system not to execute binary files. This option must be used for mounting any file system not containing approved binary files as they may be incompatible. Executing files from untrusted file systems increases the opportunity for unprivileged users to attain unauthorized administrative access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_noexec_remote_filesystems

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 | AC-6, AC-6(8), AC-6(10), CM-6(a)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257855r1044936_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    vfstype_points=()
    readarray -t vfstype_points < <(grep -E "[[:space:]]nfs[4]?[[:space:]]" /etc/fstab | awk '{print $2}')

    for vfstype_point in "${vfstype_points[@]}"
    do
        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" ${vfstype_point//\\/\\\\})"

        # If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
        if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
            # runtime opts without some automatic kernel/userspace-added defaults
            previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                        | sed -E "s/(rw|defaults|seclabel|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="nfs4"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " ${vfstype_point//\\/\\\\} nfs4 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
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231070
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(10)
      - NIST-800-53-AC-6(8)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_noexec_remote_filesystems
      - no_reboot_needed

    - name: Get nfs and nfs4 mount points, that don't have noexec
      ansible.builtin.command: findmnt --fstab --types nfs,nfs4 -O nonoexec -n -P
      register: points_register
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-231070
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(10)
      - NIST-800-53-AC-6(8)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_noexec_remote_filesystems
      - no_reboot_needed

    - name: Add noexec to nfs and nfs4 mount points
      ansible.posix.mount:
        path: '{{ item | regex_search(''TARGET="([^"]+)"'',''\1'') | first }}'
        src: '{{ item | regex_search(''SOURCE="([^"]+)"'',''\1'') | first }}'
        fstype: '{{ item | regex_search(''FSTYPE="([^"]+)"'',''\1'') | first }}'
        state: present
        opts: '{{ item | regex_search(''OPTIONS="([^"]+)"'',''\1'') | first }},noexec'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - (points_register.stdout | length > 0) and '\\x09' not in item
      with_items: '{{ points_register.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-231070
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(10)
      - NIST-800-53-AC-6(8)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_noexec_remote_filesystems
      - no_reboot_needed

#### Rule Mount Remote Filesystems with nosuid [ref]

Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of any NFS mounts.
Rationale: | NFS mounts should not present suid binaries to users. Only vendor-supplied suid executables should be installed to their default location on the local filesystem.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nosuid_remote_filesystems

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 | AC-6, AC-6(1), CM6(a)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257856r1044938_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    vfstype_points=()
    readarray -t vfstype_points < <(grep -E "[[:space:]]nfs[4]?[[:space:]]" /etc/fstab | awk '{print $2}')

    for vfstype_point in "${vfstype_points[@]}"
    do
        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" ${vfstype_point//\\/\\\\})"

        # If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
        if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
            # runtime opts without some automatic kernel/userspace-added defaults
            previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                        | sed -E "s/(rw|defaults|seclabel|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="nfs4"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " ${vfstype_point//\\/\\\\} nfs4 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
    done

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-231075
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nosuid_remote_filesystems
      - no_reboot_needed

    - name: Get nfs and nfs4 mount points, that don't have nosuid
      ansible.builtin.command: findmnt --fstab --types nfs,nfs4 -O nonosuid -n -P
      register: points_register
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-231075
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nosuid_remote_filesystems
      - no_reboot_needed

    - name: Add nosuid to nfs and nfs4 mount points
      ansible.posix.mount:
        path: '{{ item | regex_search(''TARGET="([^"]+)"'',''\1'') | first }}'
        src: '{{ item | regex_search(''SOURCE="([^"]+)"'',''\1'') | first }}'
        fstype: '{{ item | regex_search(''FSTYPE="([^"]+)"'',''\1'') | first }}'
        state: present
        opts: '{{ item | regex_search(''OPTIONS="([^"]+)"'',''\1'') | first }},nosuid'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - (points_register.stdout | length > 0) and '\\x09' not in item
      with_items: '{{ points_register.stdout_lines }}'
      tags:
      - DISA-STIG-RHEL-09-231075
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM6(a)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - mount_option_nosuid_remote_filesystems
      - no_reboot_needed

#### Rule Uninstall nfs-utils Package [ref]

The `nfs-utils` package can be removed with the following command:

    $ sudo dnf remove nfs-utils

Rationale: | `nfs-utils` provides a daemon for the kernel NFS server and related tools. This package also contains the `showmount` program. `showmount` queries the mount daemon on a remote host for information about the Network File System (NFS) server on the remote host. For example, `showmount` can display the clients which are mounted on that host.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_nfs-utils_removed

References:

os-srg | SRG-OS-000095-GPOS-00049
stigref | SV-257828r1044894_rule

Remediation script ⇲

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

    dnf remove nfs-utils

Remediation script ⇲

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

    package remove nfs-utils

Remediation Shell script ⇲

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

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

    if rpm -q --quiet "nfs-utils" ; then
    dnf remove -y --noautoremove "nfs-utils"
    fi

Remediation Puppet snippet ⇲

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

    include remove_nfs-utils

    class remove_nfs-utils {
      package { 'nfs-utils':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=nfs-utils

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall nfs-utils Package: Ensure nfs-utils is removed'
      ansible.builtin.package:
        name: nfs-utils
        state: absent
      tags:
      - DISA-STIG-RHEL-09-215025
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_nfs-utils_removed

Group Network Time Protocol Group contains 7 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://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/configuring_basic_system_settings/configuring-time-synchronization_configuring-basic-system-settings 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:

    $ sudo dnf install chrony

Rationale: | Time synchronization is important to support time sensitive security mechanisms like Kerberos and also ensures log files have consistent time records across the enterprise, which aids in forensic investigations.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_chrony_installed

References:

ospp | FMT_SMF_EXT.1
pcidss | Req-10.4
os-srg | SRG-OS-000355-GPOS-00143
anssi | R71
ism | 0988, 1405
pcidss4 | 10.6.1, 10.6
cis | 2.3.1
stigref | SV-257943r1045001_rule

Remediation script ⇲

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

    dnf install chrony

Remediation script ⇲

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

    package install chrony

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "chrony" ; then
        dnf install -y "chrony"
    fi

    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 Anaconda snippet ⇲

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

    package --add=chrony

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-252010
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252010
      - 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 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
ism | 0988, 1405
stigref | SV-257944r1038944_rule

Remediation script ⇲

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

    service enable chronyd

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q chrony; }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'chronyd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'chronyd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'chronyd.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_chronyd

    class enable_chronyd {
      service {'chronyd':
        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:
      - DISA-STIG-RHEL-09-252015
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_chronyd_enabled

    - name: The Chronyd service is enabled - Enable service chronyd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: The Chronyd service is enabled - Enable Service chronyd
        ansible.builtin.systemd:
          name: chronyd
          enabled: true
          state: started
          masked: false
        when:
        - '"chrony" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252015
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_chronyd_enabled
      - special_service_block
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["chronyd"]

#### Rule A remote time server for Chrony is configured [ref]

`Chrony` is a daemon which implements the Network Time Protocol (NTP). It is designed to synchronize system clocks across a variety of systems and use a source that is highly accurate. More information on `chrony` can be found at https://chrony-project.org/. `Chrony` can be configured to be a client and/or a server. Add or edit server or pool lines to `/etc/chrony.conf` as appropriate:

    server <remote-server>

Multiple servers may be configured.

Rationale: | If `chrony` is in use on the system proper configuration is vital to ensuring time synchronization is working properly.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_chronyd_specify_remote_server

References:

nist | CM-6(a), AU-8(1)(a)
pcidss | Req-10.4.3
os-srg | SRG-OS-000355-GPOS-00143
anssi | R71
ism | 0988, 1405
pcidss4 | 10.6.2, 10.6
cis | 2.3.2
stigref | SV-257945r1038944_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q chrony; }; then

    var_multiple_time_servers='0.us.pool.ntp.mil'

    config_file="/etc/chrony.conf"

    if ! grep -q '^[[:space:]]*\(server\|pool\)[[:space:]]\+[[:graph:]]\+' "$config_file" ; then
      if ! grep -q '#[[:space:]]*server' "$config_file" ; then
        for server in $(echo "$var_multiple_time_servers" | tr ',' '\n') ; do
          printf '\nserver %s' "$server" >> "$config_file"
        done
      else
        sed -i 's/#[ \t]*server/server/g' "$config_file"
      fi
      if [[ -s "$config_file" ]] && [[ -n "$(tail -c 1 -- "$config_file" || true)" ]]; then
          LC_ALL=C sed -i --follow-symlinks '$a'\\ "$config_file"
      fi
    fi

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

Remediation Ansible snippet ⇲

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

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_multiple_time_servers # promote to variable
      set_fact:
        var_multiple_time_servers: !!str 0.us.pool.ntp.mil
      tags:
        - always

    - name: Detect if chrony is already configured with pools or servers
      ansible.builtin.find:
        path: /etc
        patterns: chrony.conf
        contains: ^[\s]*(?:server|pool)[\s]+[\w]+
      register: chrony_servers
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure remote time servers
      ansible.builtin.lineinfile:
        path: /etc/chrony.conf
        line: server {{ item }}
        state: present
        create: true
      loop: '{{ var_multiple_time_servers.split(",") }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      - chrony_servers.matched == 0
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Disable chrony daemon from acting as server [ref]

The `port` option in `/etc/chrony.conf` can be set to `0` to make chrony daemon to never open any listening port for server operation and to operate strictly in a client-only mode.

Rationale:

In order to prevent unauthorized connection of devices, unauthorized transfer of information, or unauthorized tunneling (i.e., embedding of data types within data types), organizations must disable or restrict unused or unnecessary physical and logical ports/protocols on information systems. Operating systems are capable of providing a wide variety of functions and services. Some of the functions and services provided by default may not be necessary to support essential organizational operations. Additionally, it is sometimes convenient to provide multiple services from a single component (e.g., VPN and IPS); however, doing so increases risk over limiting the services provided by any one component. To support the requirements and principles of least functionality, the operating system must support the organizational requirements, providing only essential capabilities and limiting the use of ports, protocols, and/or services to only those required, authorized, and approved to conduct official business or to address authorized quality of life issues.

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

References:

nist | AU-8(1), AU-12(1)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000096-GPOS-00050, SRG-OS-000095-GPOS-00049
stigref | SV-257946r958480_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q chrony; }; then

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

    # 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 "^port\\>" "/etc/chrony.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^port\\>.*/$escaped_formatted_output/gi" "/etc/chrony.conf"
    else
        if [[ -s "/etc/chrony.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/chrony.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/chrony.conf"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/chrony.conf" >> "/etc/chrony.conf"
        printf '%s\n' "$formatted_output" >> "/etc/chrony.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:
      - DISA-STIG-RHEL-09-252025
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)
      - chronyd_client_only
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable chrony daemon from acting as server
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*port\s+
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/chrony.conf
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*port\s+
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/chrony.conf
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*port\s+
          line: port 0
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252025
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)
      - chronyd_client_only
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

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

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%20Allow%20for%20extra%20configuration%20files.%20This%20is%20useful%0A%23%20for%20admins%20specifying%20their%20own%20NTP%20servers%0Ainclude%20/etc/chrony.d/%2A.conf%0A%0A%23%20Set%20chronyd%20as%20client-only.%0Aport%200%0A%0A%23%20Disable%20chronyc%20from%20the%20network%0Acmdport%200%0A%0A%23%20Record%20the%20rate%20at%20which%20the%20system%20clock%20gains/losses%20time.%0Adriftfile%20/var/lib/chrony/drift%0A%0A%23%20Allow%20the%20system%20clock%20to%20be%20stepped%20in%20the%20first%20three%20updates%0A%23%20if%20its%20offset%20is%20larger%20than%201%20second.%0Amakestep%201.0%203%0A%0A%23%20Enable%20kernel%20synchronization%20of%20the%20real-time%20clock%20%28RTC%29.%0Artcsync%0A%0A%23%20Enable%20hardware%20timestamping%20on%20all%20interfaces%20that%20support%20it.%0A%23hwtimestamp%20%2A%0A%0A%23%20Increase%20the%20minimum%20number%20of%20selectable%20sources%20required%20to%20adjust%0A%23%20the%20system%20clock.%0A%23minsources%202%0A%0A%23%20Allow%20NTP%20client%20access%20from%20local%20network.%0A%23allow%20192.168.0.0/16%0A%0A%23%20Serve%20time%20even%20if%20not%20synchronized%20to%20a%20time%20source.%0A%23local%20stratum%2010%0A%0A%23%20Require%20authentication%20%28nts%20or%20key%20option%29%20for%20all%20NTP%20sources.%0A%23authselectmode%20require%0A%0A%23%20Specify%20file%20containing%20keys%20for%20NTP%20authentication.%0Akeyfile%20/etc/chrony.keys%0A%0A%23%20Insert/delete%20leap%20seconds%20by%20slewing%20instead%20of%20stepping.%0A%23leapsecmode%20slew%0A%0A%23%20Get%20TAI-UTC%20offset%20and%20leap%20seconds%20from%20the%20system%20tz%20database.%0Aleapsectz%20right/UTC%0A%0A%23%20Specify%20directory%20for%20log%20files.%0Alogdir%20/var/log/chrony%0A%0A%23%20Select%20which%20information%20is%20logged.%0A%23log%20measurements%20statistics%20tracking }}
            mode: 420
            overwrite: true
            path: /etc/chrony.conf
          - contents:
              source: data:,
            mode: 420
            overwrite: true
            path: /etc/chrony.d/.mco-keep
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20ntp%20server%0A%23%20%7B%7B.var_multiple_time_servers%7D%7D%20we%20have%20to%20put%20variable%20array%20name%20here%20for%20mutilines%20remediation%0A%7B%7B%24var_time_service_set_maxpoll%3A%3D.var_time_service_set_maxpoll%7D%7D%0A%7B%7Brange%20%24element%3A%3D.var_multiple_time_servers%7CtoArrayByComma%7D%7Dserver%20%7B%7B%24element%7D%7D%20minpoll%204%20maxpoll%20%7B%7B%24var_time_service_set_maxpoll%7D%7D%0A%7B%7Bend%7D%7D }}
            mode: 420
            overwrite: true
            path: /etc/chrony.d/ntp-server.conf

#### Rule Disable network management of chrony daemon [ref]

The `cmdport` option in `/etc/chrony.conf` can be set to `0` to stop chrony daemon from listening on the UDP port 323 for management connections made by chronyc.
Rationale: | Minimizing the exposure of the server functionality of the chrony daemon diminishes the attack surface.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_chronyd_no_chronyc_network

References:

nist | CM-7(1)
os-srg | SRG-OS-000096-GPOS-00050, SRG-OS-000095-GPOS-00049
stigref | SV-257947r958480_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q chrony; }; then

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

    # 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 "^cmdport\\>" "/etc/chrony.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^cmdport\\>.*/$escaped_formatted_output/gi" "/etc/chrony.conf"
    else
        if [[ -s "/etc/chrony.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/chrony.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/chrony.conf"
        fi
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/chrony.conf" >> "/etc/chrony.conf"
        printf '%s\n' "$formatted_output" >> "/etc/chrony.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:
      - DISA-STIG-RHEL-09-252030
      - NIST-800-53-CM-7(1)
      - chronyd_no_chronyc_network
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Disable network management of chrony daemon
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*cmdport\s+
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/chrony.conf
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*cmdport\s+
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/chrony.conf
        ansible.builtin.lineinfile:
          path: /etc/chrony.conf
          create: true
          regexp: (?i)^\s*cmdport\s+
          line: cmdport 0
          state: present
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-252030
      - NIST-800-53-CM-7(1)
      - chronyd_no_chronyc_network
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

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

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%20Allow%20for%20extra%20configuration%20files.%20This%20is%20useful%0A%23%20for%20admins%20specifying%20their%20own%20NTP%20servers%0Ainclude%20/etc/chrony.d/%2A.conf%0A%0A%23%20Set%20chronyd%20as%20client-only.%0Aport%200%0A%0A%23%20Disable%20chronyc%20from%20the%20network%0Acmdport%200%0A%0A%23%20Record%20the%20rate%20at%20which%20the%20system%20clock%20gains/losses%20time.%0Adriftfile%20/var/lib/chrony/drift%0A%0A%23%20Allow%20the%20system%20clock%20to%20be%20stepped%20in%20the%20first%20three%20updates%0A%23%20if%20its%20offset%20is%20larger%20than%201%20second.%0Amakestep%201.0%203%0A%0A%23%20Enable%20kernel%20synchronization%20of%20the%20real-time%20clock%20%28RTC%29.%0Artcsync%0A%0A%23%20Enable%20hardware%20timestamping%20on%20all%20interfaces%20that%20support%20it.%0A%23hwtimestamp%20%2A%0A%0A%23%20Increase%20the%20minimum%20number%20of%20selectable%20sources%20required%20to%20adjust%0A%23%20the%20system%20clock.%0A%23minsources%202%0A%0A%23%20Allow%20NTP%20client%20access%20from%20local%20network.%0A%23allow%20192.168.0.0/16%0A%0A%23%20Serve%20time%20even%20if%20not%20synchronized%20to%20a%20time%20source.%0A%23local%20stratum%2010%0A%0A%23%20Require%20authentication%20%28nts%20or%20key%20option%29%20for%20all%20NTP%20sources.%0A%23authselectmode%20require%0A%0A%23%20Specify%20file%20containing%20keys%20for%20NTP%20authentication.%0Akeyfile%20/etc/chrony.keys%0A%0A%23%20Insert/delete%20leap%20seconds%20by%20slewing%20instead%20of%20stepping.%0A%23leapsecmode%20slew%0A%0A%23%20Get%20TAI-UTC%20offset%20and%20leap%20seconds%20from%20the%20system%20tz%20database.%0Aleapsectz%20right/UTC%0A%0A%23%20Specify%20directory%20for%20log%20files.%0Alogdir%20/var/log/chrony%0A%0A%23%20Select%20which%20information%20is%20logged.%0A%23log%20measurements%20statistics%20tracking }}
            mode: 420
            overwrite: true
            path: /etc/chrony.conf
          - contents:
              source: data:,
            mode: 420
            overwrite: true
            path: /etc/chrony.d/.mco-keep
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20ntp%20server%0A%23%20%7B%7B.var_multiple_time_servers%7D%7D%20we%20have%20to%20put%20variable%20array%20name%20here%20for%20mutilines%20remediation%0A%7B%7B%24var_time_service_set_maxpoll%3A%3D.var_time_service_set_maxpoll%7D%7D%0A%7B%7Brange%20%24element%3A%3D.var_multiple_time_servers%7CtoArrayByComma%7D%7Dserver%20%7B%7B%24element%7D%7D%20minpoll%204%20maxpoll%20%7B%7B%24var_time_service_set_maxpoll%7D%7D%0A%7B%7Bend%7D%7D }}
            mode: 420
            overwrite: true
            path: /etc/chrony.d/ntp-server.conf

#### Rule Configure Time Service Maxpoll Interval [ref]

The `maxpoll` should be configured to 16 in `/etc/ntp.conf` or `/etc/chrony.conf` (or `/etc/chrony.d/`) to continuously poll time servers. To configure `maxpoll` in `/etc/ntp.conf` or `/etc/chrony.conf` (or `/etc/chrony.d/`) add the following after each `server`, `pool` or `peer` entry:

    maxpoll 16

to `server` directives. If using chrony, any `pool` directives should be configured too.

Rationale:

Inaccurate time stamps make it more difficult to correlate events and can lead to an inaccurate analysis. Determining the correct time a particular event occurred on a system is critical when conducting forensic analysis and investigating system events. Sources outside the configured acceptable allowance (drift) may be inaccurate. Synchronizing internal information system clocks provides uniformity of time stamps for information systems with multiple system clocks and systems connected over a network. Organizations should consider endpoints that may not have regular access to the authoritative time server (e.g., mobile, teleworking, and tactical endpoints).

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

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)(b), AU-12(1)
nist-csf | PR.PT-1
os-srg | SRG-OS-000355-GPOS-00143, SRG-OS-000356-GPOS-00144, SRG-OS-000359-GPOS-00146
stigref | SV-257945r1038944_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { ( rpm --quiet -q chrony || rpm --quiet -q ntp ); }; then

    var_time_service_set_maxpoll='16'

    pof="/usr/sbin/pidof"

    CONFIG_FILES="/etc/ntp.conf"
    $pof ntpd || {
        CHRONY_D_PATH=/etc/chrony.d/

        mapfile -t CONFIG_FILES < <(find ${CHRONY_D_PATH}.* -type f -name '*.conf')

        CONFIG_FILES+=(/etc/chrony.conf)
    }

    # get list of ntp files

    for config_file in "${CONFIG_FILES[@]}" ; do
        # Set maxpoll values to var_time_service_set_maxpoll
        sed -i "s/^\(\(server\|pool\|peer\).*maxpoll\) [0-9,-][0-9]*\(.*\)$/\1 $var_time_service_set_maxpoll \3/" "$config_file"
    done

    for config_file in "${CONFIG_FILES[@]}" ; do
        # Add maxpoll to server, pool or peer entries without maxpoll
        grep "^\(server\|pool\|peer\)" "$config_file" | grep -v maxpoll | while read -r line ; do
            sed -i "s/$line/& maxpoll $var_time_service_set_maxpoll/" "$config_file"
        done
    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:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_time_service_set_maxpoll # promote to variable
      set_fact:
        var_time_service_set_maxpoll: !!str 16
      tags:
        - always

    - name: Configure Time Service Maxpoll Interval - Check That /etc/ntp.conf Exist
      ansible.builtin.stat:
        path: /etc/ntp.conf
      register: ntp_conf_exist_result
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Update the maxpoll Values in /etc/ntp.conf
      ansible.builtin.replace:
        path: /etc/ntp.conf
        regexp: ^(server.*maxpoll)[ ]+[0-9]+(.*)$
        replace: \1 {{ var_time_service_set_maxpoll }}\2
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - ntp_conf_exist_result.stat.exists
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Set the maxpoll Values in /etc/ntp.conf
      ansible.builtin.replace:
        path: /etc/ntp.conf
        regexp: (^server\s+((?!maxpoll).)*)$
        replace: \1 maxpoll {{ var_time_service_set_maxpoll }}\n
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - ntp_conf_exist_result.stat.exists
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Check That /etc/chrony.conf Exist
      ansible.builtin.stat:
        path: /etc/chrony.conf
      register: chrony_conf_exist_result
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Update the maxpoll Values in /etc/chrony.conf
      ansible.builtin.replace:
        path: /etc/chrony.conf
        regexp: ^((?:server|pool|peer).*maxpoll)[ ]+[0-9]+(.*)$
        replace: \1 {{ var_time_service_set_maxpoll }}\2
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - chrony_conf_exist_result.stat.exists
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Set the maxpoll Values in /etc/chrony.conf
      ansible.builtin.replace:
        path: /etc/chrony.conf
        regexp: (^(?:server|pool|peer)\s+((?!maxpoll).)*)$
        replace: \1 maxpoll {{ var_time_service_set_maxpoll }}\n
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - chrony_conf_exist_result.stat.exists
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Get Conf Files from /etc/chrony.d/
      ansible.builtin.find:
        path: /etc/chrony.d/
        patterns: '*.conf'
        file_type: file
      register: chrony_d_conf_files
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Update the maxpoll Values in /etc/chrony.d/
      ansible.builtin.replace:
        path: '{{ item.path }}'
        regexp: ^((?:server|pool|peer).*maxpoll)[ ]+[0-9,-]+(.*)$
        replace: \1 {{ var_time_service_set_maxpoll }}\2
      loop: '{{ chrony_d_conf_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - chrony_d_conf_files.matched
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Time Service Maxpoll Interval - Set the maxpoll Values in /etc/chrony.d/
      ansible.builtin.replace:
        path: '{{ item.path }}'
        regexp: (^(?:server|pool|peer)\s+((?!maxpoll).)*)$
        replace: \1 maxpoll {{ var_time_service_set_maxpoll }}\n
      loop: '{{ chrony_d_conf_files.files }}'
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ( "chrony" in ansible_facts.packages or "ntp" in ansible_facts.packages )
      - chrony_d_conf_files.matched
      tags:
      - DISA-STIG-RHEL-09-252020
      - NIST-800-53-AU-12(1)
      - NIST-800-53-AU-8(1)(b)
      - NIST-800-53-CM-6(a)
      - chronyd_or_ntpd_set_maxpoll
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

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

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%20Allow%20for%20extra%20configuration%20files.%20This%20is%20useful%0A%23%20for%20admins%20specifying%20their%20own%20NTP%20servers%0Ainclude%20/etc/chrony.d/%2A.conf%0A%0A%23%20Set%20chronyd%20as%20client-only.%0Aport%200%0A%0A%23%20Disable%20chronyc%20from%20the%20network%0Acmdport%200%0A%0A%23%20Record%20the%20rate%20at%20which%20the%20system%20clock%20gains/losses%20time.%0Adriftfile%20/var/lib/chrony/drift%0A%0A%23%20Allow%20the%20system%20clock%20to%20be%20stepped%20in%20the%20first%20three%20updates%0A%23%20if%20its%20offset%20is%20larger%20than%201%20second.%0Amakestep%201.0%203%0A%0A%23%20Enable%20kernel%20synchronization%20of%20the%20real-time%20clock%20%28RTC%29.%0Artcsync%0A%0A%23%20Enable%20hardware%20timestamping%20on%20all%20interfaces%20that%20support%20it.%0A%23hwtimestamp%20%2A%0A%0A%23%20Increase%20the%20minimum%20number%20of%20selectable%20sources%20required%20to%20adjust%0A%23%20the%20system%20clock.%0A%23minsources%202%0A%0A%23%20Allow%20NTP%20client%20access%20from%20local%20network.%0A%23allow%20192.168.0.0/16%0A%0A%23%20Serve%20time%20even%20if%20not%20synchronized%20to%20a%20time%20source.%0A%23local%20stratum%2010%0A%0A%23%20Require%20authentication%20%28nts%20or%20key%20option%29%20for%20all%20NTP%20sources.%0A%23authselectmode%20require%0A%0A%23%20Specify%20file%20containing%20keys%20for%20NTP%20authentication.%0Akeyfile%20/etc/chrony.keys%0A%0A%23%20Insert/delete%20leap%20seconds%20by%20slewing%20instead%20of%20stepping.%0A%23leapsecmode%20slew%0A%0A%23%20Get%20TAI-UTC%20offset%20and%20leap%20seconds%20from%20the%20system%20tz%20database.%0Aleapsectz%20right/UTC%0A%0A%23%20Specify%20directory%20for%20log%20files.%0Alogdir%20/var/log/chrony%0A%0A%23%20Select%20which%20information%20is%20logged.%0A%23log%20measurements%20statistics%20tracking }}
            mode: 420
            overwrite: true
            path: /etc/chrony.conf
          - contents:
              source: data:,
            mode: 420
            overwrite: true
            path: /etc/chrony.d/.mco-keep
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20ntp%20server%0A%23%20%7B%7B.var_multiple_time_servers%7D%7D%20we%20have%20to%20put%20variable%20array%20name%20here%20for%20mutilines%20remediation%0A%7B%7B%24var_time_service_set_maxpoll%3A%3D.var_time_service_set_maxpoll%7D%7D%0A%7B%7Brange%20%24element%3A%3D.var_multiple_time_servers%7CtoArrayByComma%7D%7Dserver%20%7B%7B%24element%7D%7D%20minpoll%204%20maxpoll%20%7B%7B%24var_time_service_set_maxpoll%7D%7D%0A%7B%7Bend%7D%7D }}
            mode: 420
            overwrite: true
            path: /etc/chrony.d/ntp-server.conf

#### Rule Ensure Chrony is only configured with the server directive [ref]

Check that Chrony only has time sources configured with the `server` directive. Warning: This rule doesn't come with a remediation, the time source needs to be added by the administrator.
Rationale: | Depending on the infrastructure being used the `pool` directive may not be supported. Using the `server` directive allows for better control of where the system gets time data from.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_chronyd_server_directive

References:

os-srg | SRG-OS-000355-GPOS-00143, SRG-OS-000356-GPOS-00144, SRG-OS-000359-GPOS-00146
stigref | SV-257945r1038944_rule

Group Obsolete Services Group contains 3 groups and 4 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 Red Hat Enterprise Linux 9 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 `firewalld` to restrict access to the vulnerable service to only those remote hosts which have a known need to use it.

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 Remove Host-Based Authentication Files [ref]

The `shosts.equiv` file lists remote hosts and users that are trusted by the local system. To remove these files, run the following command to delete them from any location:

    $ sudo rm /[path]/[to]/[file]/shosts.equiv

Rationale: | The shosts.equiv files are used to configure host-based authentication for the system via SSH. Host-based authentication is not sufficient for preventing unauthorized access to the system, as it does not require interactive identification and authentication of a connection request, or for the use of two-factor authentication.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_no_host_based_files

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257955r991589_rule

Remediation Shell script ⇲

    # Identify local mounts
    MOUNT_LIST=$(df --local | awk '{ print $6 }')

    # Find file on each listed mount point
    for cur_mount in ${MOUNT_LIST}
    do
    	find ${cur_mount} -xdev -type f -name "shosts.equiv" -exec rm -f {} \;
    done

Remediation Ansible snippet ⇲

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

    - name: Remove Host-Based Authentication Files - Define Excluded (Non-Local) File
        Systems and Paths
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
        excluded_paths:
        - dev
        - proc
        - run
        - sys
        search_paths: []
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Find Relevant Root Directories Ignoring
        Pre-Defined Excluded Paths
      ansible.builtin.find:
        paths: /
        file_type: directory
        excludes: '{{ excluded_paths }}'
        hidden: true
        recurse: false
      register: result_relevant_root_dirs
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Include Relevant Root Directories
        in a List of Paths to be Searched
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.path]) }}'
      loop: '{{ result_relevant_root_dirs.files }}'
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Increment Search Paths List with
        Local Partitions Mount Points
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.mount]) }}'
      loop: '{{ ansible_mounts }}'
      when:
      - item.fstype not in excluded_fstypes
      - item.mount != '/'
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Increment Search Paths List with
        Local NFS File System Targets
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.device.split('':'')[1]]) }}'
      loop: '{{ ansible_mounts }}'
      when: item.device is search("localhost:")
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Define Rule Specific Facts
      ansible.builtin.set_fact:
        shosts_equiv_files:
        - /shosts.equiv
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Find All shosts.equiv Files in Local
        File Systems
      ansible.builtin.command:
        cmd: find {{ item }} -xdev -type f -name "shosts.equiv"
      loop: '{{ search_paths }}'
      changed_when: false
      register: result_found_shosts_equiv_files
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Create List of shosts.equiv Files
        Present in Local File Systems
      ansible.builtin.set_fact:
        shosts_equiv_files: '{{ shosts_equiv_files | union(item.stdout_lines) | list }}'
      loop: '{{ result_found_shosts_equiv_files.results }}'
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

    - name: Remove Host-Based Authentication Files - Ensure No shosts.equiv Files Are
        Present in the System
      ansible.builtin.file:
        path: '{{ item }}'
        state: absent
      loop: '{{ shosts_equiv_files }}'
      tags:
      - DISA-STIG-RHEL-09-252070
      - high_severity
      - low_complexity
      - low_disruption
      - no_host_based_files
      - no_reboot_needed
      - restrict_strategy

#### Rule Remove User Host-Based Authentication Files [ref]

The `~/.shosts` (in each user's home directory) files list remote hosts and users that are trusted by the local system. To remove these files, run the following command to delete them from any location:

    $ sudo find / -name '.shosts' -type f -delete

Rationale: | The .shosts files are used to configure host-based authentication for individual users or the system via SSH. Host-based authentication is not sufficient for preventing unauthorized access to the system, as it does not require interactive identification and authentication of a connection request, or for the use of two-factor authentication.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_no_user_host_based_files

References:

os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257956r991589_rule

Remediation Shell script ⇲

    # Identify local mounts
    MOUNT_LIST=$(df --local | awk '{ print $6 }')

    # Find file on each listed mount point
    for cur_mount in ${MOUNT_LIST}
    do
    	find ${cur_mount} -xdev -type f -name ".shosts" -exec rm -f {} \;
    done

Remediation Ansible snippet ⇲

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

    - name: Remove User Host-Based Authentication Files - Define Excluded (Non-Local)
        File Systems and Paths
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
        excluded_paths:
        - dev
        - proc
        - run
        - sys
        search_paths: []
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Find Relevant Root Directories
        Ignoring Pre-Defined Excluded Paths
      ansible.builtin.find:
        paths: /
        file_type: directory
        excludes: '{{ excluded_paths }}'
        hidden: true
        recurse: false
      register: result_relevant_root_dirs
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Include Relevant Root Directories
        in a List of Paths to be Searched
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.path]) }}'
      loop: '{{ result_relevant_root_dirs.files }}'
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Increment Search Paths List
        with Local Partitions Mount Points
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.mount]) }}'
      loop: '{{ ansible_mounts }}'
      when:
      - item.fstype not in excluded_fstypes
      - item.mount != '/'
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Increment Search Paths List
        with Local NFS File System Targets
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.device.split('':'')[1]]) }}'
      loop: '{{ ansible_mounts }}'
      when: item.device is search("localhost:")
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Define Rule Specific Facts
      ansible.builtin.set_fact:
        user_shosts_files:
        - /.shosts
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Find All .shosts Files in Local
        File Systems
      ansible.builtin.command:
        cmd: find {{ item }} -xdev -type f -name ".shosts"
      loop: '{{ search_paths }}'
      changed_when: false
      register: result_found_shosts_files
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Create List of .shosts Files
        Present in Local File Systems
      ansible.builtin.set_fact:
        user_shosts_files: '{{ user_shosts_files | union(item.stdout_lines) | list }}'
      loop: '{{ result_found_shosts_files.results }}'
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

    - name: Remove User Host-Based Authentication Files - Ensure No .shosts Files Are
        Present in the System
      ansible.builtin.file:
        path: '{{ item }}'
        state: absent
      loop: '{{ user_shosts_files }}'
      tags:
      - DISA-STIG-RHEL-09-252075
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - no_user_host_based_files
      - restrict_strategy

Group Telnet Group contains 1 rule
[ref] The telnet protocol does not provide confidentiality or integrity for information transmitted on the network. This includes authentication information such as passwords. Organizations which use telnet should be actively working to migrate to a more secure protocol.

#### Rule Uninstall telnet-server Package [ref]

The `telnet-server` package can be removed with the following command:

    $ sudo dnf remove telnet-server

Rationale:

It is detrimental for operating systems to provide, or install by default, functionality exceeding requirements or mission objectives. These unnecessary capabilities are often overlooked and therefore may remain insecure. They increase the risk to the platform by providing additional attack vectors.
The telnet service provides an unencrypted remote access service which does not provide for the confidentiality and integrity of user passwords or the remote session. If a privileged user were to login using this service, the privileged user password could be compromised.
Removing the `telnet-server` package decreases the risk of the telnet service's accidental (or intentional) activation.

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_telnet-server_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-2.2.2
os-srg | SRG-OS-000095-GPOS-00049
anssi | R62
ism | 1409
pcidss4 | 2.2.4, 2.2
bsi | SYS.1.3.A8
cis | 2.1.15
stigref | SV-257831r1044898_rule

Remediation script ⇲

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

    dnf remove telnet-server

Remediation script ⇲

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

    package remove telnet-server

Remediation Shell script ⇲

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

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

    if rpm -q --quiet "telnet-server" ; then
    dnf remove -y --noautoremove "telnet-server"
    fi

Remediation Puppet snippet ⇲

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

    include remove_telnet-server

    class remove_telnet-server {
      package { 'telnet-server':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet ⇲

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

    package --remove=telnet-server

Remediation Ansible snippet ⇲

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

    - name: 'Uninstall telnet-server Package: Ensure telnet-server is removed'
      ansible.builtin.package:
        name: telnet-server
        state: absent
      tags:
      - DISA-STIG-RHEL-09-215040
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-2.2.2
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_telnet-server_removed

Group TFTP Server Group contains 1 rule
[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:

     $ sudo dnf remove tftp-server

Rationale: | Removing the `tftp-server` package decreases the risk of the accidental (or intentional) activation of tftp services. If TFTP is required for operational support (such as transmission of router configurations), its use must be documented with the Information Systems Security Manager (ISSM), restricted to only authorized personnel, and have access control rules established.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_tftp-server_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R62
pcidss4 | 2.2.4, 2.2
cis | 2.1.16
stigref | SV-257835r1102037_rule

Remediation script ⇲

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

    dnf remove tftp-server

Remediation script ⇲

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

    package remove tftp-server

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!

    if rpm -q --quiet "tftp-server" ; then
    dnf remove -y --noautoremove "tftp-server"
    fi

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 Anaconda snippet ⇲

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

    package --remove=tftp-server

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:
      - DISA-STIG-RHEL-09-215060
      - 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

Group SSH Server Group contains 2 groups and 38 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 Client if Necessary Group contains 1 rule

[ref] The following configuration changes apply to the SSH client. They can improve security parameters relwevant to the client user, e.g. increasing entropy while generating initialization vectors. Note that these changes influence only the default SSH client configuration. Changes in this group can be overridden by the client user by modifying files within the

    ~/.ssh

directory or by supplying parameters on the command line.

#### Rule Verify the SSH Private Key Files Have a Passcode [ref]

When creating SSH key pairs, always use a passcode.
You can create such keys with the following command:

    $ sudo ssh-keygen -n [passphrase]

Red Hat Enterprise Linux 9, for certificate-based authentication, must enforce authorized access to the corresponding private key.

Rationale: | If an unauthorized user obtains access to a private key without a passcode, that user would have unauthorized access to any system where the associated public key has been installed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ssh_keys_passphrase_protected

References:

os-srg | SRG-OS-000067-GPOS-00035
stigref | SV-258127r958450_rule

Group Configure OpenSSH Server if Necessary Group contains 22 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 SSHD Must Include System Crypto Policy Config File [ref]

SSHD should follow the system cryptographic policy. In order to accomplish this the SSHD configuration should include the configuration file provided by the system crypto policy. The following line should be present in `/etc/ssh/sshd_config` or in a file included by this file (a file within the `/etc/ssh/sshd_config.d` directory):

    Include /etc/crypto-policies/back-ends/opensshserver.config

Warning: There is no automated remediation because recommended action could severely disrupt the system and might not be efficient in fixing the problem.

Rationale: | Without cryptographic integrity protections, information can be altered by unauthorized users without detection.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_include_crypto_policy

References:

nist | AC-17 (2)
os-srg | SRG-OS-000250-GPOS-00093

#### 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
pcidss4 | 8.2.8, 8.2
cis | 5.1.9
stigref | SV-257995r1045053_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_sshd_set_keepalive='1'

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*ClientAliveCountMax\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*ClientAliveCountMax\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*ClientAliveCountMax\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "ClientAliveCountMax $var_sshd_set_keepalive" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255095
      - 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 1
      tags:
        - always

    - name: Set SSH Client Alive Count Max - Check if the parameter ClientAliveCountMax
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255095
      - 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: Set SSH Client Alive Count Max - Check if the parameter ClientAliveCountMax
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+{{ var_sshd_set_keepalive
          }}$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255095
      - 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: Set SSH Client Alive Count Max
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter ClientAliveCountMax is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "ClientAliveCountMax"| regex_escape }}\s+
          line: ClientAliveCountMax {{ var_sshd_set_keepalive }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255095
      - 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: Set SSH Client Alive Count Max - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255095
      - 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 600

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
pcidss4 | 8.2.8, 8.2
cis | 5.1.9
stigref | SV-257996r1045055_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    sshd_idle_timeout_value='600'

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*ClientAliveInterval\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*ClientAliveInterval\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*ClientAliveInterval\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "ClientAliveInterval $sshd_idle_timeout_value" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255100
      - 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 600
      tags:
        - always

    - name: Set SSH Client Alive Interval - Check if the parameter ClientAliveInterval
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255100
      - 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: Set SSH Client Alive Interval - Check if the parameter ClientAliveInterval
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+{{ sshd_idle_timeout_value
          }}$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255100
      - 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: Set SSH Client Alive Interval
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter ClientAliveInterval is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "ClientAliveInterval"| regex_escape }}\s+
          line: ClientAliveInterval {{ sshd_idle_timeout_value }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255100
      - 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: Set SSH Client Alive Interval - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255100
      - 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.d/00-complianceascode-hardening.conf`:

    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
ism | 0421, 0422, 0484, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.1, 8.3
cis | 5.1.12
stigref | SV-257992r1045047_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*HostbasedAuthentication\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*HostbasedAuthentication\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*HostbasedAuthentication\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "HostbasedAuthentication no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255080
      - 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 - Check if the parameter HostbasedAuthentication
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255080
      - 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 - Check if the parameter HostbasedAuthentication
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255080
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter HostbasedAuthentication is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "HostbasedAuthentication"| regex_escape }}\s+
          line: HostbasedAuthentication no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255080
      - 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 - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255080
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    metadata:
      annotations:
        complianceascode.io/ocp-version: '<=4.12'
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,%23%09%24OpenBSD%3A%20sshd_config%2Cv%201.103%202018%2F04%2F09%2020%3A41%3A22%20tj%20Exp%20%24%0A%0A%23%20This%20is%20the%20sshd%20server%20system-wide%20configuration%20file.%20%20See%0A%23%20sshd_config%285%29%20for%20more%20information.%0A%0A%23%20This%20sshd%20was%20compiled%20with%20PATH%3D%2Fusr%2Flocal%2Fbin%3A%2Fusr%2Fbin%3A%2Fusr%2Flocal%2Fsbin%3A%2Fusr%2Fsbin%0A%0A%23%20The%20strategy%20used%20for%20options%20in%20the%20default%20sshd_config%20shipped%20with%0A%23%20OpenSSH%20is%20to%20specify%20options%20with%20their%20default%20value%20where%0A%23%20possible%2C%20but%20leave%20them%20commented.%20%20Uncommented%20options%20override%20the%0A%23%20default%20value.%0A%0A%23%20If%20you%20want%20to%20change%20the%20port%20on%20a%20SELinux%20system%2C%20you%20have%20to%20tell%0A%23%20SELinux%20about%20this%20change.%0A%23%20semanage%20port%20-a%20-t%20ssh_port_t%20-p%20tcp%20%23PORTNUMBER%0A%23%0A%23Port%2022%0A%23AddressFamily%20any%0A%23ListenAddress%200.0.0.0%0A%23ListenAddress%20%3A%3A%0A%0AHostKey%20%2Fetc%2Fssh%2Fssh_host_rsa_key%0AHostKey%20%2Fetc%2Fssh%2Fssh_host_ecdsa_key%0AHostKey%20%2Fetc%2Fssh%2Fssh_host_ed25519_key%0A%0A%23%20Ciphers%20and%20keying%0ARekeyLimit%20512M%201h%0A%0A%23%20System-wide%20Crypto%20policy%3A%0A%23%20This%20system%20is%20following%20system-wide%20crypto%20policy.%20The%20changes%20to%0A%23%20Ciphers%2C%20MACs%2C%20KexAlgoritms%20and%20GSSAPIKexAlgorithsm%20will%20not%20have%20any%0A%23%20effect%20here.%20They%20will%20be%20overridden%20by%20command-line%20options%20passed%20on%0A%23%20the%20server%20start%20up.%0A%23%20To%20opt%20out%2C%20uncomment%20a%20line%20with%20redefinition%20of%20%20CRYPTO_POLICY%3D%0A%23%20variable%20in%20%20%2Fetc%2Fsysconfig%2Fsshd%20%20to%20overwrite%20the%20policy.%0A%23%20For%20more%20information%2C%20see%20manual%20page%20for%20update-crypto-policies%288%29.%0A%0A%23%20Logging%0A%23SyslogFacility%20AUTH%0ASyslogFacility%20AUTHPRIV%0A%23LogLevel%20INFO%0A%0A%23%20Authentication%3A%0A%0A%23LoginGraceTime%202m%0APermitRootLogin%20no%0AStrictModes%20yes%0A%23MaxAuthTries%206%0A%23MaxSessions%2010%0A%0APubkeyAuthentication%20yes%0A%0A%23%20The%20default%20is%20to%20check%20both%20.ssh%2Fauthorized_keys%20and%20.ssh%2Fauthorized_keys2%0A%23%20but%20this%20is%20overridden%20so%20installations%20will%20only%20check%20.ssh%2Fauthorized_keys%0AAuthorizedKeysFile%09.ssh%2Fauthorized_keys%0A%0A%23AuthorizedPrincipalsFile%20none%0A%0A%23AuthorizedKeysCommand%20none%0A%23AuthorizedKeysCommandUser%20nobody%0A%0A%23%20For%20this%20to%20work%20you%20will%20also%20need%20host%20keys%20in%20%2Fetc%2Fssh%2Fssh_known_hosts%0AHostbasedAuthentication%20no%0A%23%20Change%20to%20yes%20if%20you%20don%27t%20trust%20~%2F.ssh%2Fknown_hosts%20for%0A%23%20HostbasedAuthentication%0AIgnoreUserKnownHosts%20yes%0A%23%20Don%27t%20read%20the%20user%27s%20~%2F.rhosts%20and%20~%2F.shosts%20files%0AIgnoreRhosts%20yes%0A%0A%23%20To%20disable%20tunneled%20clear%20text%20passwords%2C%20change%20to%20no%20here%21%0A%23PasswordAuthentication%20yes%0APermitEmptyPasswords%20no%0APasswordAuthentication%20no%0A%0A%23%20Change%20to%20no%20to%20disable%20s%2Fkey%20passwords%0A%23ChallengeResponseAuthentication%20yes%0AChallengeResponseAuthentication%20no%0A%0A%23%20Kerberos%20options%0AKerberosAuthentication%20no%0A%23KerberosOrLocalPasswd%20yes%0A%23KerberosTicketCleanup%20yes%0A%23KerberosGetAFSToken%20no%0A%23KerberosUseKuserok%20yes%0A%0A%23%20GSSAPI%20options%0AGSSAPIAuthentication%20no%0AGSSAPICleanupCredentials%20no%0A%23GSSAPIStrictAcceptorCheck%20yes%0A%23GSSAPIKeyExchange%20no%0A%23GSSAPIEnablek5users%20no%0A%0A%23%20Set%20this%20to%20%27yes%27%20to%20enable%20PAM%20authentication%2C%20account%20processing%2C%0A%23%20and%20session%20processing.%20If%20this%20is%20enabled%2C%20PAM%20authentication%20will%0A%23%20be%20allowed%20through%20the%20ChallengeResponseAuthentication%20and%0A%23%20PasswordAuthentication.%20%20Depending%20on%20your%20PAM%20configuration%2C%0A%23%20PAM%20authentication%20via%20ChallengeResponseAuthentication%20may%20bypass%0A%23%20the%20setting%20of%20%22PermitRootLogin%20without-password%22.%0A%23%20If%20you%20just%20want%20the%20PAM%20account%20and%20session%20checks%20to%20run%20without%0A%23%20PAM%20authentication%2C%20then%20enable%20this%20but%20set%20PasswordAuthentication%0A%23%20and%20ChallengeResponseAuthentication%20to%20%27no%27.%0A%23%20WARNING%3A%20%27UsePAM%20no%27%20is%20not%20supported%20in%20Fedora%20and%20may%20cause%20several%0A%23%20problems.%0AUsePAM%20yes%0A%0A%23AllowAgentForwarding%20yes%0A%23AllowTcpForwarding%20yes%0A%23GatewayPorts%20no%0AX11Forwarding%20yes%0A%23X11DisplayOffset%2010%0A%23X11UseLocalhost%20yes%0A%23PermitTTY%20yes%0A%0A%23%20It%20is%20recommended%20to%20use%20pam_motd%20in%20%2Fetc%2Fpam.d%2Fsshd%20instead%20of%20PrintMotd%2C%0A%23%20as%20it%20is%20more%20configurable%20and%20versatile%20than%20the%20built-in%20version.%0APrintMotd%20no%0A%0APrintLastLog%20yes%0A%23TCPKeepAlive%20yes%0APermitUserEnvironment%20no%0ACompression%20no%0AClientAliveInterval%20600%0AClientAliveCountMax%200%0A%23UseDNS%20no%0A%23PidFile%20%2Fvar%2Frun%2Fsshd.pid%0A%23MaxStartups%2010%3A30%3A100%0A%23PermitTunnel%20no%0A%23ChrootDirectory%20none%0A%23VersionAddendum%20none%0A%0A%23%20no%20default%20banner%20path%0ABanner%20%2Fetc%2Fissue%0A%0A%23%20Accept%20locale-related%20environment%20variables%0AAcceptEnv%20LANG%20LC_CTYPE%20LC_NUMERIC%20LC_TIME%20LC_COLLATE%20LC_MONETARY%20LC_MESSAGES%0AAcceptEnv%20LC_PAPER%20LC_NAME%20LC_ADDRESS%20LC_TELEPHONE%20LC_MEASUREMENT%0AAcceptEnv%20LC_IDENTIFICATION%20LC_ALL%20LANGUAGE%0AAcceptEnv%20XMODIFIERS%0A%0A%23%20override%20default%20of%20no%20subsystems%0ASubsystem%09sftp%09%2Fusr%2Flibexec%2Fopenssh%2Fsftp-server%0A%0A%23%20Example%20of%20overriding%20settings%20on%20a%20per-user%20basis%0A%23Match%20User%20anoncvs%0A%23%09X11Forwarding%20no%0A%23%09AllowTcpForwarding%20no%0A%23%09PermitTTY%20no%0A%23%09ForceCommand%20cvs%20server%0A%0AUsePrivilegeSeparation%20sandbox
            mode: 0600
            path: /etc/ssh/sshd_config
            overwrite: true
    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    metadata:
      annotations:
        complianceascode.io/ocp-version: '>=4.13.0'
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ HostbasedAuthentication%20no }}
            mode: 0600
            path: /etc/ssh/sshd_config.d/00-complianceascode-disable_host_auth.conf
            overwrite: true

#### Rule Enable SSH Server firewalld Firewall Exception [ref]

If the SSH server is in use, inbound connections to SSH's port should be allowed to permit remote access through SSH. In more restrictive firewalld settings, the SSH port should be added to the proper firewalld zone in order to allow SSH remote access.
To configure `firewalld` to allow `ssh` access, run the following command(s):

    firewall-cmd --permanent --add-service=ssh

Then run the following command to load the newly created rule(s):

    firewall-cmd --reload

Warning: The remediation for this rule uses `firewall-cmd` and `nmcli` tools. Therefore, it will only be executed if `firewalld` and `NetworkManager` services are running. Otherwise, the remediation will be aborted and a informative message will be shown in the remediation report. These respective services will not be started in order to preserve any intentional change in network components related to firewall and network interfaces.
Warning: This rule also checks if the SSH port was modified by the administrator in the firewalld services definitions and is reflecting the expected port number. Although this is checked, fixing the custom ssh.xml file placed by the administrator at /etc/firewalld/services it is not in the scope of the remediation since there is no reliable way to manually change the respective file. If the default SSH port is modified, it is on the administrator responsibility to ensure the firewalld customizations in the service port level are properly configured.
Warning: Red Hat Enterprise Linux 9 prefers and recommends to use NetworkManager keyfiles instead of the `ifcfg` files stored in `/etc/sysconfig/network-scripts`. Therefore, if the system was upgraded from a previous release, make sure the NIC configuration files are properly migrated from `ifcfg` format to NetworkManager keyfiles. Otherwise, this rule won't be able to check the configuration. The migration can be accomplished by `nmcli connection migrate` command.

Rationale: | If inbound SSH connections are expected, adding the SSH port to the proper firewalld zone will allow remote access through the SSH port.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_firewalld_sshd_port_enabled

References:

cui | 3.1.12
nist | AC-17(a), CM-6(b), CM-7(a), CM-7(b)
os-srg | SRG-OS-000096-GPOS-00050
ism | 1416
bsi | SYS.1.3.A8
stigref | SV-257940r1106312_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "firewalld" ; then
        dnf install -y "firewalld"
    fi
    if ! rpm -q --quiet "NetworkManager" ; then
        dnf install -y "NetworkManager"
    fi
    firewalld_sshd_zone='public'

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; }; then
        # By default, NetworkManager interfaces are created only once
        # container image is booted so we do not have information about
        # what interfaces will be created during container build time.
        # Therefore, we will rely on NetworkManager to automatically assign
        # interfaces to the default firewalld zone. For more details see:
        # https://firewalld.org/documentation/man-pages/firewalld.zone.html
        # https://firewalld.org/documentation/zone/connections-interfaces-and-sources.html
        # That also means this remediation only works if zone defined in
        # the firewalld_sshd_zone variable equals to the default zone of firewalld.
        default_zone=$(firewall-offline-cmd --get-default-zone)
        if [ "$firewalld_sshd_zone" != "$default_zone" ]; then
            echo "Firewalld default zone ($default_zone) and pre-set zone for sshd ($firewalld_sshd_zone) differ. Remediation aborted!" >&2
            exit 1
        fi

        # Make sure default zone is set in all existing NetworkManager keyfiles.
        while IFS= read -r -d '' file; do
            sed "s|^\s*zone=.*$|zone=$firewalld_sshd_zone|g" "$file"
        done < <(find /etc/NetworkManager/system-connections -maxdepth 1 -name "*.nmconnection" -print0)

        firewall-offline-cmd --zone="$firewalld_sshd_zone" --add-service=ssh
    else
        if test "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)"; then
            # TODO: NM (nmcli) now has --offline mode support, and it could operate without NM service.
            # See: https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/1183
            # The feature is not quite straightforward (and probably incomplete), though.
            echo "Not applicable in offline mode. Remediation aborted!"
        else
            if systemctl is-active NetworkManager && systemctl is-active firewalld; then
                # First make sure the SSH service is enabled in run-time for the proper zone.
                # This is to avoid connection issues when new interfaces are addeded to this zone.
                firewall-cmd --zone="$firewalld_sshd_zone" --add-service=ssh

                # This will collect all NetworkManager connections names
                readarray -t nm_connections < <(nmcli -g UUID,TYPE con | grep -v loopback | awk -F ':' '{ print $1 }')
                # If the connection is not yet assigned to a firewalld zone, assign it to the proper zone.
                # This will not change connections which are already assigned to any firewalld zone.
                for connection in "${nm_connections[@]}"; do
                    current_zone=$(nmcli -f connection.zone connection show "$connection" | awk '{ print $2}')
                    if [ $current_zone = "--" ]; then
                        nmcli connection modify "$connection" connection.zone $firewalld_sshd_zone
                    fi
                done
                systemctl restart NetworkManager

                # Active zones are zones with at least one interface assigned to it.
                # It is possible that traffic is coming by any active interface and consequently any
                # active zone. So, this make sure all active zones are permanently allowing SSH service.
                readarray -t firewalld_active_zones < <(firewall-cmd --get-active-zones | grep -v "^ " | cut -d " " -f 1)
                for zone in "${firewalld_active_zones[@]}"; do
                    firewall-cmd --permanent --zone="$zone" --add-service=ssh
                done
                firewall-cmd --reload
            else
                echo "The firewalld or NetworkManager service is not active. Remediation aborted!"
            fi
        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:
      - DISA-STIG-RHEL-09-251035
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - firewalld_sshd_port_enabled
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value firewalld_sshd_zone # promote to variable
      set_fact:
        firewalld_sshd_zone: !!str public
      tags:
        - always

    - name: Enable SSH Server firewalld Firewall Exception - Ensure firewalld and NetworkManager
        packages are installed
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      with_items:
      - firewalld
      - NetworkManager
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251035
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - firewalld_sshd_port_enabled
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable SSH Server firewalld Firewall Exception - Collect facts about system
        services
      ansible.builtin.service_facts: null
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251035
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - firewalld_sshd_port_enabled
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable SSH Server firewalld Firewall Exception - Remediation is applicable
        if firewalld and NetworkManager services are running
      block:

      - name: Enable SSH Server firewalld Firewall Exception - Collect NetworkManager
          connections names
        ansible.builtin.shell:
          cmd: nmcli -g UUID,TYPE con | grep -v loopback | awk -F ':' '{ print $1 }'
        register: result_nmcli_cmd_connections_names
        check_mode: false
        changed_when: false
        failed_when: false

      - name: Enable SSH Server firewalld Firewall Exception - Collect NetworkManager
          connections zones
        ansible.builtin.shell:
          cmd: nmcli -f connection.zone connection show {{ item | trim }} | awk '{ print
            $2}'
        register: result_nmcli_cmd_connections_zones
        changed_when: false
        failed_when: false
        with_items:
        - '{{ result_nmcli_cmd_connections_names.stdout_lines | default([]) }}'
        when:
        - result_nmcli_cmd_connections_names.stdout_lines is defined
        - result_nmcli_cmd_connections_names.stdout_lines | length > 0

      - name: Enable SSH Server firewalld Firewall Exception - Ensure NetworkManager connections
          are assigned to a firewalld zone
        ansible.builtin.command:
          cmd: nmcli connection modify {{ item.0 }} connection.zone {{ firewalld_sshd_zone
            }}
        register: result_nmcli_cmd_zone_assignment
        changed_when: true
        with_together:
        - '{{ result_nmcli_cmd_connections_names.stdout_lines | default([]) }}'
        - '{{ result_nmcli_cmd_connections_zones.stdout_lines | default([]) }}'
        when:
        - result_nmcli_cmd_connections_zones.stdout_lines is defined
        - result_nmcli_cmd_connections_zones.stdout_lines | length > 0
        - item.1.stdout == '--' or item.1.stdout != firewalld_sshd_zone

      - name: Enable SSH Server firewalld Firewall Exception - Ensure NetworkManager connections
          changes are applied
        ansible.builtin.service:
          name: NetworkManager
          state: restarted
        when:
        - result_nmcli_cmd_zone_assignment is defined
        - result_nmcli_cmd_zone_assignment is changed
        - result_nmcli_cmd_zone_assignment.results | selectattr('changed', 'equalto',
          true) | list | length > 0

      - name: Enable SSH Server firewalld Firewall Exception - Collect firewalld active
          zones
        ansible.builtin.shell:
          cmd: firewall-cmd --get-active-zones | grep -v "^ " | cut -d " " -f 1
        register: result_firewall_cmd_zones_names
        changed_when: false
        failed_when: false

      - name: Enable SSH Server firewalld Firewall Exception - Ensure firewalld zones
          allow SSH
        ansible.posix.firewalld:
          zone: '{{ item }}'
          service: ssh
          permanent: true
          state: enabled
          immediate: true
        register: result_firewall_ssh_service_assignment
        with_items:
        - '{{ result_firewall_cmd_zones_names.stdout_lines | default([]) }}'
        when:
        - result_firewall_cmd_zones_names.stdout_lines is defined
        - result_firewall_cmd_zones_names.stdout_lines | length > 0
      when:
      - '"kernel-core" in ansible_facts.packages'
      - ansible_facts.services['firewalld.service'].state == 'running'
      - ansible_facts.services['NetworkManager.service'].state == 'running'
      tags:
      - DISA-STIG-RHEL-09-251035
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - firewalld_sshd_port_enabled
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Enable SSH Server firewalld Firewall Exception - Informative message based
        on services states
      ansible.builtin.assert:
        that:
        - ansible_check_mode or ansible_facts.services['firewalld.service'].state == 'running'
        - ansible_check_mode or ansible_facts.services['NetworkManager.service'].state
          == 'running'
        fail_msg:
        - firewalld and NetworkManager services are not active. Remediation aborted!
        - This remediation could not be applied because it depends on firewalld and NetworkManager
          services running.
        - The service is not started by this remediation in order to prevent connection
          issues.
        success_msg:
        - Enable SSH Server firewalld Firewall Exception remediation successfully executed
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-251035
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - configure_strategy
      - firewalld_sshd_port_enabled
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Disable Compression Or Set Compression to delayed [ref]

Compression is useful for slow network connections over long distances but can cause performance issues on local LANs. If use of compression is required, it should be enabled only after a user has authenticated; otherwise, it should be disabled. To disable compression or delay compression until after a user has successfully authenticated, add or correct the following line in the `/etc/ssh/sshd_config` file:

    Compression no

Rationale: | If compression is allowed in an SSH connection prior to authentication, vulnerabilities in the compression software could result in compromise of the system from an unauthenticated connection, potentially with root privileges.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_compression

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 | AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258002r991589_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_sshd_disable_compression='no'

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*Compression\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*Compression\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*Compression\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "Compression $var_sshd_disable_compression" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - DISA-STIG-RHEL-09-255130
      - 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_compression
    - name: XCCDF Value var_sshd_disable_compression # promote to variable
      set_fact:
        var_sshd_disable_compression: !!str no
      tags:
        - always

    - name: Disable Compression Or Set Compression to delayed - Check if the parameter
        Compression is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "Compression"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255130
      - 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_compression

    - name: Disable Compression Or Set Compression to delayed - Check if the parameter
        Compression is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "Compression"| regex_escape }}\s+{{ var_sshd_disable_compression
          }}$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255130
      - 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_compression

    - name: Disable Compression Or Set Compression to delayed
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "Compression"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter Compression is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "Compression"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "Compression"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "Compression"| regex_escape }}\s+
          line: Compression {{ var_sshd_disable_compression }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255130
      - 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_compression

    - name: Disable Compression Or Set Compression to delayed - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255130
      - 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_compression

#### 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.d/00-complianceascode-hardening.conf`:

    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
ism | 1546
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A8
cis | 5.1.19
stigref | SV-257984r1045026_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*PermitEmptyPasswords\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*PermitEmptyPasswords\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*PermitEmptyPasswords\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PermitEmptyPasswords no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255040
      - 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 - Check if the parameter PermitEmptyPasswords
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255040
      - 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 - Check if the parameter PermitEmptyPasswords
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255040
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter PermitEmptyPasswords is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "PermitEmptyPasswords"| regex_escape }}\s+
          line: PermitEmptyPasswords no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255040
      - 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 - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255040
      - 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 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.d/00-complianceascode-hardening.conf`:

    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
ism | 0418, 1055, 1402
cis | 5.1.11
stigref | SV-258003r1045065_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*GSSAPIAuthentication\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*GSSAPIAuthentication\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*GSSAPIAuthentication\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "GSSAPIAuthentication no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255135
      - 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 - Check if the parameter GSSAPIAuthentication
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255135
      - 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 - Check if the parameter GSSAPIAuthentication
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255135
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter GSSAPIAuthentication is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "GSSAPIAuthentication"| regex_escape }}\s+
          line: GSSAPIAuthentication no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255135
      - 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 - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255135
      - 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 Kerberos Authentication [ref]

Unless needed, SSH should not permit extraneous or unnecessary authentication mechanisms like Kerberos.
The default SSH configuration disallows authentication validation through Kerberos. The appropriate configuration is used if no value is set for `KerberosAuthentication`.
To explicitly disable Kerberos authentication, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    KerberosAuthentication no

Rationale: | Kerberos authentication for SSH is often implemented using GSSAPI. If Kerberos is enabled through SSH, the SSH daemon provides a means of access to the system's Kerberos implementation. Configuring these settings for the SSH daemon provides additional assurance that remote logon via SSH will not use unused methods of authentication, even in the event of misconfiguration elsewhere.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_kerb_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 | AC-17(a), CM-7(a), CM-7(b), CM-6(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
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
stigref | SV-258004r1045067_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*KerberosAuthentication\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*KerberosAuthentication\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*KerberosAuthentication\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "KerberosAuthentication no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255140
      - 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_kerb_auth

    - name: Disable Kerberos Authentication - Check if the parameter KerberosAuthentication
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255140
      - 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_kerb_auth

    - name: Disable Kerberos Authentication - Check if the parameter KerberosAuthentication
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255140
      - 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_kerb_auth

    - name: Disable Kerberos Authentication
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter KerberosAuthentication is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "KerberosAuthentication"| regex_escape }}\s+
          line: KerberosAuthentication no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255140
      - 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_kerb_auth

    - name: Disable Kerberos Authentication - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255140
      - 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_kerb_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.d/00-complianceascode-hardening.conf`:

    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
ism | 1546
pcidss4 | 2.2.6, 2.2
cis | 5.1.13
stigref | SV-258005r1045069_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*IgnoreRhosts\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*IgnoreRhosts\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*IgnoreRhosts\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "IgnoreRhosts yes" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255145
      - 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 - Check if the parameter IgnoreRhosts
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255145
      - 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 - Check if the parameter IgnoreRhosts
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255145
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter IgnoreRhosts is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "IgnoreRhosts"| regex_escape }}\s+
          line: IgnoreRhosts yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255145
      - 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 - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255145
      - 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.d/00-complianceascode-hardening.conf`:

    PermitRootLogin no

Rationale: | Even though the communications channel may be encrypted, an additional layer of security is gained by extending the policy of not logging directly on as root. In addition, logging in with a user-specific account provides individual accountability of actions performed on the system and also helps to minimize direct attack attempts on root's password.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_root_login

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.6
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.06, DSS06.10
cui | 3.1.1, 3.1.5
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.18.1.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.2.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3
nist | AC-6(2), AC-17(a), IA-2, IA-2(5), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5, PR.PT-3
ospp | FAU_GEN.1
pcidss | Req-2.2.4
os-srg | SRG-OS-000109-GPOS-00056, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000148-CTR-000335, SRG-APP-000190-CTR-000500
anssi | R33
ism | 1546
pcidss4 | 2.2.6, 2.2
cis | 5.1.20
stigref | SV-257985r1069364_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*PermitRootLogin\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*PermitRootLogin\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*PermitRootLogin\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PermitRootLogin no" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255045
      - 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 - Check if the parameter PermitRootLogin is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255045
      - 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 - Check if the parameter PermitRootLogin is configured
        correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255045
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter PermitRootLogin is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "PermitRootLogin"| regex_escape }}\s+
          line: PermitRootLogin no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255045
      - 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 - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255045
      - 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 Disable SSH Support for User Known Hosts [ref]

SSH can allow system users to connect to systems if a cache of the remote systems public keys is available. This should be disabled.
To ensure this behavior is disabled, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    IgnoreUserKnownHosts yes

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: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_user_known_hosts

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 | AC-17(a), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1
os-srg | SRG-OS-000480-GPOS-00227
ism | 1546
stigref | SV-258006r1045071_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*IgnoreUserKnownHosts\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*IgnoreUserKnownHosts\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*IgnoreUserKnownHosts\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "IgnoreUserKnownHosts yes" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - DISA-STIG-RHEL-09-255150
      - 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_user_known_hosts

    - name: Disable SSH Support for User Known Hosts - Check if the parameter IgnoreUserKnownHosts
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255150
      - 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_user_known_hosts

    - name: Disable SSH Support for User Known Hosts - Check if the parameter IgnoreUserKnownHosts
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255150
      - 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_user_known_hosts

    - name: Disable SSH Support for User Known Hosts
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter IgnoreUserKnownHosts is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "IgnoreUserKnownHosts"| regex_escape }}\s+
          line: IgnoreUserKnownHosts yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255150
      - 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_user_known_hosts

    - name: Disable SSH Support for User Known Hosts - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255150
      - 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_user_known_hosts

#### Rule Disable X11 Forwarding [ref]

The X11Forwarding parameter provides the ability to tunnel X11 traffic through the connection to enable remote graphic connections. SSH has the capability to encrypt remote X11 connections when SSH's `X11Forwarding` option is enabled.
The default SSH configuration disables X11Forwarding. The appropriate configuration is used if no value is set for `X11Forwarding`.
To explicitly disable X11 Forwarding, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    X11Forwarding no

Rationale: | Disable X11 forwarding unless there is an operational requirement to use X11 applications directly. There is a small risk that the remote X11 servers of users who are logged in via SSH with X11 forwarding could be compromised by other users on the X11 server. Note that even if X11 forwarding is disabled, users can always install their own forwarders.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_x11_forwarding

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
ism | 0484
pcidss4 | 2.2.6, 2.2
stigref | SV-258007r1045073_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*X11Forwarding\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*X11Forwarding\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*X11Forwarding\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "X11Forwarding no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255155
      - NIST-800-53-CM-6(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_x11_forwarding

    - name: Disable X11 Forwarding - Check if the parameter X11Forwarding is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255155
      - NIST-800-53-CM-6(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_x11_forwarding

    - name: Disable X11 Forwarding - Check if the parameter X11Forwarding is configured
        correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255155
      - NIST-800-53-CM-6(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_x11_forwarding

    - name: Disable X11 Forwarding
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter X11Forwarding is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "X11Forwarding"| regex_escape }}\s+
          line: X11Forwarding no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255155
      - NIST-800-53-CM-6(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_x11_forwarding

    - name: Disable X11 Forwarding - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255155
      - NIST-800-53-CM-6(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_x11_forwarding

#### 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.d/00-complianceascode-hardening.conf`:

    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
ism | 1546
pcidss4 | 2.2.6, 2.2
cis | 5.1.21
stigref | SV-257993r1045049_rule

Remediation Shell script ⇲

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

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*PermitUserEnvironment\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*PermitUserEnvironment\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*PermitUserEnvironment\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PermitUserEnvironment no" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255085
      - 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 - Check if the parameter PermitUserEnvironment
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255085
      - 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 - Check if the parameter PermitUserEnvironment
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+no$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255085
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter PermitUserEnvironment is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "PermitUserEnvironment"| regex_escape }}\s+
          line: PermitUserEnvironment no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255085
      - 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 - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255085
      - 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.d/00-complianceascode-hardening.conf`:

    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
pcidss4 | 2.2.6, 2.2
cis | 5.1.22
stigref | SV-257986r1045030_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*UsePAM\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*UsePAM\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*UsePAM\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "UsePAM yes" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - DISA-STIG-RHEL-09-255050
      - 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 - Check if the parameter UsePAM is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "UsePAM"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255050
      - 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 - Check if the parameter UsePAM is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "UsePAM"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255050
      - 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: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "UsePAM"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter UsePAM is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "UsePAM"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "UsePAM"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "UsePAM"| regex_escape }}\s+
          line: UsePAM yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255050
      - 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 - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255050
      - 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 Public Key Authentication [ref]

Enable SSH login with public keys.
The default SSH configuration enables authentication based on public keys. The appropriate configuration is used if no value is set for `PubkeyAuthentication`.
To explicitly enable Public Key Authentication, add or correct the following `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    PubkeyAuthentication yes

Rationale:

Without the use of multifactor authentication, the ease of access to privileged functions is greatly increased. Multifactor authentication requires using two or more factors to achieve authentication. A privileged account is defined as an information system account with authorizations of a privileged user. Smart cards or hardware tokens paired with digital certificates are common examples of multifactor implementations.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_enable_pubkey_auth

References:

os-srg | SRG-OS-000105-GPOS-00052, SRG-OS-000106-GPOS-00053, SRG-OS-000107-GPOS-00054, SRG-OS-000108-GPOS-00055
bsi | SYS.1.3.A8
stigref | SV-257983r1045024_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*PubkeyAuthentication\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*PubkeyAuthentication\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*PubkeyAuthentication\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PubkeyAuthentication yes" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - DISA-STIG-RHEL-09-255035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pubkey_auth

    - name: Enable Public Key Authentication - Check if the parameter PubkeyAuthentication
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pubkey_auth

    - name: Enable Public Key Authentication - Check if the parameter PubkeyAuthentication
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pubkey_auth

    - name: Enable Public Key Authentication
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter PubkeyAuthentication is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "PubkeyAuthentication"| regex_escape }}\s+
          line: PubkeyAuthentication yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pubkey_auth

    - name: Enable Public Key Authentication - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255035
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_pubkey_auth

#### Rule Enable Use of Strict Mode Checking [ref]

SSHs `StrictModes` option checks file and ownership permissions in the user's home directory `.ssh` folder before accepting login. If world- writable permissions are found, logon is rejected.
The default SSH configuration has `StrictModes` enabled. The appropriate configuration is used if no value is set for `StrictModes`.
To explicitly enable `StrictModes` in SSH, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    StrictModes yes

Rationale: | If other users have access to modify user-specific SSH configuration files, they may be able to log into the system as another user.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_enable_strictmodes

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
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.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-6, AC-17(a), CM-6(a)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
ism | 1409
stigref | SV-258008r1045075_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*StrictModes\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*StrictModes\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*StrictModes\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "StrictModes yes" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255160
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_strictmodes

    - name: Enable Use of Strict Mode Checking - Check if the parameter StrictModes is
        configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "StrictModes"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255160
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_strictmodes

    - name: Enable Use of Strict Mode Checking - Check if the parameter StrictModes is
        configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "StrictModes"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255160
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_strictmodes

    - name: Enable Use of Strict Mode Checking
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "StrictModes"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter StrictModes is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "StrictModes"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "StrictModes"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "StrictModes"| regex_escape }}\s+
          line: StrictModes yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255160
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_strictmodes

    - name: Enable Use of Strict Mode Checking - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255160
      - NIST-800-171-3.1.12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6
      - NIST-800-53-CM-6(a)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_strictmodes

#### 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.d/00-complianceascode-hardening.conf`:

    Banner /etc/issue

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

References:

cis-csc | 1, 12, 15, 16
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
ospp | FTA_TAB.1
pcidss | Req-2.2.4
os-srg | SRG-OS-000023-GPOS-00006, SRG-OS-000228-GPOS-00088
ism | 0484
stigref | SV-257981r1101970_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*Banner\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*Banner\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*Banner\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "Banner /etc/issue" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255025
      - 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)
      - PCI-DSS-Req-2.2.4
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner

    - name: Enable SSH Warning Banner - Check if the parameter Banner is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "Banner"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255025
      - 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)
      - PCI-DSS-Req-2.2.4
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner

    - name: Enable SSH Warning Banner - Check if the parameter Banner is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "Banner"| regex_escape }}\s+/etc/issue$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255025
      - 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)
      - PCI-DSS-Req-2.2.4
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner

    - name: Enable SSH Warning Banner
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "Banner"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter Banner is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "Banner"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "Banner"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "Banner"| regex_escape }}\s+
          line: Banner /etc/issue
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255025
      - 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)
      - PCI-DSS-Req-2.2.4
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner

    - name: Enable SSH Warning Banner - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - DISA-STIG-RHEL-09-255025
      - 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)
      - PCI-DSS-Req-2.2.4
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_enable_warning_banner

#### Rule Enable SSH Print Last Log [ref]

Ensure that SSH will display the date and time of the last successful account logon.
The default SSH configuration enables print of the date and time of the last login. The appropriate configuration is used if no value is set for `PrintLastLog`.
To explicitly enable LastLog in SSH, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    PrintLastLog yes

Rationale: | Providing users feedback on when account accesses last occurred facilitates user recognition and reporting of unauthorized account use.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_print_last_log

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | AC-9, AC-9(1)
nist-csf | PR.AC-7
os-srg | SRG-OS-000480-GPOS-00227
ism | 0582, 0846
stigref | SV-258009r1045077_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*PrintLastLog\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*PrintLastLog\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*PrintLastLog\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PrintLastLog yes" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255165
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_print_last_log

    - name: Enable SSH Print Last Log - Check if the parameter PrintLastLog is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255165
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_print_last_log

    - name: Enable SSH Print Last Log - Check if the parameter PrintLastLog is configured
        correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255165
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_print_last_log

    - name: Enable SSH Print Last Log
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter PrintLastLog is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "PrintLastLog"| regex_escape }}\s+
          line: PrintLastLog yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255165
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_print_last_log

    - name: Enable SSH Print Last Log - set file mode for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255165
      - NIST-800-53-AC-9
      - NIST-800-53-AC-9(1)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_print_last_log

#### Rule Force frequent session key renegotiation [ref]

The `RekeyLimit` parameter specifies how often the session key of the is renegotiated, both in terms of amount of data that may be transmitted and the time elapsed.
To decrease the default limits, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    RekeyLimit 1G
                      1h

Rationale: | By decreasing the limit based on the amount of data and enabling time-based limit, effects of potential attacks against encryption keys are limited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_rekey_limit

References:

ospp | FCS_SSH_EXT.1.8
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000033-GPOS-00014
stigref | SV-257994r1045051_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    var_rekey_limit_size='1G'
    var_rekey_limit_time='1h'

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*RekeyLimit\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*RekeyLimit\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*RekeyLimit\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "RekeyLimit $var_rekey_limit_size $var_rekey_limit_time" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"

    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:
      - DISA-STIG-RHEL-09-255090
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - sshd_rekey_limit
    - name: XCCDF Value var_rekey_limit_size # promote to variable
      set_fact:
        var_rekey_limit_size: !!str 1G
      tags:
        - always
    - name: XCCDF Value var_rekey_limit_time # promote to variable
      set_fact:
        var_rekey_limit_time: !!str 1h
      tags:
        - always

    - name: Force frequent session key renegotiation - Check if the parameter RekeyLimit
        is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255090
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - sshd_rekey_limit

    - name: Force frequent session key renegotiation - Check if the parameter RekeyLimit
        is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+{{ var_rekey_limit_size }}
          {{ var_rekey_limit_time }}$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255090
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - sshd_rekey_limit

    - name: Force frequent session key renegotiation
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter RekeyLimit is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "RekeyLimit"| regex_escape }}\s+
          line: RekeyLimit {{ var_rekey_limit_size }} {{ var_rekey_limit_time }}
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255090
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - sshd_rekey_limit

    - name: Force frequent session key renegotiation - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255090
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - sshd_rekey_limit

#### Rule Set SSH Daemon LogLevel to VERBOSE [ref]

The `VERBOSE` parameter configures the SSH daemon to record login and logout activity. To specify the log level in SSH, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`:

    LogLevel VERBOSE

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` or `VERBOSE` 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: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_set_loglevel_verbose

References:

nerc-cip | CIP-007-3 R7.1
nist | AC-17(a), AC-17(1), CM-6(a)
pcidss | Req-2.2.4
os-srg | SRG-OS-000032-GPOS-00013
pcidss4 | 2.2.6, 2.2
cis | 5.1.15
stigref | SV-257982r1045021_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
    chmod 0600 /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf

    LC_ALL=C sed -i "/^\s*LogLevel\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*LogLevel\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" ] ; then

        LC_ALL=C sed -i "/^\s*LogLevel\s\+/Id" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    else
        touch "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"

    cp "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf" "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "LogLevel VERBOSE" > "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    cat "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf.bak" >> "/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/00-complianceascode-hardening.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:
      - DISA-STIG-RHEL-09-255030
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - 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_set_loglevel_verbose

    - name: Set SSH Daemon LogLevel to VERBOSE - Check if the parameter LogLevel is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "LogLevel"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255030
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - 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_set_loglevel_verbose

    - name: Set SSH Daemon LogLevel to VERBOSE - Check if the parameter LogLevel is configured
        correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "LogLevel"| regex_escape }}\s+VERBOSE$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255030
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - 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_set_loglevel_verbose

    - name: Set SSH Daemon LogLevel to VERBOSE
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "LogLevel"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter LogLevel is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "LogLevel"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "LogLevel"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "LogLevel"| regex_escape }}\s+
          line: LogLevel VERBOSE
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255030
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - 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_set_loglevel_verbose

    - name: Set SSH Daemon LogLevel to VERBOSE - set file mode for /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/00-complianceascode-hardening.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255030
      - NIST-800-53-AC-17(1)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-CM-6(a)
      - 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_set_loglevel_verbose

#### Rule Prevent remote hosts from connecting to the proxy display [ref]

The SSH daemon should prevent remote hosts from connecting to the proxy display. The default SSH configuration for `X11UseLocalhost` is `yes`, which prevents remote hosts from connecting to the proxy display. To explicitly prevent remote connections to the proxy display, add or correct the following line in `/etc/ssh/sshd_config.d/00-complianceascode-hardening.conf`: `X11UseLocalhost yes`
Rationale: | When X11 forwarding is enabled, there may be additional exposure to the server and client displays if the sshd proxy display is configured to listen on the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the `DISPLAY` environment variable to localhost. This prevents remote hosts from connecting to the proxy display.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_x11_use_localhost

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-258011r1045079_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    mkdir -p /etc/ssh/sshd_config.d
    touch /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
    chmod 0600 /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf

    LC_ALL=C sed -i "/^\s*X11UseLocalhost\s\+/Id" "/etc/ssh/sshd_config"
    LC_ALL=C sed -i "/^\s*X11UseLocalhost\s\+/Id" "/etc/ssh/sshd_config.d"/*.conf
    if [ -e "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" ] ; then

        LC_ALL=C sed -i "/^\s*X11UseLocalhost\s\+/Id" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    else
        touch "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"

    cp "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf" "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak"
    # Insert at the beginning of the file
    printf '%s\n' "X11UseLocalhost yes" > "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    cat "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf.bak" >> "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.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:
      - DISA-STIG-RHEL-09-255175
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_x11_use_localhost

    - name: Prevent remote hosts from connecting to the proxy display - Check if the parameter
        X11UseLocalhost is configured
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+
      register: _sshd_config_has_parameter
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255175
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_x11_use_localhost

    - name: Prevent remote hosts from connecting to the proxy display - Check if the parameter
        X11UseLocalhost is configured correctly
      ansible.builtin.find:
        paths:
        - /etc/ssh/sshd_config
        - /etc/ssh/sshd_config.d
        contains: (?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+yes$
      register: _sshd_config_correctly
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255175
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_x11_use_localhost

    - name: Prevent remote hosts from connecting to the proxy display
      block:

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: false
          regexp: (?i)(?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+
          state: absent

      - name: Check if /etc/ssh/sshd_config.d exists
        ansible.builtin.stat:
          path: /etc/ssh/sshd_config.d
        register: _etc_ssh_sshd_config_d_exists

      - name: Check if the parameter X11UseLocalhost is present in /etc/ssh/sshd_config.d
        ansible.builtin.find:
          paths: /etc/ssh/sshd_config.d
          recurse: 'yes'
          follow: 'no'
          contains: (?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+
        register: _etc_ssh_sshd_config_d_has_parameter
        when: _etc_ssh_sshd_config_d_exists.stat.isdir is defined and _etc_ssh_sshd_config_d_exists.stat.isdir

      - name: Remove parameter from files in /etc/ssh/sshd_config.d
        ansible.builtin.lineinfile:
          path: '{{ item.path }}'
          create: false
          regexp: (?i)(?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+
          state: absent
        with_items: '{{ _etc_ssh_sshd_config_d_has_parameter.files }}'
        when: _etc_ssh_sshd_config_d_has_parameter.matched

      - name: Insert correct line to /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
          create: true
          regexp: (?i)(?i)^\s*{{ "X11UseLocalhost"| regex_escape }}\s+
          line: X11UseLocalhost yes
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when:
      - '"kernel-core" in ansible_facts.packages'
      - _sshd_config_correctly.matched == 0 or _sshd_config_has_parameter.matched != 1
      tags:
      - DISA-STIG-RHEL-09-255175
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_x11_use_localhost

    - name: Prevent remote hosts from connecting to the proxy display - set file mode
        for /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/01-complianceascode-reinforce-os-defaults.conf
        mode: '0600'
        state: touch
        modification_time: preserve
        access_time: preserve
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255175
      - NIST-800-53-CM-6(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_x11_use_localhost

#### Rule Install OpenSSH client software [ref]

The `openssh-clients` package can be installed with the following command:

    $ sudo dnf install openssh-clients

Rationale: | This package includes utilities to make encrypted connections and transfer files securely to SSH servers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_openssh-clients_installed

References:

ospp | FIA_UAU.5, FTP_ITC_EXT.1, FCS_SSH_EXT.1, FCS_SSHC_EXT.1
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257980r1045016_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    dnf install openssh-clients

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package install openssh-clients

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    if ! rpm -q --quiet "openssh-clients" ; then
        dnf install -y "openssh-clients"
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_openssh-clients

    class install_openssh-clients {
      package { 'openssh-clients':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package --add=openssh-clients

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Ensure openssh-clients is installed
      ansible.builtin.package:
        name: openssh-clients
        state: present
      tags:
      - DISA-STIG-RHEL-09-255020
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_openssh-clients_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "openssh-clients"
    version = "*"

#### Rule Install the OpenSSH Server Package [ref]

The `openssh-server` package should be installed. The `openssh-server` package can be installed with the following command:

    $ sudo dnf install openssh-server

Rationale: | Without protection of the transmitted information, confidentiality, and integrity may be compromised because unprotected communications can be intercepted and either read or altered.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_openssh-server_installed

References:

cis-csc | 13, 14
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.07, DSS06.02, DSS06.06
isa-62443-2013 | SR 3.1, SR 3.8, SR 4.1, SR 4.2, 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)
nist-csf | PR.DS-2, PR.DS-5
ospp | FIA_UAU.5, FTP_ITC_EXT.1, FCS_SSH_EXT.1, FCS_SSHS_EXT.1
os-srg | SRG-OS-000423-GPOS-00187, SRG-OS-000424-GPOS-00188, SRG-OS-000425-GPOS-00189, SRG-OS-000426-GPOS-00190
stigref | SV-257978r1045013_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    dnf install openssh-server

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package install openssh-server

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "openssh-server" ; then
        dnf install -y "openssh-server"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_openssh-server

    class install_openssh-server {
      package { 'openssh-server':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package --add=openssh-server

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-255010
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_openssh-server_installed

    - name: Ensure openssh-server is installed
      ansible.builtin.package:
        name: openssh-server
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255010
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_openssh-server_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "openssh-server"
    version = "*"

#### Rule Enable the OpenSSH Service [ref]

The SSH server service, sshd, is commonly needed. The `sshd` service can be enabled with the following command:

    $ sudo systemctl enable sshd.service

Rationale:

Without protection of the transmitted information, confidentiality, and integrity may be compromised because unprotected communications can be intercepted and either read or altered.
This checklist item applies to both internal and external networks and all types of information system components from which information can be transmitted (e.g., servers, mobile devices, notebook computers, printers, copiers, scanners, etc). Communication paths outside the physical protection of a controlled boundary are exposed to the possibility of interception and modification.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_sshd_enabled

References:

cis-csc | 13, 14
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.13, 3.5.4, 3.13.8
isa-62443-2013 | SR 3.1, SR 3.8, SR 4.1, SR 4.2, 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), SC-8, SC-8(1), SC-8(2), SC-8(3), SC-8(4)
nist-csf | PR.DS-2, PR.DS-5
os-srg | SRG-OS-000423-GPOS-00187, SRG-OS-000424-GPOS-00188, SRG-OS-000425-GPOS-00189, SRG-OS-000426-GPOS-00190
bsi | SYS.1.3.A8
stigref | SV-257979r958908_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    service enable sshd

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'sshd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'sshd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'sshd.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_sshd

    class enable_sshd {
      service {'sshd':
        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:
      - DISA-STIG-RHEL-09-255015
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.8
      - NIST-800-171-3.5.4
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-8
      - NIST-800-53-SC-8(1)
      - NIST-800-53-SC-8(2)
      - NIST-800-53-SC-8(3)
      - NIST-800-53-SC-8(4)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_sshd_enabled

    - name: Enable the OpenSSH Service - Enable service sshd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable the OpenSSH Service - Enable Service sshd
        ansible.builtin.systemd:
          name: sshd
          enabled: true
          state: started
          masked: false
        when:
        - '"openssh-server" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255015
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.8
      - NIST-800-171-3.5.4
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-8
      - NIST-800-53-SC-8(1)
      - NIST-800-53-SC-8(2)
      - NIST-800-53-SC-8(3)
      - NIST-800-53-SC-8(4)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_sshd_enabled
      - special_service_block
      when: '"kernel-core" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["sshd"]

#### Rule Verify Group Who Owns SSH Server Configuration Files [ref]

To properly set the group owner of `/etc/ssh/sshd_config.d`, run the command:

    $ sudo chgrp root /etc/ssh/sshd_config.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_directory_groupowner_sshd_config_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
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
stigref | SV-257997r1069370_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    find -P /etc/ssh/sshd_config.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:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_groupowner_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_sshd_config_d_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        directory_groupowner_sshd_config_d_newgroup: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_groupowner_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ssh/sshd_config.d/
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/
        follow: false
        state: directory
        group: '{{ directory_groupowner_sshd_config_d_newgroup }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_groupowner_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on SSH Server Configuration Files [ref]

To properly set the owner of `/etc/ssh/sshd_config.d`, run the command:

    $ sudo chown root /etc/ssh/sshd_config.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_directory_owner_sshd_config_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
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
stigref | SV-257998r1082181_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/ssh/sshd_config.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:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_owner_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_sshd_config_d_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_sshd_config_d_newown: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_owner_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/ssh/sshd_config.d/
      ansible.builtin.file:
        path: /etc/ssh/sshd_config.d/
        follow: false
        state: directory
        owner: '{{ directory_owner_sshd_config_d_newown }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_owner_sshd_config_d
      - 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.d`, run the command:

    $ sudo chmod 0700 /etc/ssh/sshd_config.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_directory_permissions_sshd_config_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
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
stigref | SV-257999r1082182_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    find -H /etc/ssh/sshd_config.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:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_permissions_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/sshd_config.d/ file(s)
      ansible.builtin.command: 'find -P /etc/ssh/sshd_config.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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_permissions_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/ssh/sshd_config.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - directory_permissions_sshd_config_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### 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
bsi | SYS.1.3.A14
cis | 5.1.1
stigref | SV-257997r1069370_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-255105
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns SSH Server Configuration Files [ref]

To properly set the group owner of files in `/etc/ssh/sshd_config.d`, run the command:

    find -H /etc/ssh/sshd_config.d -type d -exec chgrp -L root {} \;

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_drop_in_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
stigref | SV-257997r1069370_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -type f  ! -group 0 -regextype posix-extended -regex '^.*$' -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:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_sshd_drop_in_config_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupowner_sshd_drop_in_config_newgroup: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/sshd_config.d/ file(s) matching ^.*$
      ansible.builtin.command: find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -type f  !
        -group 0 -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ssh/sshd_config.d/ file(s) matching ^.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_sshd_drop_in_config_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255105
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_drop_in_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
bsi | SYS.1.3.A14
cis | 5.1.1
stigref | SV-257998r1082181_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-255110
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-255110
      - 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 Owner on SSH Server Configuration Files [ref]

To properly set the owner of files in `/etc/ssh/sshd_config.d`, run the command:

    find -H /etc/ssh/sshd_config.d -type d -exec chown -L root {} \;

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_drop_in_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
stigref | SV-257998r1082181_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else

    find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*$' -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:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_sshd_drop_in_config_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_sshd_drop_in_config_newown: '0'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/sshd_config.d/ file(s) matching ^.*$
      ansible.builtin.command: find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -type f  !
        -user 0 -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ssh/sshd_config.d/ file(s) matching ^.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_sshd_drop_in_config_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255110
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_drop_in_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
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 5.1.1
stigref | SV-257999r1082182_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-255115
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255115
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-255115
      - 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 Config File [ref]

To properly set the permissions of files in `/etc/ssh/sshd_config.d`, run the command:

    find -H /etc/ssh/sshd_config.d -type d -exec chown 0600 {} \;

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_drop_in_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
stigref | SV-257999r1082182_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type f -regextype posix-extended -regex '^.*$' -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:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/sshd_config.d/ file(s)
      ansible.builtin.command: find -P /etc/ssh/sshd_config.d/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type
        f -regextype posix-extended -regex "^.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_sshd_drop_in_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/ssh/sshd_config.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xwrs,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255115
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_sshd_drop_in_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. If they are owned by the `root` user, but by a dedicated group `ssh_keys`, they can have the `0640` permission or stricter.
Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.

Rationale: | If an unauthorized user obtains the private SSH host key file, the host could be impersonated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sshd_private_key

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.13, 3.13.10
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-2.2.4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
ism | 1449
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 5.1.2
stigref | SV-258000r1045063_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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"

        elif test root:ssh_keys = "$(stat -c "%U:%G" "$keyfile")"; then
    	chmod u-xs,g-xws,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:
      - DISA-STIG-RHEL-09-255120
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255120
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255120
      - 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:ssh_keys-owned keys
      ansible.builtin.command: find -H /etc/ssh/ -maxdepth 1 -user root -regex ".*_key$"
        -type f -group ssh_keys -perm /u+xs,g+xws,o+xwrt
      register: dedicated_group_owned_keys
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255120
      - 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:ssh_keys-owned keys
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwrt
        state: file
      with_items:
      - '{{ dedicated_group_owned_keys.stdout_lines }}'
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255120
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on SSH Server Public *.pub Key Files [ref]

To properly set the permissions of `/etc/ssh/*.pub`, run the command:

    $ sudo chmod 0644 /etc/ssh/*.pub

Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.

Rationale: | If a public host key file is modified by an unauthorized user, the SSH service may be compromised.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sshd_pub_key

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.13, 3.13.10
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-2.2.4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2
bsi | SYS.1.3.A14
cis | 5.1.3
stigref | SV-258001r991589_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-255125
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255125
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-255125
      - 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

#### Rule The File /etc/ssh/sshd_config.d/50-redhat.conf Must Exist [ref]

The `/etc/ssh/sshd_config.d/50-redhat.conf` file must exist as it contains important settings to secure SSH. Warning: There is no remediation available for this rule since this file needs to have the correct content for the given system.
Rationale: | The file must exist to configure SSH correctly.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_sshd_50_redhat_exists

References:

nist | AC-17 (2)
os-srg | SRG-OS-000250-GPOS-00093

Group System Security Services Daemon Group contains 5 rules

[ref] The System Security Services Daemon (SSSD) is a system daemon that provides access to different identity and authentication providers such as Red Hat's IdM, Microsoft's AD, openLDAP, MIT Kerberos, etc. It uses a common framework that can provide caching and offline support to systems utilizing SSSD. SSSD using caching to reduce load on authentication servers permit offline authentication as well as store extended user data.
For more information, see https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html-single/installing_identity_management/index#assembly_installing-an-idm-client_installing-identity-management

#### Rule Certificate status checking in SSSD [ref]

Multifactor solutions that require devices separate from information systems gaining access include, for example, hardware tokens providing time-based or challenge-response authenticators and smart cards. Configuring `certificate_verification` to `ocsp_dgst=sha512` ensures that certificates for multifactor solutions are checked via Online Certificate Status Protocol (OCSP).
Rationale: | Ensuring that multifactor solutions certificates are checked via Online Certificate Status Protocol (OCSP) ensures the security of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_certificate_verification

References:

nist | IA-2(11)
os-srg | SRG-OS-000375-GPOS-00160, SRG-OS-000377-GPOS-00162
stigref | SV-258123r1045248_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q sssd-common; then

    var_sssd_certificate_verification_digest_function='sha512'

    # sssd configuration files must be created with 600 permissions if they don't exist
    # otherwise the sssd module fails to start
    OLD_UMASK=$(umask)
    umask u=rw,go=

    MAIN_CONF="/etc/sssd/conf.d/certificate_verification.conf"

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "$MAIN_CONF /etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[sssd\]([^\n\[]*\n+)+?[[:space:]]*certificate_verification" "$f"; then
            if ! grep -qPz "certificate_verification=ocsp_dgst=$var_sssd_certificate_verification_digest_function" "$f"; then

                sed -i "s/certificate_verification[^(\n)]*/certificate_verification=ocsp_dgst=$var_sssd_certificate_verification_digest_function/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[sssd\]" "$f"; then

                sed -i "/[[:space:]]*\[sssd\]/a certificate_verification=ocsp_dgst=$var_sssd_certificate_verification_digest_function" "$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 "$MAIN_CONF /etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[sssd]\ncertificate_verification=ocsp_dgst=$var_sssd_certificate_verification_digest_function" >> "$file"

    fi

    umask $OLD_UMASK

    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:
      - DISA-STIG-RHEL-09-611170
      - NIST-800-53-IA-2(11)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_certificate_verification
    - name: XCCDF Value var_sssd_certificate_verification_digest_function # promote to variable
      set_fact:
        var_sssd_certificate_verification_digest_function: !!str sha512
      tags:
        - always

    - name: Ensure that "certificate_verification" is not set in /etc/sssd/sssd.conf
      community.general.ini_file:
        path: /etc/sssd/sssd.conf
        section: sssd
        option: certificate_verification
        state: absent
        mode: 384
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611170
      - NIST-800-53-IA-2(11)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_certificate_verification

    - name: Ensure that "certificate_verification" is not set in  /etc/sssd/conf.d/*.conf
      community.general.ini_file:
        path: /etc/sssd/conf.d/*.conf
        section: sssd
        option: certificate_verification
        state: absent
        mode: 384
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611170
      - NIST-800-53-IA-2(11)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_certificate_verification

    - name: Ensure that "certificate_verification" is set
      community.general.ini_file:
        path: /etc/sssd/conf.d/certificate_verification.conf
        section: sssd
        option: certificate_verification
        value: ocsp_dgst={{ var_sssd_certificate_verification_digest_function }}
        state: present
        mode: 384
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611170
      - NIST-800-53-IA-2(11)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_certificate_verification

#### Rule Enable Certmap in SSSD [ref]

SSSD should be configured to verify the certificate of the user or group. To set this up ensure that section like `certmap/testing.test/rule_name` is setup in `/etc/sssd/sssd.conf`. For example

    [certmap/testing.test/rule_name]
    matchrule =<SAN>.*EDIPI@mil
    maprule = (userCertificate;binary={cert!bin})
    domains = testing.test

Warning: Automatic remediation of this control is not available, since all of the settings in in the certmap need to be customized.

Rationale: | Without mapping the certificate used to authenticate to the user account, the ability to determine the identity of the individual user or group will not be available for forensic analysis.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_enable_certmap

References:

nist | IA-5 (2) (c)
os-srg | SRG-OS-000068-GPOS-00036
stigref | SV-258132r1045260_rule

#### Rule Enable Smartcards in SSSD [ref]

SSSD should be configured to authenticate access to the system using smart cards. To enable smart cards in SSSD, set `pam_cert_auth` to `True` under the `[pam]` section in `/etc/sssd/sssd.conf`. For example:

    [pam]
    pam_cert_auth = True

Add or update "pam_sss.so" line in auth section of "/etc/pam.d/system-auth" file to include "try_cert_auth" or "require_cert_auth" option, like in the following example:

    /etc/pam.d/system-auth:auth [success=done authinfo_unavail=ignore ignore=ignore default=die] pam_sss.so try_cert_auth

Also add or update "pam_sss.so" line in auth section of "/etc/pam.d/smartcard-auth" file to include the "allow_missing_name" option, like in the following example:

    /etc/pam.d/smartcard-auth:auth sufficient pam_sss.so allow_missing_name

Rationale:

Using an authentication device, such as a CAC or token that is separate from the information system, ensures that even if the information system is compromised, that compromise will not affect credentials stored on the authentication device.
Multi-Factor Authentication (MFA) solutions that require devices separate from information systems gaining access include, for example, hardware tokens providing time-based or challenge-response authenticators and smart cards or similar secure authentication devices issued by an organization or identity provider.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_enable_smartcards

References:

pcidss | Req-8.3
os-srg | SRG-OS-000375-GPOS-00160, SRG-OS-000105-GPOS-00052, SRG-OS-000106-GPOS-00053, SRG-OS-000107-GPOS-00054, SRG-OS-000108-GPOS-00055
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
stigref | SV-258122r1045246_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q sssd-common; then

    # sssd configuration files must be created with 600 permissions if they don't exist
    # otherwise the sssd module fails to start
    OLD_UMASK=$(umask)
    umask u=rw,go=

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[pam\]([^\n\[]*\n+)+?[[:space:]]*pam_cert_auth" "$f"; then
            if ! grep -qPz "pam_cert_auth=True" "$f"; then

                sed -i "s/pam_cert_auth[^(\n)]*/pam_cert_auth=True/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[pam\]" "$f"; then

                sed -i "/[[:space:]]*\[pam\]/a pam_cert_auth=True" "$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 "/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[pam]\npam_cert_auth=True" >> "$file"

    fi

    umask $OLD_UMASK

    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-smartcard

        authselect apply-changes -b
    else

        if ! grep -qP "^\s*auth\s+sufficient\s+pam_sss.so\s*.*" "/etc/pam.d/smartcard-auth"; then
            # Line matching group + control + module was not found. Check group + module.
            if [ "$(grep -cP '^\s*auth\s+.*\s+pam_sss.so\s*' "/etc/pam.d/smartcard-auth")" -eq 1 ]; then
                # The control is updated only if one single line matches.
                sed -i -E --follow-symlinks "s/^(\s*auth\s+).*(\bpam_sss.so.*)/\1sufficient \2/" "/etc/pam.d/smartcard-auth"
            else
                echo "auth    sufficient    pam_sss.so" >> "/etc/pam.d/smartcard-auth"
            fi
        fi
        # Check the option
        if ! grep -qP "^\s*auth\s+sufficient\s+pam_sss.so\s*.*\sallow_missing_name\b" "/etc/pam.d/smartcard-auth"; then
            sed -i -E --follow-symlinks "/\s*auth\s+sufficient\s+pam_sss.so.*/ s/$/ allow_missing_name/" "/etc/pam.d/smartcard-auth"
        fi

        if ! grep -qP "^\s*auth\s+\[success=done authinfo_unavail=ignore ignore=ignore default=die\]\s+pam_sss.so\s*.*" "/etc/pam.d/system-auth"; then
            # Line matching group + control + module was not found. Check group + module.
            if [ "$(grep -cP '^\s*auth\s+.*\s+pam_sss.so\s*' "/etc/pam.d/system-auth")" -eq 1 ]; then
                # The control is updated only if one single line matches.
                sed -i -E --follow-symlinks "s/^(\s*auth\s+).*(\bpam_sss.so.*)/\1[success=done authinfo_unavail=ignore ignore=ignore default=die] \2/" "/etc/pam.d/system-auth"
            else
                echo "auth    [success=done authinfo_unavail=ignore ignore=ignore default=die]    pam_sss.so" >> "/etc/pam.d/system-auth"
            fi
        fi
        # Check the option
        if ! grep -qP "^\s*auth\s+\[success=done authinfo_unavail=ignore ignore=ignore default=die\]\s+pam_sss.so\s*.*\stry_cert_auth\b" "/etc/pam.d/system-auth"; then
            sed -i -E --follow-symlinks "/\s*auth\s+\[success=done authinfo_unavail=ignore ignore=ignore default=die\]\s+pam_sss.so.*/ s/$/ try_cert_auth/" "/etc/pam.d/system-auth"
        fi
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Test for domain group
      ansible.builtin.command: grep '^\s*\[domain\/[^]]*]' /etc/sssd/sssd.conf
      register: test_grep_domain
      failed_when: false
      changed_when: false
      check_mode: false
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Add default domain group (if no domain there)
      community.general.ini_file:
        path: /etc/sssd/sssd.conf
        section: '{{ item.section }}'
        option: '{{ item.option }}'
        value: '{{ item.value }}'
        create: true
        mode: 384
      with_items:
      - section: sssd
        option: domains
        value: default
      - section: domain/default
        option: id_provider
        value: files
      when:
      - '"sssd-common" in ansible_facts.packages'
      - test_grep_domain.stdout is defined
      - test_grep_domain.stdout | length < 1
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Enable Smartcards in SSSD
      community.general.ini_file:
        dest: /etc/sssd/sssd.conf
        section: pam
        option: pam_cert_auth
        value: 'True'
        create: true
        mode: 384
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Find all the conf files inside /etc/sssd/conf.d/
      ansible.builtin.find:
        paths: /etc/sssd/conf.d/
        patterns: '*.conf'
      register: sssd_conf_d_files
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Fix pam_cert_auth configuration in /etc/sssd/conf.d/
      ansible.builtin.replace:
        path: '{{ item.path }}'
        regexp: '[^#]*pam_cert_auth.*'
        replace: pam_cert_auth = True
      with_items: '{{ sssd_conf_d_files.files }}'
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Enable Smartcards in SSSD - Check if system relies on authselect
      ansible.builtin.stat:
        path: /usr/bin/authselect
      register: result_authselect_present
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Enable Smartcards in SSSD - Remediate using authselect
      block:

      - name: Enable Smartcards in SSSD - 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: Enable Smartcards in SSSD - 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: Enable Smartcards in SSSD - Get authselect current features
        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_check_cmd is success

      - name: Enable Smartcards in SSSD - Ensure "with-smartcard" feature is enabled using
          authselect tool
        ansible.builtin.command:
          cmd: authselect enable-feature with-smartcard
        register: result_authselect_enable_feature_cmd
        when:
        - result_authselect_check_cmd is success
        - result_authselect_features.stdout is not search("with-smartcard")

      - name: Enable Smartcards in SSSD - Ensure authselect changes are applied
        ansible.builtin.command:
          cmd: authselect apply-changes -b
        when:
        - result_authselect_enable_feature_cmd is not skipped
        - result_authselect_enable_feature_cmd is success
      when:
      - '"sssd-common" in ansible_facts.packages'
      - result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

    - name: Enable Smartcards in SSSD - Remediate by directly editing PAM files
      block:

      - name: Enable Smartcards in SSSD - Define a fact for control already filtered in
          case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Enable Smartcards in SSSD - Check if expected PAM module line is present
          in /etc/pam.d/smartcard-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/smartcard-auth
          regexp: ^\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Enable Smartcards in SSSD - Include or update the PAM module line in /etc/pam.d/smartcard-auth
        block:

        - name: Enable Smartcards in SSSD - Check if required PAM module line is present
            in /etc/pam.d/smartcard-auth with different control
          ansible.builtin.lineinfile:
            path: /etc/pam.d/smartcard-auth
            regexp: ^\s*auth\s+.*\s+pam_sss.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Enable Smartcards in SSSD - Ensure the correct control for the required
            PAM module line in /etc/pam.d/smartcard-auth
          ansible.builtin.replace:
            dest: /etc/pam.d/smartcard-auth
            regexp: ^(\s*auth\s+).*(\bpam_sss.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Enable Smartcards in SSSD - Ensure the required PAM module line is included
            in /etc/pam.d/smartcard-auth
          ansible.builtin.lineinfile:
            dest: /etc/pam.d/smartcard-auth
            line: auth    {{ pam_module_control }}    pam_sss.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: Enable Smartcards in SSSD - 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: Enable Smartcards in SSSD - Define a fact for control already filtered in
          case filters are used
        ansible.builtin.set_fact:
          pam_module_control: sufficient

      - name: Enable Smartcards in SSSD - Check if the required PAM module option is present
          in /etc/pam.d/smartcard-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/smartcard-auth
          regexp: ^\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so\s*.*\sallow_missing_name\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_sssd_enable_smartcards_option_present

      - name: Enable Smartcards in SSSD - Ensure the "allow_missing_name" PAM option for
          "pam_sss.so" is included in /etc/pam.d/smartcard-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/smartcard-auth
          backrefs: true
          regexp: ^(\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so.*)
          line: \1 allow_missing_name
          state: present
        register: result_pam_sssd_enable_smartcards_add
        when:
        - result_pam_module_sssd_enable_smartcards_option_present.found is defined
        - result_pam_module_sssd_enable_smartcards_option_present.found == 0

      - name: Enable Smartcards in SSSD - Define a fact for control already filtered in
          case filters are used
        ansible.builtin.set_fact:
          pam_module_control: '[success=done authinfo_unavail=ignore ignore=ignore default=die]'

      - name: Enable Smartcards in SSSD - Check if expected PAM module line is present
          in /etc/pam.d/system-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: ^\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so\s*.*
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_line_present

      - name: Enable Smartcards in SSSD - Include or update the PAM module line in /etc/pam.d/system-auth
        block:

        - name: Enable Smartcards in SSSD - Check if required PAM module line is present
            in /etc/pam.d/system-auth with different control
          ansible.builtin.lineinfile:
            path: /etc/pam.d/system-auth
            regexp: ^\s*auth\s+.*\s+pam_sss.so\s*
            state: absent
          check_mode: true
          changed_when: false
          register: result_pam_line_other_control_present

        - name: Enable Smartcards in SSSD - Ensure the correct control for the required
            PAM module line in /etc/pam.d/system-auth
          ansible.builtin.replace:
            dest: /etc/pam.d/system-auth
            regexp: ^(\s*auth\s+).*(\bpam_sss.so.*)
            replace: \1{{ pam_module_control }} \2
          register: result_pam_module_edit
          when:
          - result_pam_line_other_control_present.found == 1

        - name: Enable Smartcards in SSSD - Ensure the required PAM module line is included
            in /etc/pam.d/system-auth
          ansible.builtin.lineinfile:
            dest: /etc/pam.d/system-auth
            line: auth    {{ pam_module_control }}    pam_sss.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: Enable Smartcards in SSSD - 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: Enable Smartcards in SSSD - Define a fact for control already filtered in
          case filters are used
        ansible.builtin.set_fact:
          pam_module_control: '[success=done authinfo_unavail=ignore ignore=ignore default=die]'

      - name: Enable Smartcards in SSSD - Check if the required PAM module option is present
          in /etc/pam.d/system-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          regexp: ^\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so\s*.*\stry_cert_auth\b
          state: absent
        check_mode: true
        changed_when: false
        register: result_pam_module_sssd_enable_smartcards_option_present

      - name: Enable Smartcards in SSSD - Ensure the "try_cert_auth" PAM option for "pam_sss.so"
          is included in /etc/pam.d/system-auth
        ansible.builtin.lineinfile:
          path: /etc/pam.d/system-auth
          backrefs: true
          regexp: ^(\s*auth\s+{{ pam_module_control | regex_escape() }}\s+pam_sss.so.*)
          line: \1 try_cert_auth
          state: present
        register: result_pam_sssd_enable_smartcards_add
        when:
        - result_pam_module_sssd_enable_smartcards_option_present.found is defined
        - result_pam_module_sssd_enable_smartcards_option_present.found == 0
      when:
      - '"sssd-common" in ansible_facts.packages'
      - not result_authselect_present.stat.exists
      tags:
      - DISA-STIG-RHEL-09-611165
      - PCI-DSS-Req-8.3
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_smartcards

#### Rule SSSD Has a Correct Trust Anchor [ref]

SSSD must have acceptable trust anchor present. Warning: Automatic remediation of this control is not available.

Rationale:

Without path validation, an informed trust decision by the relying party cannot be made when presented with any certificate not already explicitly trusted. A trust anchor is an authoritative entity represented via a public key and associated data. It is used in the context of public key infrastructures, X.509 digital certificates, and DNSSEC. When there is a chain of trust, usually the top entity to be trusted becomes the trust anchor; it can be, for example, a Certification Authority (CA). A certification path starts with the subject certificate and proceeds through a number of intermediate certificates up to a trusted root certificate, typically issued by a trusted CA. This requirement verifies that a certification path to an accepted trust anchor is used for certificate validation and that the path includes status information. Path validation is necessary for a relying party to make an informed trust decision when presented with any certificate not already explicitly trusted. Status information for certification paths includes certificate revocation lists or online certificate status protocol responses. Validation of the certificate status information is out of scope for this requirement.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_has_trust_anchor

References:

nist | IA-5 (2) (a)
os-srg | SRG-OS-000066-GPOS-00034, SRG-OS-000384-GPOS-00167
stigref | SV-258131r1015125_rule

#### Rule Configure SSSD to Expire Offline Credentials [ref]

SSSD should be configured to expire offline credentials after 1 day. Check if SSSD allows cached authentications with the following command:

    $ sudo grep cache_credentials /etc/sssd/sssd.conf
    cache_credentials = true

If "cache_credentials" is set to "false" or is missing no further checks are required.
To configure SSSD to expire offline credentials, set `offline_credentials_expiration` to `1` under the `[pam]` section in `/etc/sssd/sssd.conf`. For example:

    [pam]
    offline_credentials_expiration = 1

Rationale: | If cached authentication information is out-of-date, the validity of the authentication information may be questionable.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_offline_cred_expiration

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), IA-5(13)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000383-GPOS-00166
stigref | SV-258133r1045263_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q sssd-common; then

    # sssd configuration files must be created with 600 permissions if they don't exist
    # otherwise the sssd module fails to start
    OLD_UMASK=$(umask)
    umask u=rw,go=

    found=false

    # set value in all files if they contain section or key
    for f in $(echo -n "/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf"); do
        if [ ! -e "$f" ]; then
            continue
        fi

        # find key in section and change value
        if grep -qzosP "[[:space:]]*\[pam\]([^\n\[]*\n+)+?[[:space:]]*offline_credentials_expiration" "$f"; then
            if ! grep -qPz "offline_credentials_expiration=1" "$f"; then

                sed -i "s/offline_credentials_expiration[^(\n)]*/offline_credentials_expiration=1/" "$f"

            fi

            found=true

        # find section and add key = value to it
        elif grep -qs "[[:space:]]*\[pam\]" "$f"; then

                sed -i "/[[:space:]]*\[pam\]/a offline_credentials_expiration=1" "$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 "/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf" | cut -f1 -d ' ')
        mkdir -p "$(dirname "$file")"

        echo -e "[pam]\noffline_credentials_expiration=1" >> "$file"

    fi

    umask $OLD_UMASK

    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:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

    - name: Test for domain group
      ansible.builtin.command: grep '\s*\[domain\/[^]]*]' /etc/sssd/sssd.conf
      register: test_grep_domain
      failed_when: false
      changed_when: false
      check_mode: false
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

    - name: Add default domain group (if no domain there)
      community.general.ini_file:
        path: /etc/sssd/sssd.conf
        section: '{{ item.section }}'
        option: '{{ item.option }}'
        value: '{{ item.value }}'
        create: true
        mode: 384
      with_items:
      - section: sssd
        option: domains
        value: default
      - section: domain/default
        option: id_provider
        value: files
      when:
      - '"sssd-common" in ansible_facts.packages'
      - test_grep_domain.stdout is defined
      - test_grep_domain.stdout | length < 1
      tags:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

    - name: Configure SSD to Expire Offline Credentials
      community.general.ini_file:
        dest: /etc/sssd/sssd.conf
        section: pam
        option: offline_credentials_expiration
        value: 1
        create: true
        mode: 384
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

    - name: Find all the conf files inside /etc/sssd/conf.d/
      ansible.builtin.find:
        paths: /etc/sssd/conf.d/
        patterns: '*.conf'
      register: sssd_conf_d_files
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

    - name: Fix offline_credentials_expiration configuration in /etc/sssd/conf.d/
      ansible.builtin.replace:
        path: '{{ item.path }}'
        regexp: '[^#]*offline_credentials_expiration.*'
        replace: offline_credentials_expiration = 1
      with_items: '{{ sssd_conf_d_files.files }}'
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-631020
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(13)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_offline_cred_expiration

Group USBGuard daemon Group contains 4 rules
[ref] The USBGuard daemon enforces the USB device authorization policy for all USB devices.

#### Rule Install usbguard Package [ref]

The `usbguard` package can be installed with the following command:

    $ sudo dnf install usbguard

Rationale: | `usbguard` is a software framework that helps to protect against rogue USB devices by implementing basic whitelisting/blacklisting capabilities based on USB device attributes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_usbguard_installed

References:

nist | CM-8(3), IA-3
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000378-GPOS-00163
app-srg-ctr | SRG-APP-000141-CTR-000315
ism | 1418
stigref | SV-258035r1045125_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    dnf install usbguard

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package install usbguard

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if ( ! ( grep -sqE "^.*\.s390x$" /proc/sys/kernel/osrelease || grep -sqE "^s390x$" /proc/sys/kernel/arch; ) && rpm --quiet -q kernel-core ); then

    if ! rpm -q --quiet "usbguard" ; then
        dnf install -y "usbguard"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_usbguard

    class install_usbguard {
      package { 'usbguard':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package --add=usbguard

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-291015
      - NIST-800-53-CM-8(3)
      - NIST-800-53-IA-3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_usbguard_installed

    - name: Ensure usbguard is installed
      ansible.builtin.package:
        name: usbguard
        state: present
      when: ( ansible_architecture != "s390x" and "kernel-core" in ansible_facts.packages
        )
      tags:
      - DISA-STIG-RHEL-09-291015
      - NIST-800-53-CM-8(3)
      - NIST-800-53-IA-3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_usbguard_installed

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
      extensions:
        - usbguard

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "usbguard"
    version = "*"

#### Rule Enable the USBGuard Service [ref]

The USBGuard service should be enabled. The `usbguard` service can be enabled with the following command:

    $ sudo systemctl enable usbguard.service

Rationale: | The `usbguard` service must be running in order to enforce the USB device authorization policy for all USB devices.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_usbguard_enabled

References:

nist | CM-8(3)(a), IA-3
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000378-GPOS-00163
app-srg-ctr | SRG-APP-000141-CTR-000315
ism | 1418
stigref | SV-258036r1014861_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    service enable usbguard

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if ( ! ( grep -sqE "^.*\.s390x$" /proc/sys/kernel/osrelease || grep -sqE "^s390x$" /proc/sys/kernel/arch; ) && rpm --quiet -q kernel-core ); then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'usbguard.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'usbguard.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'usbguard.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_usbguard

    class enable_usbguard {
      service {'usbguard':
        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:
      - DISA-STIG-RHEL-09-291020
      - NIST-800-53-CM-8(3)(a)
      - NIST-800-53-IA-3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_usbguard_enabled

    - name: Enable the USBGuard Service - Enable service usbguard
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable the USBGuard Service - Enable Service usbguard
        ansible.builtin.systemd:
          name: usbguard
          enabled: true
          state: started
          masked: false
        when:
        - '"usbguard" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-291020
      - NIST-800-53-CM-8(3)(a)
      - NIST-800-53-IA-3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_usbguard_enabled
      - special_service_block
      when: ( ansible_architecture != "s390x" and "kernel-core" in ansible_facts.packages
        )

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    metadata:
      annotations:
        complianceascode.io/depends-on: xccdf_org.ssgproject.content_rule_package_usbguard_installed
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: usbguard.service
            enabled: true

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["usbguard"]

#### Rule Log USBGuard daemon audit events using Linux Audit [ref]

To configure USBGuard daemon to log via Linux Audit (as opposed directly to a file), `AuditBackend` option in `/etc/usbguard/usbguard-daemon.conf` needs to be set to `LinuxAudit`.
Rationale: | Using the Linux Audit logging allows for centralized trace of events.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_configure_usbguard_auditbackend

References:

nist | AU-2, CM-8(3), IA-3
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000062-GPOS-00031, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000141-CTR-000315
stigref | SV-258037r1014863_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( ! ( grep -sqE "^.*\.s390x$" /proc/sys/kernel/osrelease || grep -sqE "^s390x$" /proc/sys/kernel/arch; ) && rpm --quiet -q kernel-core ) && { rpm --quiet -q usbguard; }; then

    if [ -e "/etc/usbguard/usbguard-daemon.conf" ] ; then

        LC_ALL=C sed -i "/^[ \\t]*AuditBackend=/Id" "/etc/usbguard/usbguard-daemon.conf"
    else
        touch "/etc/usbguard/usbguard-daemon.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/usbguard/usbguard-daemon.conf"

    cp "/etc/usbguard/usbguard-daemon.conf" "/etc/usbguard/usbguard-daemon.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "AuditBackend=LinuxAudit" >> "/etc/usbguard/usbguard-daemon.conf"
    # Clean up after ourselves.
    rm "/etc/usbguard/usbguard-daemon.conf.bak"

    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:
      - DISA-STIG-RHEL-09-291025
      - NIST-800-53-AU-2
      - NIST-800-53-CM-8(3)
      - NIST-800-53-IA-3
      - configure_strategy
      - configure_usbguard_auditbackend
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Log USBGuard daemon audit events using Linux Audit
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/usbguard/usbguard-daemon.conf
          create: true
          regexp: (?i)^[ \\t]*AuditBackend=
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/usbguard/usbguard-daemon.conf
        ansible.builtin.lineinfile:
          path: /etc/usbguard/usbguard-daemon.conf
          create: true
          regexp: (?i)^[ \\t]*AuditBackend=
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/usbguard/usbguard-daemon.conf
        ansible.builtin.lineinfile:
          path: /etc/usbguard/usbguard-daemon.conf
          create: true
          regexp: (?i)^[ \\t]*AuditBackend=
          line: AuditBackend=LinuxAudit
          state: present
      when:
      - ( ansible_architecture != "s390x" and "kernel-core" in ansible_facts.packages
        )
      - '"usbguard" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-291025
      - NIST-800-53-AU-2
      - NIST-800-53-CM-8(3)
      - NIST-800-53-IA-3
      - configure_strategy
      - configure_usbguard_auditbackend
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    metadata:
      annotations:
        complianceascode.io/depends-on: xccdf_org.ssgproject.content_rule_package_usbguard_installed
        complianceascode.io/ocp-version: '>=4.7.0'
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %0A%23%0A%23%20Rule%20set%20file%20path.%0A%23%0A%23%20The%20USBGuard%20daemon%20will%20use%20this%20file%20to%20load%20the%20policy%0A%23%20rule%20set%20from%20it%20and%20to%20write%20new%20rules%20received%20via%20the%0A%23%20IPC%20interface.%0A%23%0A%23%20RuleFile%3D/path/to/rules.conf%0A%23%0ARuleFile%3D/etc/usbguard/rules.conf%0A%0A%23%0A%23%20Rule%20set%20folder%20path.%0A%23%0A%23%20The%20USBGuard%20daemon%20will%20use%20this%20folder%20to%20load%20the%20policy%0A%23%20rule%20set%20from%20it%20and%20to%20write%20new%20rules%20received%20via%20the%0A%23%20IPC%20interface.%20Usually%2C%20we%20set%20the%20option%20to%0A%23%20/etc/usbguard/rules.d/.%20The%20USBGuard%20daemon%20is%20supposed%20to%0A%23%20behave%20like%20any%20other%20standard%20Linux%20daemon%20therefore%20it%0A%23%20loads%20rule%20files%20in%20alpha-numeric%20order.%20File%20names%20inside%0A%23%20RuleFolder%20directory%20should%20start%20with%20a%20two-digit%20number%0A%23%20prefix%20indicating%20the%20position%2C%20in%20which%20the%20rules%20are%0A%23%20scanned%20by%20the%20daemon.%0A%23%0A%23%20RuleFolder%3D/path/to/rulesfolder/%0A%23%0ARuleFolder%3D/etc/usbguard/rules.d/%0A%0A%23%0A%23%20Implicit%20policy%20target.%0A%23%0A%23%20How%20to%20treat%20devices%20that%20don%27t%20match%20any%20rule%20in%20the%0A%23%20policy.%20One%20of%3A%0A%23%0A%23%20%2A%20allow%20%20-%20authorize%20the%20device%0A%23%20%2A%20block%20%20-%20block%20the%20device%0A%23%20%2A%20reject%20-%20remove%20the%20device%0A%23%0AImplicitPolicyTarget%3Dblock%0A%0A%23%0A%23%20Present%20device%20policy.%0A%23%0A%23%20How%20to%20treat%20devices%20that%20are%20already%20connected%20when%20the%0A%23%20daemon%20starts.%20One%20of%3A%0A%23%0A%23%20%2A%20allow%20%20%20%20%20%20%20%20-%20authorize%20every%20present%20device%0A%23%20%2A%20block%20%20%20%20%20%20%20%20-%20deauthorize%20every%20present%20device%0A%23%20%2A%20reject%20%20%20%20%20%20%20-%20remove%20every%20present%20device%0A%23%20%2A%20keep%20%20%20%20%20%20%20%20%20-%20just%20sync%20the%20internal%20state%20and%20leave%20it%0A%23%20%2A%20apply-policy%20-%20evaluate%20the%20ruleset%20for%20every%20present%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20device%0A%23%0APresentDevicePolicy%3Dapply-policy%0A%0A%23%0A%23%20Present%20controller%20policy.%0A%23%0A%23%20How%20to%20treat%20USB%20controllers%20that%20are%20already%20connected%0A%23%20when%20the%20daemon%20starts.%20One%20of%3A%0A%23%0A%23%20%2A%20allow%20%20%20%20%20%20%20%20-%20authorize%20every%20present%20device%0A%23%20%2A%20block%20%20%20%20%20%20%20%20-%20deauthorize%20every%20present%20device%0A%23%20%2A%20reject%20%20%20%20%20%20%20-%20remove%20every%20present%20device%0A%23%20%2A%20keep%20%20%20%20%20%20%20%20%20-%20just%20sync%20the%20internal%20state%20and%20leave%20it%0A%23%20%2A%20apply-policy%20-%20evaluate%20the%20ruleset%20for%20every%20present%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20device%0A%23%0APresentControllerPolicy%3Dkeep%0A%0A%23%0A%23%20Inserted%20device%20policy.%0A%23%0A%23%20How%20to%20treat%20USB%20devices%20that%20are%20already%20connected%0A%23%20%2Aafter%2A%20the%20daemon%20starts.%20One%20of%3A%0A%23%0A%23%20%2A%20block%20%20%20%20%20%20%20%20-%20deauthorize%20every%20present%20device%0A%23%20%2A%20reject%20%20%20%20%20%20%20-%20remove%20every%20present%20device%0A%23%20%2A%20apply-policy%20-%20evaluate%20the%20ruleset%20for%20every%20present%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20device%0A%23%0AInsertedDevicePolicy%3Dapply-policy%0A%0A%23%0A%23%20Control%20which%20devices%20are%20authorized%20by%20default.%0A%23%0A%23%20The%20USBGuard%20daemon%20modifies%20some%20the%20default%20authorization%20state%20attributes%0A%23%20of%20controller%20devices.%20This%20setting%2C%20enables%20you%20to%20define%20what%20value%20the%0A%23%20default%20authorization%20is%20set%20to.%0A%23%0A%23%20%2A%20keep%20%20%20%20%20%20%20%20%20-%20do%20not%20change%20the%20authorization%20state%0A%23%20%2A%20none%20%20%20%20%20%20%20%20%20-%20every%20new%20device%20starts%20out%20deauthorized%0A%23%20%2A%20all%20%20%20%20%20%20%20%20%20%20-%20every%20new%20device%20starts%20out%20authorized%0A%23%20%2A%20internal%20%20%20%20%20-%20internal%20devices%20start%20out%20authorized%2C%20external%20devices%20start%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20out%20deauthorized%20%28this%20requires%20the%20ACPI%20tables%20to%20properly%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20label%20internal%20devices%2C%20and%20kernel%20support%29%0A%23%0A%23AuthorizedDefault%3Dnone%0A%0A%23%0A%23%20Restore%20controller%20device%20state.%0A%23%0A%23%20The%20USBGuard%20daemon%20modifies%20some%20attributes%20of%20controller%0A%23%20devices%20like%20the%20default%20authorization%20state%20of%20new%20child%20device%0A%23%20instances.%20Using%20this%20setting%2C%20you%20can%20control%20whether%20the%0A%23%20daemon%20will%20try%20to%20restore%20the%20attribute%20values%20to%20the%20state%0A%23%20before%20modification%20on%20shutdown.%0A%23%0A%23%20SECURITY%20CONSIDERATIONS%3A%20If%20set%20to%20true%2C%20the%20USB%20authorization%0A%23%20policy%20could%20be%20bypassed%20by%20performing%20some%20sort%20of%20attack%20on%20the%0A%23%20daemon%20%28via%20a%20local%20exploit%20or%20via%20a%20USB%20device%29%20to%20make%20it%20shutdown%0A%23%20and%20restore%20to%20the%20operating-system%20default%20state%20%28known%20to%20be%20permissive%29.%0A%23%0ARestoreControllerDeviceState%3Dfalse%0A%0A%23%0A%23%20Device%20manager%20backend%0A%23%0A%23%20Which%20device%20manager%20backend%20implementation%20to%20use.%20One%20of%3A%0A%23%0A%23%20%2A%20uevent%20%20%20-%20Netlink%20based%20implementation%20which%20uses%20sysfs%20to%20scan%20for%20present%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20devices%20and%20an%20uevent%20netlink%20socket%20for%20receiving%20USB%20device%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20related%20events.%0A%23%20%2A%20umockdev%20-%20umockdev%20based%20device%20manager%20capable%20of%20simulating%20devices%20based%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20on%20umockdev-record%20files.%20Useful%20for%20testing.%0A%23%0ADeviceManagerBackend%3Duevent%0A%0A%23%21%21%21%20WARNING%3A%20It%27s%20good%20practice%20to%20set%20at%20least%20one%20of%20the%20%21%21%21%0A%23%21%21%21%20%20%20%20%20%20%20%20%20%20two%20options%20bellow.%20If%20none%20of%20them%20are%20set%2C%20%20%21%21%21%0A%23%21%21%21%20%20%20%20%20%20%20%20%20%20the%20daemon%20will%20accept%20IPC%20connections%20from%20%20%20%21%21%21%0A%23%21%21%21%20%20%20%20%20%20%20%20%20%20anyone%2C%20thus%20allowing%20anyone%20to%20modify%20the%20%20%20%20%21%21%21%0A%23%21%21%21%20%20%20%20%20%20%20%20%20%20rule%20set%20and%20%28de%29authorize%20USB%20devices.%20%20%20%20%20%20%20%21%21%21%0A%0A%23%0A%23%20Users%20allowed%20to%20use%20the%20IPC%20interface.%0A%23%0A%23%20A%20space%20delimited%20list%20of%20usernames%20that%20the%20daemon%20will%0A%23%20accept%20IPC%20connections%20from.%0A%23%0A%23%20IPCAllowedUsers%3Dusername1%20username2%20...%0A%23%0AIPCAllowedUsers%3Droot%0A%0A%23%0A%23%20Groups%20allowed%20to%20use%20the%20IPC%20interface.%0A%23%0A%23%20A%20space%20delimited%20list%20of%20groupnames%20that%20the%20daemon%20will%0A%23%20accept%20IPC%20connections%20from.%0A%23%0A%23%20IPCAllowedGroups%3Dgroupname1%20groupname2%20...%0A%23%0AIPCAllowedGroups%3Dwheel%0A%0A%23%0A%23%20IPC%20access%20control%20definition%20files%20path.%0A%23%0A%23%20The%20files%20at%20this%20location%20will%20be%20interpreted%20by%20the%20daemon%0A%23%20as%20access%20control%20definition%20files.%20The%20%28base%29name%20of%20a%20file%0A%23%20should%20be%20in%20the%20form%3A%0A%23%0A%23%20%20%20%5Buser%5D%5B%3A%3Cgroup%3E%5D%0A%23%0A%23%20and%20should%20contain%20lines%20in%20the%20form%3A%0A%23%0A%23%20%20%20%3Csection%3E%3D%5Bprivilege%5D%20...%0A%23%0A%23%20This%20way%20each%20file%20defines%20who%20is%20able%20to%20connect%20to%20the%20IPC%0A%23%20bus%20and%20what%20privileges%20he%20has.%0A%23%0AIPCAccessControlFiles%3D/etc/usbguard/IPCAccessControl.d/%0A%0A%23%0A%23%20Generate%20device%20specific%20rules%20including%20the%20%22via-port%22%0A%23%20attribute.%0A%23%0A%23%20This%20option%20modifies%20the%20behavior%20of%20the%20allowDevice%0A%23%20action.%20When%20instructed%20to%20generate%20a%20permanent%20rule%2C%0A%23%20the%20action%20can%20generate%20a%20port%20specific%20rule.%20Because%0A%23%20some%20systems%20have%20unstable%20port%20numbering%2C%20the%20generated%0A%23%20rule%20might%20not%20match%20the%20device%20after%20rebooting%20the%20system.%0A%23%0A%23%20If%20set%20to%20false%2C%20the%20generated%20rule%20will%20still%20contain%0A%23%20the%20%22parent-hash%22%20attribute%20which%20also%20defines%20an%20association%0A%23%20to%20the%20parent%20device.%20See%20usbguard-rules.conf%285%29%20for%20more%0A%23%20details.%0A%23%0ADeviceRulesWithPort%3Dfalse%0A%0A%23%0A%23%20USBGuard%20Audit%20events%20log%20backend%0A%23%0A%23%20One%20of%3A%0A%23%0A%23%20%2A%20FileAudit%20-%20Log%20audit%20events%20into%20a%20file%20specified%20by%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20AuditFilePath%20setting%20%28see%20below%29%0A%23%20%2A%20LinuxAudit%20-%20Log%20audit%20events%20using%20the%20Linux%20Audit%0A%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20subsystem%20%28using%20audit_log_user_message%29%0A%23%0AAuditBackend%3DLinuxAudit%0A%0A%23%0A%23%20USBGuard%20audit%20events%20log%20file%20path.%0A%23%0A%23AuditFilePath%3D/var/log/usbguard/usbguard-audit.log%0A%0A%23%0A%23%20Hides%20personally%20identifiable%20information%20such%20as%20device%20serial%20numbers%20and%0A%23%20hashes%20of%20descriptors%20%28which%20include%20the%20serial%20number%29%20from%20audit%20entries.%0A%23%0A%23HidePII%3Dfalse }}
            mode: 0600
            path: /etc/usbguard/usbguard-daemon.conf
            overwrite: true

#### Rule Generate USBGuard Policy [ref]

By default USBGuard when enabled prevents access to all USB devices and this lead to inaccessible system if they use USB mouse/keyboard. To prevent this scenario, the initial policy configuration must be generated based on current connected USB devices.
Rationale: | The `usbguard` must be configured to allow connected USB devices to work properly, avoiding the system to become inaccessible.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_usbguard_generate_policy

References:

nist | CM-8(3)(a), IA-3
os-srg | SRG-OS-000378-GPOS-00163
stigref | SV-258038r1045128_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( ! ( grep -sqE "^.*\.s390x$" /proc/sys/kernel/osrelease || grep -sqE "^s390x$" /proc/sys/kernel/arch; ) && rpm --quiet -q kernel-core ); then

    if rpm --quiet -q usbguard
    then
        USBGUARD_CONF=/etc/usbguard/rules.conf
        if [ ! -f "$USBGUARD_CONF" ] || [ ! -s "$USBGUARD_CONF" ]; then
            usbguard generate-policy > $USBGUARD_CONF
            if [ ! -s "$USBGUARD_CONF" ]; then
                # make sure OVAL check doesn't fail on systems where
                # generate-policy doesn't find any USB devices (for
                # example a system might not have a USB bus)
                echo "# No USB devices found" > $USBGUARD_CONF
            fi
            # make sure it has correct permissions
            chmod 600 $USBGUARD_CONF

            SYSTEMCTL_EXEC='/usr/bin/systemctl'
            "$SYSTEMCTL_EXEC" unmask 'usbguard.service'
            "$SYSTEMCTL_EXEC" restart 'usbguard.service'
            "$SYSTEMCTL_EXEC" enable 'usbguard.service'
        fi
    else
        echo "USBGuard is not installed. No remediation was applied!"
    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:
      - DISA-STIG-RHEL-09-291030
      - NIST-800-53-CM-8(3)(a)
      - NIST-800-53-IA-3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - usbguard_generate_policy

    - name: Generate USBGuard Policy
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Check that the /etc/usbguard/rules.conf exists
        ansible.builtin.stat:
          path: /etc/usbguard/rules.conf
        register: policy_file

      - name: Create USBGuard Policy configuration
        ansible.builtin.command: usbguard generate-policy
        register: policy
        when: not policy_file.stat.exists or policy_file.stat.size == 0

      - name: Copy the Generated Policy configuration to a persistent file
        ansible.builtin.copy:
          content: '{{ policy.stdout }}'
          dest: /etc/usbguard/rules.conf
          mode: 384
        when: not policy_file.stat.exists or policy_file.stat.size == 0

      - name: Add comment into /etc/usbguard/rules.conf when system has no USB devices
        ansible.builtin.lineinfile:
          path: /etc/usbguard/rules.conf
          line: '# No USB devices found'
          state: present
        when: not policy_file.stat.exists or policy_file.stat.size == 0

      - name: Enable service usbguard
        ansible.builtin.systemd:
          name: usbguard
          enabled: 'yes'
          state: started
          masked: 'no'
      when:
      - ( ansible_architecture != "s390x" and "kernel-core" in ansible_facts.packages
        )
      - '"usbguard" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-291030
      - NIST-800-53-CM-8(3)(a)
      - NIST-800-53-IA-3
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - usbguard_generate_policy

Group X Window System Group contains 1 group and 2 rules
[ref] The X Window System implementation included with the system is called X.org.
Group Disable X Windows Group contains 2 rules

[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 Disable graphical user interface [ref]

By removing the following packages, the system no longer has X Windows installed. `xorg-x11-server-Xorg` `xorg-x11-server-common` `xorg-x11-server-utils` `xorg-x11-server-Xwayland` 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 dnf remove xorg-x11-server-Xorg xorg-x11-server-common xorg-x11-server-utils xorg-x11-server-Xwayland

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. The rule `xwindows_runlevel_target` can be used to configure the system to boot into the multi-user.target. If a GUI is an operational requirement, a tailored profile that removes this rule should be 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_xwindows_remove_packages

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
stigref | SV-257837r1044910_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    # remove packages

    if rpm -q --quiet "xorg-x11-server-Xorg" ; then
    dnf remove -y --noautoremove "xorg-x11-server-Xorg"
    fi

    if rpm -q --quiet "xorg-x11-server-common" ; then
    dnf remove -y --noautoremove "xorg-x11-server-common"
    fi

    if rpm -q --quiet "xorg-x11-server-utils" ; then
    dnf remove -y --noautoremove "xorg-x11-server-utils"
    fi

    if rpm -q --quiet "xorg-x11-server-Xwayland" ; then
    dnf remove -y --noautoremove "xorg-x11-server-Xwayland"
    fi

Remediation Anaconda snippet ⇲

    # remove packages

    package --remove=xorg-x11-server-Xorg

    package --remove=xorg-x11-server-common

    package --remove=xorg-x11-server-utils

    package --remove=xorg-x11-server-Xwayland

#### Rule Disable Graphical Environment Startup By Setting Default Target [ref]

Systems that do not require a graphical user interface should only boot by default into `multi-user.target` mode. This prevents accidental booting of the system into a `graphical.target` mode. Setting the system's default target to `multi-user.target` will prevent automatic startup of the graphical environment. To do so, run:

    $ systemctl set-default multi-user.target

You should see the following output:

    Removed symlink /etc/systemd/system/default.target.
    Created symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/multi-user.target.

Rationale: | Services that are not required for system and application processes must not be active to decrease the attack surface of the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_xwindows_runlevel_target

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
stigref | SV-257781r991589_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    systemctl set-default multi-user.target

    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:
      - DISA-STIG-RHEL-09-211030
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - xwindows_runlevel_target

    - name: Switch to multi-user runlevel
      ansible.builtin.file:
        src: /usr/lib/systemd/system/multi-user.target
        dest: /etc/systemd/system/default.target
        state: link
        force: true
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-211030
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
      - xwindows_runlevel_target

Group System Accounting with auditd Group contains 11 groups and 102 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 8 groups and 81 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 15 rules

[ref] At a minimum, the audit system should collect file permission changes for all users and root. Note that the "-F arch=b32" lines should be present even on a 64 bit system. These commands identify system calls for auditing. Even if the system is 64 bit it can still execute 32 bit system calls. Additionally, these rules can be configured in a number of ways while still achieving the desired effect. An example of this is that the "-S" calls could be split up and placed on separate lines, however, this is less efficient. Add the following to `/etc/audit/audit.rules`:

    -a always,exit -F arch=b32 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

        -a always,exit -F arch=b32 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=unset -F key=perm_mod
        -a always,exit -F arch=b32 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If your system is 64 bit then these lines should be duplicated and the arch=b32 replaced with arch=b64 as follows:

    -a always,exit -F arch=b64 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

        -a always,exit -F arch=b64 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=unset -F key=perm_mod
        -a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

#### Rule Record Events that Modify the System's Discretionary Access Controls - chmod [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_chmod

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
ism | 0582
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258177r1106368_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - chown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_chown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
ism | 0582
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258178r1106370_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchmod [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchmod

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258177r1106368_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchmodat [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchmodat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258177r1106368_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654015
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmodat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258178r1106370_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchownat [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchownat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258178r1106370_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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

    -a always,exit -F arch=b32 -S fremovexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S fremovexattr -F auid=0 -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

    -a always,exit -F arch=b32 -S fremovexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S fremovexattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fremovexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

    -a always,exit -F arch=b32 -S fsetxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S fsetxattr -F auid=0 -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

    -a always,exit -F arch=b32 -S fsetxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S fsetxattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fsetxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - lchown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lchown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258178r1106370_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654020
      - 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

    -a always,exit -F arch=b32 -S lremovexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S lremovexattr -F auid=0 -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

    -a always,exit -F arch=b32 -S lremovexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S lremovexattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lremovexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

    -a always,exit -F arch=b32 -S lsetxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S lsetxattr -F auid=0 -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

    -a always,exit -F arch=b32 -S lsetxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S lsetxattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lsetxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

    -a always,exit -F arch=b32 -S removexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S removexattr -F auid=0 -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

    -a always,exit -F arch=b32 -S removexattr -F auid=0 -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

    -a always,exit -F arch=b64 -S removexattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_removexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

    -a always,exit -F arch=b32 -S setxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S setxattr -F auid=0 -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

    -a always,exit -F arch=b32 -S setxattr -F auid=0 -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

    -a always,exit -F arch=b64 -S setxattr -F auid=0 -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_setxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000466-GPOS-00210, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235
anssi | R73
pcidss4 | 10.3.4, 10.3
bsi | SYS.1.1.A10
cis | 6.3.3.9
stigref | SV-258179r1106371_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid=0"
    	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
      - DISA-STIG-RHEL-09-654025
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - 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

      - 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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -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=0 (-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=0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and 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=0 -F
            key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654025
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_setxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - umount [ref]

At a minimum, the audit system should collect file system umount changes. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S umount -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 umount -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_umount

References:

os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258215r1106381_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    ACTION_ARCH_FILTERS="-a always,exit -F arch=b32"
    OTHER_FILTERS=""
    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="umount"
    KEY="perm_mod"
    SYSCALL_GROUPING=""

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'augenrules', then check if the audit rule is defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
    # If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
    default_file="/etc/audit/rules.d/$KEY.rules"
    # As other_filters may include paths, lets use a different delimiter for it
    # The "F" script expression tells sed to print the filenames where the expressions matched
    readarray -t files_to_inspect < <(sed -s -n -e "/^$ACTION_ARCH_FILTERS/!d" -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" -e "F" /etc/audit/rules.d/*.rules)
    # Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    if [ ${#files_to_inspect[@]} -eq "0" ]
    then
        file_to_inspect="/etc/audit/rules.d/$KEY.rules"
        files_to_inspect=("$file_to_inspect")
        if [ ! -e "$file_to_inspect" ]
        then
            touch "$file_to_inspect"
            chmod 0600 "$file_to_inspect"
        fi
    fi

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    default_file="/etc/audit/audit.rules"
    files_to_inspect+=('/etc/audit/audit.rules' )

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi

    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:
      - DISA-STIG-RHEL-09-654205
      - audit_rules_dac_modification_umount
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for umount for x86 platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount
          syscall_grouping: []

      - name: Check existence of umount 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:
          - umount
          syscall_grouping: []

      - name: Check existence of umount 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654205
      - audit_rules_dac_modification_umount
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - umount2 [ref]

At a minimum, the audit system should collect file system umount2 changes. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_umount2

References:

os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
stigref | SV-258216r1102090_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="umount2"
    	KEY="perm_mod"
    	SYSCALL_GROUPING=""

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'augenrules', then check if the audit rule is defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
    # If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
    default_file="/etc/audit/rules.d/$KEY.rules"
    # As other_filters may include paths, lets use a different delimiter for it
    # The "F" script expression tells sed to print the filenames where the expressions matched
    readarray -t files_to_inspect < <(sed -s -n -e "/^$ACTION_ARCH_FILTERS/!d" -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" -e "F" /etc/audit/rules.d/*.rules)
    # Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    if [ ${#files_to_inspect[@]} -eq "0" ]
    then
        file_to_inspect="/etc/audit/rules.d/$KEY.rules"
        files_to_inspect=("$file_to_inspect")
        if [ ! -e "$file_to_inspect" ]
        then
            touch "$file_to_inspect"
            chmod 0600 "$file_to_inspect"
        fi
    fi

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    	unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    default_file="/etc/audit/audit.rules"
    files_to_inspect+=('/etc/audit/audit.rules' )

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654210
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit umount2 tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654210
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for umount2 for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path
          :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
        loop: '{{ find_command.results | selectattr(''matched'') | list }}'

      - name: Declare files where syscalls were found
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item,
          0) }) }}"
        loop: '{{ find_command.results | map(attribute=''files'') | flatten | map(attribute=''path'')
          | list }}'

      - name: Get path with most syscalls
        ansible.builtin.set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value')
          | last).key }}"
        when: found_paths | length >= 1

      - name: No file with syscall found, set path to /etc/audit/rules.d/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: audit.rules
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Set path to /etc/audit/audit.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654210
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for umount2 for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path
          :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
        loop: '{{ find_command.results | selectattr(''matched'') | list }}'

      - name: Declare files where syscalls were found
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item,
          0) }) }}"
        loop: '{{ find_command.results | map(attribute=''files'') | flatten | map(attribute=''path'')
          | list }}'

      - name: Get path with most syscalls
        ansible.builtin.set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value')
          | last).key }}"
        when: found_paths | length >= 1

      - name: No file with syscall found, set path to /etc/audit/rules.d/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: audit.rules
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Set path to /etc/audit/audit.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654210
      - audit_rules_dac_modification_umount2
      - 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.3.3.17
stigref | SV-258181r1045328_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654035
      - audit_rules_execution_chacl
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run chacl - Perform remediation of Audit rules for
        /usr/bin/chacl
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chacl -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/chacl -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chacl -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chacl -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/chacl -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chacl -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654035
      - audit_rules_execution_chacl
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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
bsi | SYS.1.1.A10
cis | 6.3.3.16
stigref | SV-258182r1045331_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654040
      - audit_rules_execution_setfacl
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run setfacl - Perform remediation of Audit rules for
        /usr/bin/setfacl
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/setfacl -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/setfacl -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/setfacl -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/setfacl -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/setfacl -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/setfacl -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654040
      - audit_rules_execution_setfacl
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Record Execution Attempts to Run SELinux Privileged Commands Group contains 4 rules
[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
ism | 0582
bsi | SYS.1.1.A10
cis | 6.3.3.15
stigref | SV-258183r1045334_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654045
      - 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)
      - audit_rules_execution_chcon
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run chcon - Perform remediation of Audit rules for
        /usr/bin/chcon
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chcon -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/chcon -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chcon -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chcon -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chcon -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654045
      - 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)
      - audit_rules_execution_chcon
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Any Attempts to Run semanage [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/semanage -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/semanage -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_semanage

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
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.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-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
ism | 0582
stigref | SV-258184r1045337_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/semanage -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654050
      - 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)
      - audit_rules_execution_semanage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run semanage - Perform remediation of Audit rules for
        /usr/sbin/semanage
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/semanage -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/semanage -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/semanage -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/semanage -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/semanage -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654050
      - 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)
      - audit_rules_execution_semanage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Any Attempts to Run setfiles [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/setfiles -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/setfiles -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_setfiles

References:

nist | AU-2(d), AU-12(c), AC-6(9), CM-6(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-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
ism | 0582
stigref | SV-258185r1045340_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/setfiles -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654055
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - audit_rules_execution_setfiles
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run setfiles - Perform remediation of Audit rules for
        /usr/sbin/setfiles
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/setfiles -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/setfiles -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/setfiles -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/setfiles -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/setfiles -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/setfiles -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654055
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - audit_rules_execution_setfiles
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Any Attempts to Run setsebool [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/setsebool -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/setsebool -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_setsebool

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-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
ism | 0582
stigref | SV-258186r1045343_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/setsebool -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654060
      - 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)
      - audit_rules_execution_setsebool
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run setsebool - Perform remediation of Audit rules
        for /usr/sbin/setsebool
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/setsebool -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/setsebool -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/setsebool -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/setsebool -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/setsebool -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654060
      - 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)
      - audit_rules_execution_setsebool
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Record File Deletion Events by User Group contains 5 rules

[ref] At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat,renameat2 -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat,renameat2 -F auid>=1000 -F auid!=unset -F key=delete

#### Rule Ensure auditd Collects File Deletion Events by User - rename [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_rename

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2
cis | 6.3.3.13
stigref | SV-258187r1106373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rename
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - renameat [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_renameat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2
cis | 6.3.3.13
stigref | SV-258187r1106373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_renameat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - rmdir [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_rmdir

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2
stigref | SV-258187r1106373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="rmdir"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'augenrules', then check if the audit rule is defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
    # If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
    default_file="/etc/audit/rules.d/$KEY.rules"
    # As other_filters may include paths, lets use a different delimiter for it
    # The "F" script expression tells sed to print the filenames where the expressions matched
    readarray -t files_to_inspect < <(sed -s -n -e "/^$ACTION_ARCH_FILTERS/!d" -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" -e "F" /etc/audit/rules.d/*.rules)
    # Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    if [ ${#files_to_inspect[@]} -eq "0" ]
    then
        file_to_inspect="/etc/audit/rules.d/$KEY.rules"
        files_to_inspect=("$file_to_inspect")
        if [ ! -e "$file_to_inspect" ]
        then
            touch "$file_to_inspect"
            chmod 0600 "$file_to_inspect"
        fi
    fi

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    	unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    default_file="/etc/audit/audit.rules"
    files_to_inspect+=('/etc/audit/audit.rules' )

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit rmdir tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rmdir for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path
          :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
        loop: '{{ find_command.results | selectattr(''matched'') | list }}'

      - name: Declare files where syscalls were found
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item,
          0) }) }}"
        loop: '{{ find_command.results | map(attribute=''files'') | flatten | map(attribute=''path'')
          | list }}'

      - name: Get path with most syscalls
        ansible.builtin.set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value')
          | last).key }}"
        when: found_paths | length >= 1

      - name: No file with syscall found, set path to /etc/audit/rules.d/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: audit.rules
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Set path to /etc/audit/audit.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rmdir for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path
          :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
        loop: '{{ find_command.results | selectattr(''matched'') | list }}'

      - name: Declare files where syscalls were found
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item,
          0) }) }}"
        loop: '{{ find_command.results | map(attribute=''files'') | flatten | map(attribute=''path'')
          | list }}'

      - name: Get path with most syscalls
        ansible.builtin.set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value')
          | last).key }}"
        when: found_paths | length >= 1

      - name: No file with syscall found, set path to /etc/audit/rules.d/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: audit.rules
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Set path to /etc/audit/audit.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - unlink [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_unlink

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2
cis | 6.3.3.13
stigref | SV-258187r1106373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654065
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlink
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - unlinkat [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_unlinkat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2
cis | 6.3.3.13
stigref | SV-258187r1106373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654065
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654065
      - 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 6 rules

[ref] At a minimum, the audit system should collect unauthorized file accesses for all users and root. Note that the "-F arch=b32" lines should be present even on a 64 bit system. These commands identify system calls for auditing. Even if the system is 64 bit it can still execute 32 bit system calls. Additionally, these rules can be configured in a number of ways while still achieving the desired effect. An example of this is that the "-S" calls could be split up and placed on separate lines, however, this is less efficient. Add the following to `/etc/audit/audit.rules`:

    -a always,exit -F arch=b32 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
        -a always,exit -F arch=b32 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If your system is 64 bit then these lines should be duplicated and the arch=b32 replaced with arch=b64 as follows:

    -a always,exit -F arch=b64 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
        -a always,exit -F arch=b64 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

#### Rule Record Unsuccessful Access Attempts to Files - creat [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_creat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846
cis | 6.3.3.7
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - ftruncate [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_ftruncate

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846
cis | 6.3.3.7
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - open [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_open

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846
cis | 6.3.3.7
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core && { ! ( ( 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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 - open_by_handle_at [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_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open_by_handle_at -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_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S open_by_handle_at -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_by_handle_at,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open_by_handle_at,truncate,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 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 open_by_handle_at,truncate,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_open_by_handle_at

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
ism | 0582, 0846
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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_by_handle_at"
    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:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit open_by_handle_at tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open_by_handle_at EACCES for 32bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open_by_handle_at EACCES for 64bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open_by_handle_at EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open_by_handle_at EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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_by_handle_at
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open_by_handle_at 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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_by_handle_at
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - openat [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_openat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846
cis | 6.3.3.7
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - truncate [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_truncate

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846
cis | 6.3.3.7
stigref | SV-258188r1106375_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654070
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654070
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

Group Record Information on Kernel Modules Loading and Unloading Group contains 3 rules

[ref] To capture kernel module loading and unloading events, use following lines, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S init_module,delete_module -F key=modules

Place to add the lines depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the lines to file `/etc/audit/audit.rules`.

#### Rule Ensure auditd Collects Information on Kernel Module Unloading - delete_module [ref]

To capture kernel module loading and unloading events, use the following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S delete_module -F auid>=1000 -F auid!=unset -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.3.3.19
stigref | SV-258189r1106377_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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="-F auid>=1000 -F auid!=unset"

    	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:
      - DISA-STIG-RHEL-09-654075
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654075
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654075
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654075
      - 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 auid>=1000 -F auid!=unset -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.3.3.19
stigref | SV-258190r1106379_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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="-F auid>=1000 -F auid!=unset"

    	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:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654080
      - 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 auid>=1000 -F auid!=unset -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.3.3.19
stigref | SV-258190r1106379_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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="-F auid>=1000 -F auid!=unset"

    	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:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654080
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - DISA-STIG-RHEL-09-654080
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_init
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Record Attempts to Alter Logon and Logout Events Group contains 3 rules

[ref] The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to watch for attempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/log/faillock -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file in order to watch for unattempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/log/faillock -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

#### Rule Record Attempts to Alter Logon and Logout Events - faillock [ref]

The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/faillock -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/faillock -p wa -k logins

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_login_events_faillock

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.3
os-srg | SRG-OS-000392-GPOS-00172, SRG-OS-000470-GPOS-00214, SRG-OS-000473-GPOS-00218
app-srg-ctr | SRG-APP-000503-CTR-001275, SRG-APP-000506-CTR-001290
anssi | R73
ism | 0582
pcidss4 | 10.2.1.3, 10.2.1, 10.2
bsi | SYS.1.1.A10
cis | 6.3.3.12
stigref | SV-258224r1014988_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    var_accounts_passwords_pam_faillock_dir='/var/log/faillock'

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    # Tool used to load audit rules	| Rule already defined	|  Audit rules file to inspect	  |
    # -----------------------------------------------------------------------------------------
    #	auditctl		|     Doesn't matter	|  /etc/audit/audit.rules	  |
    # -----------------------------------------------------------------------------------------
    # 	augenrules		|          Yes		|  /etc/audit/rules.d/*.rules	  |
    # 	augenrules		|          No		|  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    files_to_inspect=()

    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    files_to_inspect+=('/etc/audit/audit.rules')

    # Finally perform the inspection and possible subsequent audit rule
    # correction for each of the files previously identified for inspection
    for audit_rules_file in "${files_to_inspect[@]}"
    do
        # Check if audit watch file system object rule for given path already present

        if grep -q -P -- "^[\s]*-w[\s]+${var_accounts_passwords_pam_faillock_dir}" "$audit_rules_file"

        then
            # Rule is found => verify yet if existing rule definition contains
            # all of the required access type bits

            # Define BRE whitespace class shortcut
            sp="[[:space:]]"
            # Extract current permission access types (e.g. -p [r|w|x|a] values) from audit rule

            current_access_bits=$(sed -ne "s#$sp*-w$sp\+${var_accounts_passwords_pam_faillock_dir} $sp\+-p$sp\+\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")

            # Split required access bits string into characters array
            # (to check bit's presence for one bit at a time)
            for access_bit in $(echo "wa" | grep -o .)
            do
                # For each from the required access bits (e.g. 'w', 'a') check
                # if they are already present in current access bits for rule.
                # If not, append that bit at the end
                if ! grep -q "$access_bit" <<< "$current_access_bits"
                then
                    # Concatenate the existing mask with the missing bit
                    current_access_bits="$current_access_bits$access_bit"
                fi
            done
            # Propagate the updated rule's access bits (original + the required
            # ones) back into the /etc/audit/audit.rules file for that rule

            sed -i "s#\($sp*-w$sp\+${var_accounts_passwords_pam_faillock_dir}$sp\+-p$sp\+\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"

        else
            # Rule isn't present yet. Append it at the end of $audit_rules_file file
            # with proper key

            echo "-w ${var_accounts_passwords_pam_faillock_dir} -p wa -k logins" >> "$audit_rules_file"

        fi
    done
    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    # Tool used to load audit rules	| Rule already defined	|  Audit rules file to inspect	  |
    # -----------------------------------------------------------------------------------------
    #	auditctl		|     Doesn't matter	|  /etc/audit/audit.rules	  |
    # -----------------------------------------------------------------------------------------
    # 	augenrules		|          Yes		|  /etc/audit/rules.d/*.rules	  |
    # 	augenrules		|          No		|  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    files_to_inspect=()

    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/logins.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+${var_accounts_passwords_pam_faillock_dir}" /etc/audit/rules.d/*.rules)

    # For each of the matched entries
    for match in "${matches[@]}"
    do
        # Extract filepath from the match
        rulesd_audit_file=$(echo $match | cut -f1 -d ':')
        # Append that path into list of files for inspection
        files_to_inspect+=("$rulesd_audit_file")
    done
    # Case when particular audit rule isn't defined yet
    if [ "${#files_to_inspect[@]}" -eq "0" ]
    then
        # Append '/etc/audit/rules.d/logins.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/logins.rules"
        # If the logins.rules file doesn't exist yet, create it with correct permissions
        if [ ! -e "$key_rule_file" ]
        then
            touch "$key_rule_file"
            chmod 0600 "$key_rule_file"
        fi
        files_to_inspect+=("$key_rule_file")
    fi

    # Finally perform the inspection and possible subsequent audit rule
    # correction for each of the files previously identified for inspection
    for audit_rules_file in "${files_to_inspect[@]}"
    do
        # Check if audit watch file system object rule for given path already present

        if grep -q -P -- "^[\s]*-w[\s]+${var_accounts_passwords_pam_faillock_dir}" "$audit_rules_file"

        then
            # Rule is found => verify yet if existing rule definition contains
            # all of the required access type bits

            # Define BRE whitespace class shortcut
            sp="[[:space:]]"
            # Extract current permission access types (e.g. -p [r|w|x|a] values) from audit rule

            current_access_bits=$(sed -ne "s#$sp*-w$sp\+${var_accounts_passwords_pam_faillock_dir} $sp\+-p$sp\+\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")

            # Split required access bits string into characters array
            # (to check bit's presence for one bit at a time)
            for access_bit in $(echo "wa" | grep -o .)
            do
                # For each from the required access bits (e.g. 'w', 'a') check
                # if they are already present in current access bits for rule.
                # If not, append that bit at the end
                if ! grep -q "$access_bit" <<< "$current_access_bits"
                then
                    # Concatenate the existing mask with the missing bit
                    current_access_bits="$current_access_bits$access_bit"
                fi
            done
            # Propagate the updated rule's access bits (original + the required
            # ones) back into the /etc/audit/audit.rules file for that rule

            sed -i "s#\($sp*-w$sp\+${var_accounts_passwords_pam_faillock_dir}$sp\+-p$sp\+\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"

        else
            # Rule isn't present yet. Append it at the end of $audit_rules_file file
            # with proper key

            echo "-w ${var_accounts_passwords_pam_faillock_dir} -p wa -k logins" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654250
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_passwords_pam_faillock_dir # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_dir: !!str /var/log/faillock
      tags:
        - always

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Check if watch
        rule for {{ var_accounts_passwords_pam_faillock_dir }} already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+{{ var_accounts_passwords_pam_faillock_dir }}\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654250
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654250
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Logon and Logout Events - lastlog [ref]

The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/lastlog -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/lastlog -p wa -k logins

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_login_events_lastlog

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.3
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000473-GPOS-00218, SRG-OS-000470-GPOS-00214
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000503-CTR-001275, SRG-APP-000506-CTR-001290
anssi | R73
ism | 0582
pcidss4 | 10.2.1.3, 10.2.1, 10.2
bsi | SYS.1.1.A10
cis | 6.3.3.12
stigref | SV-258225r1014990_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654255
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654255
      - 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

#### Rule Record Attempts to Alter Logon and Logout Events - tallylog [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/tallylog -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/tallylog -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_tallylog

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
ism | 0582
pcidss4 | 10.2.1.3, 10.2.1, 10.2
stigref | SV-258226r958846_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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/tallylog" "$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/tallylog $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/tallylog$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/tallylog -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/tallylog" /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/tallylog" "$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/tallylog $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/tallylog$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/tallylog -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:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - Check if watch
        rule for /var/log/tallylog already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/log/tallylog\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - Add watch rule
        for /var/log/tallylog in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/log/tallylog -p wa -k logins
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - Check if watch
        rule for /var/log/tallylog already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/log/tallylog\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - tallylog - Add watch rule
        for /var/log/tallylog in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/log/tallylog -p wa -k logins
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654260
      - 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_tallylog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Record Information on the Use of Privileged Commands Group contains 25 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 - init [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/init -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/init -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged

Rationale: | Misuse of the init command may cause availability issues for the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_privileged_commands_init

References:

nist | AU-12(c)
os-srg | SRG-OS-000477-GPOS-00222
stigref | SV-258211r1045418_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/init -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654185
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - init
        - Perform remediation of Audit rules for /usr/sbin/init
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/init -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/init -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/init -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/init -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/init -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/init -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654185
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_init
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - poweroff [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/poweroff -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/poweroff -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged

Rationale: | Misuse of the poweroff command may cause availability issues for the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_privileged_commands_poweroff

References:

nist | AU-12(c)
os-srg | SRG-OS-000477-GPOS-00222
stigref | SV-258212r1045421_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/poweroff -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654190
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_poweroff
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - poweroff
        - Perform remediation of Audit rules for /usr/sbin/poweroff
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/poweroff -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/poweroff -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/poweroff -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/poweroff -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/poweroff -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/poweroff -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654190
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_poweroff
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - reboot [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/reboot -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/reboot -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged

Rationale: | Misuse of the reboot command may cause availability issues for the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_privileged_commands_reboot

References:

nist | AU-12(c)
os-srg | SRG-OS-000477-GPOS-00222
stigref | SV-258213r1045424_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/reboot -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654195
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_reboot
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - reboot
        - Perform remediation of Audit rules for /usr/sbin/reboot
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/reboot -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/reboot -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/reboot -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/reboot -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/reboot -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/reboot -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654195
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_reboot
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - shutdown [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/shutdown -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/shutdown -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged

Rationale: | Misuse of the shutdown command may cause availability issues for the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_privileged_commands_shutdown

References:

nist | AU-12(c)
os-srg | SRG-OS-000477-GPOS-00222
stigref | SV-258214r1045427_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/shutdown -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654200
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - shutdown
        - Perform remediation of Audit rules for /usr/sbin/shutdown
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/shutdown -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/shutdown -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/shutdown -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/shutdown -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/shutdown -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/shutdown -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654200
      - NIST-800-53-AU-12(c)
      - audit_privileged_commands_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - chage [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/chage -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/chage -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_chage

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
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.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
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
stigref | SV-258191r1045358_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/chage -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654085
      - 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)
      - audit_rules_privileged_commands_chage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - chage
        - Perform remediation of Audit rules for /usr/bin/chage
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chage -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/chage -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chage -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chage -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chage -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654085
      - 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)
      - audit_rules_privileged_commands_chage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - chsh [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/chsh -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/chsh -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_chsh

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
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.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258192r1045361_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/chsh -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654090
      - 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)
      - audit_rules_privileged_commands_chsh
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - chsh
        - Perform remediation of Audit rules for /usr/bin/chsh
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chsh -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/chsh -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chsh -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/chsh -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/chsh -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654090
      - 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)
      - audit_rules_privileged_commands_chsh
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - crontab [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/crontab -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/crontab -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_crontab

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258193r1045364_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/crontab -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654095
      - 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)
      - audit_rules_privileged_commands_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - crontab
        - Perform remediation of Audit rules for /usr/bin/crontab
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/crontab -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/crontab -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/crontab -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/crontab -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/crontab -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654095
      - 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)
      - audit_rules_privileged_commands_crontab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - gpasswd [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/gpasswd -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/gpasswd -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_gpasswd

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
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.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258194r1045367_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/gpasswd -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654100
      - 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)
      - audit_rules_privileged_commands_gpasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - gpasswd
        - Perform remediation of Audit rules for /usr/bin/gpasswd
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/gpasswd -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/gpasswd -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/gpasswd -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/gpasswd -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/gpasswd -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654100
      - 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)
      - audit_rules_privileged_commands_gpasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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.3.3.19
stigref | SV-258195r1045370_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654105
      - NIST-800-53-AU-12(a)
      - NIST-800-53-AU-12.1(ii)
      - NIST-800-53-AU-12.1(iv)AU-12(c)
      - NIST-800-53-AU-3
      - NIST-800-53-AU-3.1
      - NIST-800-53-MA-4(1)(a)
      - audit_rules_privileged_commands_kmod
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - kmod
        - Perform remediation of Audit rules for /usr/bin/kmod
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/kmod -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/kmod -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/kmod -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/kmod -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/kmod -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/kmod -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654105
      - NIST-800-53-AU-12(a)
      - NIST-800-53-AU-12.1(ii)
      - NIST-800-53-AU-12.1(iv)AU-12(c)
      - NIST-800-53-AU-3
      - NIST-800-53-AU-3.1
      - NIST-800-53-MA-4(1)(a)
      - audit_rules_privileged_commands_kmod
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - mount [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/mount -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/mount -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_mount

References:

nist | AU-2(d), AU-12(c), AC-6(9), CM-6(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
app-srg-ctr | SRG-APP-000029-CTR-000085
stigref | SV-258210r1045415_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/mount -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654180
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - audit_rules_privileged_commands_mount
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - mount
        - Perform remediation of Audit rules for /usr/bin/mount
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/mount -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/mount -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/mount -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/mount -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/mount -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/mount -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654180
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - audit_rules_privileged_commands_mount
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - newgrp [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/newgrp -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/newgrp -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_newgrp

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
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.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258196r1045373_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/newgrp -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654110
      - 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)
      - audit_rules_privileged_commands_newgrp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - newgrp
        - Perform remediation of Audit rules for /usr/bin/newgrp
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/newgrp -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/newgrp -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/newgrp -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/newgrp -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/newgrp -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654110
      - 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)
      - audit_rules_privileged_commands_newgrp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - pam_timestamp_check [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/pam_timestamp_check -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/pam_timestamp_check -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_pam_timestamp_check

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258197r1045376_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/pam_timestamp_check -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654115
      - 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)
      - audit_rules_privileged_commands_pam_timestamp_check
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - pam_timestamp_check
        - Perform remediation of Audit rules for /usr/sbin/pam_timestamp_check
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/pam_timestamp_check -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/pam_timestamp_check
            -F perm=x -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/pam_timestamp_check
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/pam_timestamp_check -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/pam_timestamp_check -F perm=x -F auid>=1000
            -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/pam_timestamp_check
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654115
      - 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)
      - audit_rules_privileged_commands_pam_timestamp_check
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - passwd [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/passwd -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/passwd -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_passwd

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
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.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258198r1045379_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/passwd -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654120
      - 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)
      - audit_rules_privileged_commands_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - passwd
        - Perform remediation of Audit rules for /usr/bin/passwd
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/passwd -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/passwd -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/passwd -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/passwd -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/passwd -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654120
      - 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)
      - audit_rules_privileged_commands_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - postdrop [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/postdrop -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/postdrop -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_postdrop

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258199r1045382_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/postdrop -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654125
      - 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)
      - audit_rules_privileged_commands_postdrop
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - postdrop
        - Perform remediation of Audit rules for /usr/sbin/postdrop
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/postdrop -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/postdrop -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/postdrop -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/postdrop -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/postdrop -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/postdrop -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654125
      - 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)
      - audit_rules_privileged_commands_postdrop
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - postqueue [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/postqueue -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/postqueue -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_postqueue

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258200r1045385_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/postqueue -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654130
      - 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)
      - audit_rules_privileged_commands_postqueue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - postqueue
        - Perform remediation of Audit rules for /usr/sbin/postqueue
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/postqueue -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/postqueue -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/postqueue -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/postqueue -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/postqueue -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/postqueue -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654130
      - 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)
      - audit_rules_privileged_commands_postqueue
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Any Attempts to Run ssh-agent [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/ssh-agent -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/ssh-agent -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_ssh_agent

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
stigref | SV-258201r1045388_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/ssh-agent -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654135
      - audit_rules_privileged_commands_ssh_agent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Any Attempts to Run ssh-agent - Perform remediation of Audit rules
        for /usr/bin/ssh-agent
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/ssh-agent -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/ssh-agent -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/ssh-agent -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/ssh-agent -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/ssh-agent -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/ssh-agent -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654135
      - audit_rules_privileged_commands_ssh_agent
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - ssh-keysign [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/libexec/openssh/ssh-keysign -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/libexec/openssh/ssh-keysign -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_ssh_keysign

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258202r1045391_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/libexec/openssh/ssh-keysign -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654140
      - 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)
      - audit_rules_privileged_commands_ssh_keysign
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - ssh-keysign
        - Perform remediation of Audit rules for /usr/libexec/openssh/ssh-keysign
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/libexec/openssh/ssh-keysign -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/libexec/openssh/ssh-keysign
            -F perm=x -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/libexec/openssh/ssh-keysign
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/libexec/openssh/ssh-keysign -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/libexec/openssh/ssh-keysign -F perm=x -F auid>=1000
            -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/libexec/openssh/ssh-keysign
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654140
      - 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)
      - audit_rules_privileged_commands_ssh_keysign
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - su [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/su -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/su -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_su

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-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000755-GPOS-00220
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
stigref | SV-258203r1045394_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/su -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654145
      - 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)
      - audit_rules_privileged_commands_su
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - su
        - Perform remediation of Audit rules for /usr/bin/su
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/su -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/su -F perm=x -F auid>=1000
            -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/su -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/su -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/su -F perm=x -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/su -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654145
      - 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)
      - audit_rules_privileged_commands_su
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - sudo [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F path=/usr/bin/sudo -F 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/sudo -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_sudo

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000755-GPOS-00220
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R33
stigref | SV-258204r1045397_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/sudo -F perm=x"
    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL=""
    KEY="privileged"
    SYSCALL_GROUPING=""

    ACTION_ARCH_FILTERS="-a always,exit"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'augenrules', then check if the audit rule is defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
    # If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
    default_file="/etc/audit/rules.d/$KEY.rules"
    # As other_filters may include paths, lets use a different delimiter for it
    # The "F" script expression tells sed to print the filenames where the expressions matched
    readarray -t files_to_inspect < <(sed -s -n -e "/^$ACTION_ARCH_FILTERS/!d" -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" -e "F" /etc/audit/rules.d/*.rules)
    # Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    if [ ${#files_to_inspect[@]} -eq "0" ]
    then
        file_to_inspect="/etc/audit/rules.d/$KEY.rules"
        files_to_inspect=("$file_to_inspect")
        if [ ! -e "$file_to_inspect" ]
        then
            touch "$file_to_inspect"
            chmod 0600 "$file_to_inspect"
        fi
    fi

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi
    unset syscall_a
    unset syscall_grouping
    unset syscall_string
    unset syscall
    unset file_to_edit
    unset rule_to_edit
    unset rule_syscalls_to_edit
    unset other_string
    unset auid_string
    unset full_rule

    # Load macro arguments into arrays
    read -a syscall_a <<< $SYSCALL
    read -a syscall_grouping <<< $SYSCALL_GROUPING

    # Create a list of audit *.rules files that should be inspected for presence and correctness
    # of a particular audit rule. The scheme is as follows:
    #
    # -----------------------------------------------------------------------------------------
    #  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
    # -----------------------------------------------------------------------------------------
    #        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
    # -----------------------------------------------------------------------------------------
    #        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
    #        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
    # -----------------------------------------------------------------------------------------
    #
    files_to_inspect=()

    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    default_file="/etc/audit/audit.rules"
    files_to_inspect+=('/etc/audit/audit.rules' )

    # After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
    skip=1

    for audit_file in "${files_to_inspect[@]}"
    do
        # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
        # i.e, collect rules that match:
        # * the action, list and arch, (2-nd argument)
        # * the other filters, (3-rd argument)
        # * the auid filters, (4-rd argument)
        readarray -t similar_rules < <(sed -e "/^$ACTION_ARCH_FILTERS/!d"  -e "\#$OTHER_FILTERS#!d" -e "/$AUID_FILTERS/!d" "$audit_file")

        candidate_rules=()
        # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
        for s_rule in "${similar_rules[@]}"
        do
            # Strip all the options and fields we know of,
            # than check if there was any field left over
            extra_fields=$(sed -E -e "s/^$ACTION_ARCH_FILTERS//"  -e "s#$OTHER_FILTERS##" -e "s/$AUID_FILTERS//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
            grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
        done

        if [[ ${#syscall_a[@]} -ge 1 ]]
        then
            # Check if the syscall we want is present in any of the similar existing rules
            for rule in "${candidate_rules[@]}"
            do
                rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
                all_syscalls_found=0
                for syscall in "${syscall_a[@]}"
                do
                    grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                       # A syscall was not found in the candidate rule
                       all_syscalls_found=1
                       }
                done
                if [[ $all_syscalls_found -eq 0 ]]
                then
                    # We found a rule with all the syscall(s) we want; skip rest of macro
                    skip=0
                    break
                fi

                # Check if this rule can be grouped with our target syscall and keep track of it
                for syscall_g in "${syscall_grouping[@]}"
                do
                    if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                    then
                        file_to_edit=${audit_file}
                        rule_to_edit=${rule}
                        rule_syscalls_to_edit=${rule_syscalls}
                    fi
                done
            done
        else
            # If there is any candidate rule, it is compliant; skip rest of macro
            if [ "${#candidate_rules[@]}" -gt 0 ]
            then
                skip=0
            fi
        fi

        if [ "$skip" -eq 0 ]; then
            break
        fi
    done

    if [ "$skip" -ne 0 ]; then
        # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
        # At this point we know if we need to either append the $full_rule or group
        # the syscall together with an exsiting rule

        # Append the full_rule if it cannot be grouped to any other rule
        if [ -z ${rule_to_edit+x} ]
        then
            # Build full_rule while avoid adding double spaces when other_filters is empty
            if [ "${#syscall_a[@]}" -gt 0 ]
            then
                syscall_string=""
                for syscall in "${syscall_a[@]}"
                do
                    syscall_string+=" -S $syscall"
                done
            fi
            other_string=$([[ $OTHER_FILTERS ]] && echo " $OTHER_FILTERS") || /bin/true
            auid_string=$([[ $AUID_FILTERS ]] && echo " $AUID_FILTERS") || /bin/true
            full_rule="$ACTION_ARCH_FILTERS${syscall_string}${other_string}${auid_string} -F key=$KEY" || /bin/true
            echo "$full_rule" >> "$default_file"
            chmod 0600 ${default_file}
        else
            # Check if the syscalls are declared as a comma separated list or
            # as multiple -S parameters
            if grep -q -- "," <<< "${rule_syscalls_to_edit}"
            then
                delimiter=","
            else
                delimiter=" -S "
            fi
            new_grouped_syscalls="${rule_syscalls_to_edit}"
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
                   # A syscall was not found in the candidate rule
                   new_grouped_syscalls+="${delimiter}${syscall}"
                   }
            done

            # Group the syscall in the rule
            sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
        fi
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654150
      - 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)
      - audit_rules_privileged_commands_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - sudo
        - Perform remediation of Audit rules for /usr/bin/sudo
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/sudo -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/sudo -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/sudo -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/sudo -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/sudo -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654150
      - 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)
      - audit_rules_privileged_commands_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - sudoedit [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/sudoedit -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/sudoedit -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_sudoedit

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000755-GPOS-00220
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258205r1045400_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/sudoedit -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654155
      - 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)
      - audit_rules_privileged_commands_sudoedit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - sudoedit
        - Perform remediation of Audit rules for /usr/bin/sudoedit
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/sudoedit -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/sudoedit -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/sudoedit -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/sudoedit -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/sudoedit -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654155
      - 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)
      - audit_rules_privileged_commands_sudoedit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - umount [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/umount -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/umount -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_umount

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085
stigref | SV-258180r1045325_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/umount -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654030
      - 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)
      - audit_rules_privileged_commands_umount
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - umount
        - Perform remediation of Audit rules for /usr/bin/umount
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/umount -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/bin/umount -F perm=x -F
            auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/umount -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/bin/umount -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/bin/umount -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/bin/umount -F perm=x
            -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654030
      - 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)
      - audit_rules_privileged_commands_umount
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - unix_chkpwd [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=/sbin/unix_chkpwd -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=/sbin/unix_chkpwd -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_unix_chkpwd

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
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, CIP-007-3 R6.5
nist | AC-2(4), AU-2(d), AU-3, AU-3.1, AU-12(a), AU-12(c), AU-12.1(ii), AU-12.1(iv), AC-6(9), CM-6(a), MA-4(1)(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235
stigref | SV-258206r1045403_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/unix_chkpwd -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654160
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(a)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(ii)
      - NIST-800-53-AU-12.1(iv)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-AU-3
      - NIST-800-53-AU-3.1
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(1)(a)
      - audit_rules_privileged_commands_unix_chkpwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - unix_chkpwd
        - Perform remediation of Audit rules for /usr/sbin/unix_chkpwd
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/unix_chkpwd -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/unix_chkpwd -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/unix_chkpwd
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/unix_chkpwd -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/unix_chkpwd
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654160
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(a)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(ii)
      - NIST-800-53-AU-12.1(iv)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-AU-3
      - NIST-800-53-AU-3.1
      - NIST-800-53-CM-6(a)
      - NIST-800-53-MA-4(1)(a)
      - audit_rules_privileged_commands_unix_chkpwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - unix_update [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/unix_update -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/unix_update -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_unix_update

References:

os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258207r1045406_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/unix_update -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654165
      - audit_rules_privileged_commands_unix_update
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - unix_update
        - Perform remediation of Audit rules for /usr/sbin/unix_update
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/unix_update -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/unix_update -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/unix_update
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/unix_update -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/unix_update -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/unix_update
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654165
      - audit_rules_privileged_commands_unix_update
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - userhelper [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/userhelper -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/userhelper -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_userhelper

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
stigref | SV-258208r1045409_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/sbin/userhelper -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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654170
      - 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)
      - audit_rules_privileged_commands_userhelper
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - userhelper
        - Perform remediation of Audit rules for /usr/sbin/userhelper
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/userhelper -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/userhelper -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/userhelper
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/userhelper -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/userhelper -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/userhelper
            -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654170
      - 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)
      - audit_rules_privileged_commands_userhelper
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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
bsi | SYS.1.1.A10
cis | 6.3.3.18
stigref | SV-258209r1045412_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-654175
      - audit_rules_privileged_commands_usermod
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - usermod
        - Perform remediation of Audit rules for /usr/sbin/usermod
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/usermod -F perm=x -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/privileged.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/privileged.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)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F path=/usr/sbin/usermod -F perm=x
            -F auid>=1000 -F auid!=unset (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/usermod -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls: []
          syscall_grouping: []

      - name: Check existence of  in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)* -F
            path=/usr/sbin/usermod -F perm=x -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)(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:(
            -S |,)\w+)+)( -F path=/usr/sbin/usermod -F perm=x -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          state: present
          mode: g-rwx,o-rwx
        when: syscalls_found | length > 0 and missing_syscalls | length > 0

      - name: Add the audit rule to {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit{{ syscalls | join(',') }} -F path=/usr/sbin/usermod -F
            perm=x -F auid>=1000 -F auid!=unset -F key=privileged
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654175
      - audit_rules_privileged_commands_usermod
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ [ref]

At a minimum, the audit system should collect administrator actions 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 /etc/cron.d/ -p wa -k cronjobs

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/cron.d/ -p wa -k cronjobs

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. Editing the sudoers file may be sign of an attacker trying to establish persistent methods to a system, auditing the editing of the sudoers files mitigates this risk.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_etc_cron_d

References:

os-srg | SRG-OS-000471-GPOS-00215
stigref | SV-274878r1120758_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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/cron.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/cron.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/cron.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/cron.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/cron.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/cron.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/cron.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/cron.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/cron.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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - Check if watch
        rule for /etc/cron.d/ already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/cron.d/\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - Add watch rule
        for /etc/cron.d/ in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/cron.d/ -p wa -k actions
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - Check if watch
        rule for /etc/cron.d/ already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/cron.d/\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /etc/cron.d/ - Add watch rule
        for /etc/cron.d/ in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/cron.d/ -p wa -k actions
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_etc_cron_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Make the auditd Configuration Immutable [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to make the auditd configuration immutable:

    -e 2

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file in order to make the auditd configuration immutable:

    -e 2

With this setting, a reboot will be required to change any audit rules.

Rationale: | Making the audit configuration immutable prevents accidental as well as malicious modification of the audit rules, although it may be problematic if legitimate changes are needed during system operation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_immutable

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO01.06, APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.3.1, 3.4.3
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.310(a)(2)(iv), 164.312(d), 164.310(d)(2)(iii), 164.312(b), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.7.3, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 5.2, SR 6.1
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, ID.SC-4, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.5.2
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029
app-srg-ctr | SRG-APP-000119-CTR-000245, SRG-APP-000120-CTR-000250
anssi | R73
pcidss4 | 10.3.2, 10.3
cis | 6.3.3.20
stigref | SV-258229r958434_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - item.stat.exists
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654275
      - 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

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,-e%202%0A
            mode: 0600
            path: /etc/audit/rules.d/90-immutable.rules
            overwrite: true

#### Rule Ensure auditd Collects System Administrator Actions - /etc/sudoers [ref]

At a minimum, the audit system should collect administrator actions 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 /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

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. Editing the sudoers file may be sign of an attacker trying to establish persistent methods to a system, auditing the editing of the sudoers files mitigates this risk.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_sudoers

References:

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
stigref | SV-258217r1045436_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    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:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654215
      - audit_rules_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ [ref]

At a minimum, the audit system should collect administrator actions 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 /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. Editing the sudoers file may be sign of an attacker trying to establish persistent methods to a system, auditing the editing of the sudoers files mitigates this risk.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_sudoers_d

References:

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
stigref | SV-258218r1101981_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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.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:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - /etc/sudoers.d/ - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654220
      - audit_rules_sudoers_d
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events When Privileged Executables Are Run [ref]

Verify the system generates an audit record when privileged functions are executed. 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 uid!=euid -F euid=0 -k setuid

    -a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -k setuid

    -a always,exit -F arch=b32 -S execve -C gid!=egid -F egid=0 -k setgid

    -a always,exit -F arch=b64 -S execve -C gid!=egid -F egid=0 -k setgid

If both the "b32" and "b64" audit rules for "SUID" files are not defined, this is a finding. If both the "b32" and "b64" audit rules for "SGID" 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:

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_privilege_function

References:

nist | CM-5(1), AU-7(a), AU-7(b), AU-8(b), AU-12(3), AC-6(9)
os-srg | SRG-OS-000326-GPOS-00126, SRG-OS-000327-GPOS-00127, SRG-OS-000755-GPOS-00220
app-srg-ctr | SRG-APP-000343-CTR-000780, SRG-APP-000381-CTR-000905
pcidss4 | 10.2.1.2, 10.2.1, 10.2
stigref | SV-258176r1106366_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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 uid!=euid -F euid=0"

    	AUID_FILTERS=""
    	SYSCALL="execve"

    	KEY="setuid"

    	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

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"

    	OTHER_FILTERS="-C gid!=egid -F egid=0"

    	AUID_FILTERS=""
    	SYSCALL="execve"

    	KEY="setgid"

    	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:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Service facts
      ansible.builtin.service_facts: null
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set suid_audit_rules fact
      ansible.builtin.set_fact:
        suid_audit_rules:
        - rule: -a always,exit -F arch=b32 -S execve -C gid!=egid -F egid=0 -k setgid
          regex: ^[\s]*-a[\s]+always,exit[\s]+-F[\s]+arch=b32[\s]+-S[\s]+execve[\s]+-C[\s]+gid!=egid[\s]+-F[\s]+egid=0[\s]+(?:-k[\s]+|-F[\s]+key=)[\S]+[\s]*$
        - rule: -a always,exit -F arch=b64 -S execve -C gid!=egid -F egid=0 -k setgid
          regex: ^[\s]*-a[\s]+always,exit[\s]+-F[\s]+arch=b64[\s]+-S[\s]+execve[\s]+-C[\s]+gid!=egid[\s]+-F[\s]+egid=0[\s]+(?:-k[\s]+|-F[\s]+key=)[\S]+[\s]*$
        - rule: -a always,exit -F arch=b32 -S execve -C uid!=euid -F euid=0 -k setuid
          regex: ^[\s]*-a[\s]+always,exit[\s]+-F[\s]+arch=b32[\s]+-S[\s]+execve[\s]+-C[\s]+uid!=euid[\s]+-F[\s]+euid=0[\s]+(?:-k[\s]+|-F[\s]+key=)[\S]+[\s]*$
        - rule: -a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -k setuid
          regex: ^[\s]*-a[\s]+always,exit[\s]+-F[\s]+arch=b64[\s]+-S[\s]+execve[\s]+-C[\s]+uid!=euid[\s]+-F[\s]+euid=0[\s]+(?:-k[\s]+|-F[\s]+key=)[\S]+[\s]*$
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Update /etc/audit/rules.d/privileged.rules to audit privileged functions
      ansible.builtin.lineinfile:
        path: /etc/audit/rules.d/privileged.rules
        line: '{{  item.rule  }}'
        regexp: '{{ item.regex }}'
        mode: '0600'
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - ('"auditd.service" in ansible_facts.services' or '"augenrules.service" in ansible_facts.services')
      register: augenrules_audit_rules_privilege_function_update_result
      with_items: '{{ suid_audit_rules }}'
      tags:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Update /etc/audit/audit.rules to audit privileged functions
      ansible.builtin.lineinfile:
        path: /etc/audit/audit.rules
        line: '{{  item.rule  }}'
        regexp: '{{ item.regex }}'
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - ('"auditd.service" in ansible_facts.services' or '"augenrules.service" in ansible_facts.services')
      register: auditctl_audit_rules_privilege_function_update_result
      with_items: '{{ suid_audit_rules }}'
      tags:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Restart Auditd
      ansible.builtin.command: /usr/sbin/service auditd restart
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - (augenrules_audit_rules_privilege_function_update_result.changed or auditctl_audit_rules_privilege_function_update_result.changed)
      - ansible_facts.services["auditd.service"].state == "running"
      tags:
      - DISA-STIG-RHEL-09-654010
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(3)
      - NIST-800-53-AU-7(a)
      - NIST-800-53-AU-7(b)
      - NIST-800-53-AU-8(b)
      - NIST-800-53-CM-5(1)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.2
      - audit_rules_suid_privilege_function
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ -a%20always%2Cexit%20-F%20arch%3Db32%20-S%20execve%20-C%20uid%21%3Deuid%20-F%20euid%3D0%20-k%20execpriv%0A-a%20always%2Cexit%20-F%20arch%3Db64%20-S%20execve%20-C%20uid%21%3Deuid%20-F%20euid%3D0%20-k%20execpriv%0A-a%20always%2Cexit%20-F%20arch%3Db32%20-S%20execve%20-C%20gid%21%3Degid%20-F%20egid%3D0%20-k%20execpriv%0A-a%20always%2Cexit%20-F%20arch%3Db64%20-S%20execve%20-C%20gid%21%3Degid%20-F%20egid%3D0%20-k%20execpriv%0A }}
            mode: 0600
            path: /etc/audit/rules.d/75-audit-suid-privilege-function.rules
            overwrite: true

#### Rule Shutdown System When Auditing Failures Occur [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 to the bottom of a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -f 2

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to the bottom of the `/etc/audit/audit.rules` file:

    -f 2

Rationale:

It is critical for the appropriate personnel to be aware if a system is at risk of failing to process audit logs as required. Without this notification, the security personnel may be unaware of an impending failure of the audit capability, and system operation may be adversely affected.
Audit processing failures include software/hardware errors, failures in the audit capturing mechanisms, and audit storage capacity being reached or exceeded.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_system_shutdown

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
cui | 3.3.1, 3.3.4
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.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 | AU-5(b), SC-24, CM-6(a)
nist-csf | PR.PT-1
os-srg | SRG-OS-000046-GPOS-00022, SRG-OS-000047-GPOS-00023
stigref | SV-258227r1014992_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_audit_failure_mode='2'

    # Traverse all of:
    #
    # /etc/audit/audit.rules,			(for auditctl case)
    # /etc/audit/rules.d/*.rules			(for augenrules case)
    find /etc/audit /etc/audit/rules.d -maxdepth 1 -type f -name '*.rules' -exec sed -i '/-f[[:space:]]\+.*/d' {} ';'

    for AUDIT_FILE in "/etc/audit/audit.rules" "/etc/audit/rules.d/immutable.rules"
    do
    	echo '' >> $AUDIT_FILE
    	echo '# Set the audit.rules configuration to halt system upon audit failure per security requirements' >> $AUDIT_FILE
    	echo "-f $var_audit_failure_mode" >> $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:
      - DISA-STIG-RHEL-09-654265
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.4
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-24
      - audit_rules_system_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_audit_failure_mode # promote to variable
      set_fact:
        var_audit_failure_mode: !!str 2
      tags:
        - always

    - name: 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654265
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.4
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-24
      - audit_rules_system_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Remove the -f option from all Audit config files
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        regexp: ^\s*(?:-f)\s+.*$
        state: absent
      loop: '{{ find_rules_d.files | map(attribute=''path'') | list + [''/etc/audit/audit.rules'']
        }}'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654265
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.4
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-24
      - audit_rules_system_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add Audit -f option into /etc/audit/rules.d/immutable.rules and /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        create: true
        mode: '0600'
        line: -f {{ var_audit_failure_mode }}
      loop:
      - /etc/audit/audit.rules
      - /etc/audit/rules.d/immutable.rules
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654265
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.4
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-24
      - audit_rules_system_shutdown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/group [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/group -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/group -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_group

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2
bsi | SYS.1.1.A10, SYS.1.3.A6
cis | 6.3.3.8
stigref | SV-258219r1015130_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654225
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654225
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/gshadow [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/gshadow -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/gshadow -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_gshadow

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2
bsi | SYS.1.1.A10, SYS.1.3.A6
cis | 6.3.3.8
stigref | SV-258220r1015131_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654230
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654230
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/security/opasswd [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_opasswd

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2
bsi | SYS.1.1.A10, SYS.1.3.A6
cis | 6.3.3.8
stigref | SV-258221r1015132_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654235
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654235
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/passwd [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/passwd -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/passwd -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_passwd

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5

os-srg

SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000304-GPOS-00121, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221, SRG-OS-000274-GPOS-00104, SRG-OS-000275-GPOS-00105, SRG-OS-000276-GPOS-00106, SRG-OS-000277-GPOS-00107

app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2
bsi | SYS.1.1.A10, SYS.1.3.A6
cis | 6.3.3.8
stigref | SV-258222r1015133_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654240
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654240
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/shadow [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/shadow -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/shadow -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_shadow

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2
bsi | SYS.1.1.A10, SYS.1.3.A6
cis | 6.3.3.8
stigref | SV-258223r1015134_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-654245
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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
      - DISA-STIG-RHEL-09-654245
      - 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 Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron [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 /var/spool/cron -p wa -k cronjobs

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/spool/cron -p wa -k cronjobs

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_var_spool_cron

References:

os-srg | SRG-OS-000363-GPOS-00150, SRG-OS-000363-GPOS-00150, SRG-OS-000446-GPOS-00200, SRG-OS-000447-GPOS-00201
stigref | SV-274878r1120758_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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/spool/cron" "$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/spool/cron $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/spool/cron$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/spool/cron -p wa -k cronjobs" >> "$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/cronjobs.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/spool/cron" /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/cronjobs.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/cronjobs.rules"
        # If the cronjobs.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/spool/cron" "$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/spool/cron $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/spool/cron$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/spool/cron -p wa -k cronjobs" >> "$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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Check if watch
        rule for /var/spool/cron already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/spool/cron\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Search /etc/audit/rules.d
        for other rules with specified key cronjobs
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)cronjobs$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Use /etc/audit/rules.d/cronjobs.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/cronjobs.rules
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" 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:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Add watch
        rule for /var/spool/cron in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/spool/cron -p wa -k cronjobs
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Check if watch
        rule for /var/spool/cron already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/spool/cron\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects Changes to Cron Jobs - /var/spool/cron - Add watch
        rule for /var/spool/cron in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/spool/cron -p wa -k cronjobs
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - DISA-STIG-RHEL-09-654096
      - audit_rules_var_spool_cron
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule System Audit Directories Must Be Group Owned By Root [ref]

All audit directories must be group owned by root user. 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 directories 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_directory_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
stigref | SV-258165r958434_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    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 ' ')
    else
      GROUP=root
    fi
    if LC_ALL=C grep -iw ^log_file /etc/audit/auditd.conf; then
      DIR=$(awk -F "=" '/^log_file/ {print $2}' /etc/audit/auditd.conf | tr -d ' ' | rev | cut -d"/" -f2- | rev)
    else
      DIR="/var/log/audit"
    fi

    find ${DIR} -type d -exec chgrp ${GROUP} {} \;

    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
      - DISA-STIG-RHEL-09-653080
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_group_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: System Audit Directories Must Be Group Owned By Root - Register Audit Configuration
        Text
      ansible.builtin.slurp:
        src: /etc/audit/auditd.conf
      register: auditd_config_slurp
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653080
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_group_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: System Audit Directories Must Be Group Owned By Root - Set Permissions Custom
        Location
      ansible.builtin.file:
        group: |-
          {{ auditd_config_slurp['content'] | b64decode | regex_findall('
          log_group\s*=\s*(.+)') | default(['root',], boolean=True) | first }}
        path: |-
          {{ auditd_config_slurp['content'] | b64decode | regex_findall('
          log_file\s*=\s*(.+)') | default(['/var/log/audit/audit.log',], boolean=True) | first | dirname }}
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653080
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_group_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule System Audit Directories Must Be Owned By Root [ref]

All audit directories must be owned by root user. 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_directory_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
stigref | SV-258166r1045303_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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 ' ')
        LOGPATH="$(dirname "$FILE")"
        chown root $LOGPATH
    else
        chown root /var/log/audit
    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
      - DISA-STIG-RHEL-09-653085
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: System Audit Directories Must Be Owned By Root - Register Audit Configuration
        Text
      ansible.builtin.slurp:
        src: /etc/audit/auditd.conf
      register: auditd_config_slurp
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653085
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: System Audit Directories Must Be Owned By Root - Set Permissions Custom Location
      ansible.builtin.file:
        owner: root
        path: |-
          {{ auditd_config_slurp['content'] | b64decode | regex_findall('
          log_file\s*=\s*(.+)') | default(['/var/log/audit/audit.log',], boolean=True) | first | dirname }}
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653085
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - configure_strategy
      - directory_ownership_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### 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
bsi | SYS.1.3.A14
cis | 6.3.4.7
stigref | SV-270176r1117265_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232104
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232104
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232104
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232104
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232104
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232104
      - 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
bsi | SYS.1.3.A14
cis | 6.3.4.6
stigref | SV-270175r1117265_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-232103
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232103
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232103
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232103
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232103
      - 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:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-232103
      - configure_strategy
      - file_ownership_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Audit Configuration Files Permissions are 640 or More Restrictive [ref]

All audit configuration files permissions must be 640 or more restrictive.

    chmod 0640 /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_permissions_audit_configuration

References:

nist | AU-12 b
os-srg | SRG-OS-000063-GPOS-00032
bsi | SYS.1.3.A14
cis | 6.3.4.5
stigref | SV-258171r1045308_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    find -P /etc/audit/ -maxdepth 1 -perm /u+xs,g+xws,o+xwrt  -type f -regextype posix-extended -regex '^.*audit(\.rules|d\.conf)$' -exec chmod u-xs,g-xws,o-xwrt {} \;

    find -P /etc/audit/rules.d/ -maxdepth 1 -perm /u+xs,g+xws,o+xwrt  -type f -regextype posix-extended -regex '^.*\.rules$' -exec chmod u-xs,g-xws,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:
      - DISA-STIG-RHEL-09-653110
      - NIST-800-53-AU-12 b
      - configure_strategy
      - file_permissions_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/audit/ file(s)
      ansible.builtin.command: find -P /etc/audit/ -maxdepth 1 -perm /u+xs,g+xws,o+xwrt  -type
        f -regextype posix-extended -regex "^.*audit(\.rules|d\.conf)$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653110
      - NIST-800-53-AU-12 b
      - configure_strategy
      - file_permissions_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/audit/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653110
      - NIST-800-53-AU-12 b
      - configure_strategy
      - file_permissions_audit_configuration
      - 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+xws,o+xwrt  -type
        f -regextype posix-extended -regex "^.*\.rules$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653110
      - NIST-800-53-AU-12 b
      - configure_strategy
      - file_permissions_audit_configuration
      - 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-xws,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653110
      - NIST-800-53-AU-12 b
      - configure_strategy
      - file_permissions_audit_configuration
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule System Audit Logs Must Have Mode 0640 or Less Permissive [ref]

Determine where the audit logs are stored with the following command:

    $ sudo grep -iw log_file /etc/audit/auditd.conf
    log_file = /var/log/audit/audit.log

Configure the audit log to be protected from unauthorized read access by setting the correct permissive mode with the following command:

    $ sudo chmod 0600 audit_log_file

By default, audit_log_file is "/var/log/audit/audit.log".

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
pcidss4 | 10.3.1, 10.3
bsi | SYS.1.3.A14
cis | 6.3.4.2
stigref | SV-258167r1101918_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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

    chmod 0600 $FILE

    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
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get audit log files
      ansible.builtin.command: grep -iw ^log_file /etc/audit/auditd.conf
      failed_when: false
      changed_when: false
      check_mode: false
      register: log_file_exists
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Parse log file line
      ansible.builtin.command: awk -F '=' '/^log_file/ {print $2}' /etc/audit/auditd.conf
      register: log_file_line
      changed_when: false
      check_mode: false
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - log_file_exists is not skipped and (log_file_exists.stdout | length > 0)
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set default log_file if not set
      ansible.builtin.set_fact:
        log_file: /var/log/audit/audit.log
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - (log_file_exists is skipped) or (log_file_exists is undefined) or (log_file_exists.stdout
        | length == 0)
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set log_file from log_file_line if not set already
      ansible.builtin.set_fact:
        log_file: '{{ log_file_line.stdout | trim }}'
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      - (log_file_exists is not skipped) and (log_file_line.stdout is defined) and (log_file_line.stdout
        | length > 0)
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Apply mode to log file
      ansible.builtin.file:
        path: '{{ log_file }}'
        mode: 384
      failed_when: false
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653090
      - NIST-800-171-3.3.1
      - NIST-800-53-AC-6(1)
      - NIST-800-53-AU-9(4)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - file_permissions_var_log_audit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Configure auditd Data Retention Group contains 15 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 a Sufficiently Large Partition for Audit Logs [ref]

The Red Hat Enterprise Linux 9 operating system must allocate audit record storage capacity to store at least one weeks worth of audit records when audit records are not immediately sent to a central audit record storage facility. The partition size needed to capture a week's worth of audit records is based on the activity level of the system and the total storage capacity available. In normal circumstances, 10.0 GB of storage space for audit records will be sufficient. Determine which partition the audit records are being written to with the following command:

    $ sudo grep log_file /etc/audit/auditd.conf
    log_file = /var/log/audit/audit.log

Check the size of the partition that audit records are written to with the following command:

    $ sudo df -h /var/log/audit/
    /dev/sda2 24G 10.4G 13.6G 43% /var/log/audit

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_auditd_audispd_configure_sufficiently_large_partition

References:

os-srg | SRG-OS-000341-GPOS-00132, SRG-OS-000342-GPOS-00133
stigref | SV-258155r1045300_rule

#### 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_stig

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
stigref | SV-258153r1038966_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_disk_error_action='halt'

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/audit/auditd.conf" >> "/etc/audit/auditd.conf"
        printf '%s\n' "$formatted_output" >> "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653020
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - auditd_data_disk_error_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_disk_error_action # promote to variable
      set_fact:
        var_auditd_disk_error_action: !!str halt
      tags:
        - always

    - name: Configure auditd Disk Error Action on Disk Error
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: disk_error_action = {{ var_auditd_disk_error_action }}
        regexp: ^\s*disk_error_action\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653020
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - auditd_data_disk_error_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### 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`, `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_stig

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
stigref | SV-258154r1038966_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_disk_full_action='halt'

    # 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/audit/auditd.conf" >> "/etc/audit/auditd.conf"
        printf '%s\n' "$formatted_output" >> "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653025
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - auditd_data_disk_full_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_disk_full_action # promote to variable
      set_fact:
        var_auditd_disk_full_action: !!str halt
      tags:
        - always

    - name: Configure auditd Disk Full Action when Disk Space Is Full
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: disk_full_action = {{ var_auditd_disk_full_action }}
        regexp: ^\s*disk_full_action\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653025
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - auditd_data_disk_full_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### 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.3.2.4
stigref | SV-258163r958424_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_action_mail_acct='root'

    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' <<< "^action_mail_acct")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_auditd_action_mail_acct"

    # 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 "^action_mail_acct\\>" "$AUDITCONFIG"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^action_mail_acct\\>.*/$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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "$AUDITCONFIG" >> "$AUDITCONFIG"
        printf '%s\n' "$formatted_output" >> "$AUDITCONFIG"
    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.4.1.1
      - DISA-STIG-RHEL-09-653070
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)
      - PCI-DSS-Req-10.7.a
      - auditd_data_retention_action_mail_acct
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_action_mail_acct # promote to variable
      set_fact:
        var_auditd_action_mail_acct: !!str root
      tags:
        - always

    - name: Configure auditd mail_acct Action on Low Disk Space - Configure auditd mail_acct
        Action on Low Disk Space
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        regexp: ^action_mail_acct
        line: action_mail_acct = {{ var_auditd_action_mail_acct }}
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653070
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)
      - PCI-DSS-Req-10.7.a
      - auditd_data_retention_action_mail_acct
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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
pcidss4 | 10.5.1, 10.5
cis | 6.3.2.4
stigref | SV-258159r971542_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_admin_space_left_action='single'

    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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "$AUDITCONFIG" >> "$AUDITCONFIG"
        printf '%s\n' "$formatted_output" >> "$AUDITCONFIG"
    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.4.1.1
      - DISA-STIG-RHEL-09-653050
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - auditd_data_retention_admin_space_left_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_admin_space_left_action # promote to variable
      set_fact:
        var_auditd_admin_space_left_action: !!str single
      tags:
        - always

    - name: Configure auditd admin_space_left Action on Low Disk Space
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: admin_space_left_action = {{ var_auditd_admin_space_left_action .split('|')[0]
          }}
        regexp: ^\s*admin_space_left_action\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653050
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - auditd_data_retention_admin_space_left_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Configure auditd admin_space_left 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 PERCENTAGE appropriately:

    admin_space_left = PERCENTAGE%

Set this value to 5 to cause the system to perform an action.

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_admin_space_left_percentage

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
pcidss | Req-10.7
os-srg | SRG-OS-000343-GPOS-00134
stigref | SV-258158r971542_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_admin_space_left_percentage='5'

    grep -q "^admin_space_left[[:space:]]*=.*$" /etc/audit/auditd.conf && \
      sed -i "s/^admin_space_left[[:space:]]*=.*$/admin_space_left = $var_auditd_admin_space_left_percentage%/g" /etc/audit/auditd.conf || \
      echo "admin_space_left = $var_auditd_admin_space_left_percentage%" >> /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: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-653045
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_admin_space_left_percentage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_admin_space_left_percentage # promote to variable
      set_fact:
        var_auditd_admin_space_left_percentage: !!str 5
      tags:
        - always

    - name: Configure auditd admin_space_left on Low Disk Space
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: admin_space_left = {{ var_auditd_admin_space_left_percentage }}%
        regexp: ^\s*admin_space_left\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653045
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_admin_space_left_percentage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### 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 `rotate` to ensure log rotation occurs. This is the default. 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_stig

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
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
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
stigref | SV-258160r1038966_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_max_log_file_action='rotate'

    # 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\\>" "/etc/audit/auditd.conf"; 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" "/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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "/etc/audit/auditd.conf" >> "/etc/audit/auditd.conf"
        printf '%s\n' "$formatted_output" >> "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653055
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_max_log_file_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_max_log_file_action # promote to variable
      set_fact:
        var_auditd_max_log_file_action: !!str rotate
      tags:
        - always

    - name: Configure auditd max_log_file_action Upon Reaching Maximum Log Size
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: max_log_file_action = {{ var_auditd_max_log_file_action }}
        regexp: ^\s*max_log_file_action\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653055
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_max_log_file_action_stig
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### 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
pcidss4 | 10.5.1, 10.5
cis | 6.3.2.4
stigref | SV-258157r971542_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; 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
        cce=""
        printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "$AUDITCONFIG" >> "$AUDITCONFIG"
        printf '%s\n' "$formatted_output" >> "$AUDITCONFIG"
    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.4.1.1
      - DISA-STIG-RHEL-09-653040
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - auditd_data_retention_space_left_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_space_left_action # promote to variable
      set_fact:
        var_auditd_space_left_action: !!str email
      tags:
        - always

    - name: Configure auditd space_left Action on Low Disk Space
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: space_left_action = {{ var_auditd_space_left_action.split('|')[0] }}
        regexp: ^\s*space_left_action\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653040
      - NIST-800-171-3.3.1
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - auditd_data_retention_space_left_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Configure auditd space_left 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 PERCENTAGE appropriately:

    space_left = PERCENTAGE%

Set this value to at least 25 to cause the system to notify the user of an issue.

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_percentage

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
pcidss | Req-10.7
os-srg | SRG-OS-000343-GPOS-00134
stigref | SV-258156r1106364_rule

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_space_left_percentage='25'

    grep -q "^space_left[[:space:]]*=.*$" /etc/audit/auditd.conf && \
      sed -i "s/^space_left[[:space:]]*=.*$/space_left = $var_auditd_space_left_percentage%/g" /etc/audit/auditd.conf || \
      echo "space_left = $var_auditd_space_left_percentage%" >> /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: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-653035
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_space_left_percentage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_space_left_percentage # promote to variable
      set_fact:
        var_auditd_space_left_percentage: !!str 25
      tags:
        - always

    - name: Configure auditd space_left on Low Disk Space
      ansible.builtin.lineinfile:
        dest: /etc/audit/auditd.conf
        line: space_left = {{ var_auditd_space_left_percentage }}%
        regexp: ^\s*space_left\s*=\s*.*$
        state: present
        create: true
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653035
      - NIST-800-53-AU-5(1)
      - NIST-800-53-AU-5(2)
      - NIST-800-53-AU-5(4)
      - NIST-800-53-AU-5(b)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - auditd_data_retention_space_left_percentage
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Set number of records to cause an explicit flush to audit logs [ref]

To configure Audit daemon to issue an explicit flush to disk command after writing 100 records, set `freq` to `100` in `/etc/audit/auditd.conf`.
Rationale: | If option `freq` isn't set to `100`, the flush to disk may happen after higher number of records, increasing the danger of audit loss.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_freq

References:

nist | CM-6
ospp | FAU_GEN.1
os-srg | SRG-OS-000051-GPOS-00024
ism | 0582
stigref | SV-258168r958428_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_freq='100'

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*freq\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "freq = $var_auditd_freq" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653095
      - NIST-800-53-CM-6
      - auditd_freq
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_freq # promote to variable
      set_fact:
        var_auditd_freq: !!str 100
      tags:
        - always

    - name: Set number of records to cause an explicit flush to audit logs
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*freq\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*freq\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*freq\s*=\s*
          line: freq = {{ var_auditd_freq }}
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653095
      - NIST-800-53-CM-6
      - auditd_freq
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Include Local Events in Audit Logs [ref]

To configure Audit daemon to include local events in Audit logs, set `local_events` to `yes` in `/etc/audit/auditd.conf`. This is the default setting.
Rationale: | If option `local_events` isn't set to `yes` only events from network will be aggregated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_local_events

References:

nist | CM-6
os-srg | SRG-OS-000062-GPOS-00031, SRG-OS-000480-GPOS-00227
ism | 0582
stigref | SV-258164r1045301_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*local_events\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "local_events = yes" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653075
      - NIST-800-53-CM-6
      - auditd_local_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Include Local Events in Audit Logs
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*local_events\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*local_events\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*local_events\s*=\s*
          line: local_events = yes
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653075
      - NIST-800-53-CM-6
      - auditd_local_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Resolve information before writing to audit logs [ref]

To configure Audit daemon to resolve all uid, gid, syscall, architecture, and socket address information before writing the events to disk, set `log_format` to `ENRICHED` in `/etc/audit/auditd.conf`.
Rationale: | If option `log_format` isn't set to `ENRICHED`, the audit records will be stored in a format exactly as the kernel sends them.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_log_format

References:

nist | CM-6, AU-3
ospp | FAU_GEN.1.2
os-srg | SRG-OS-000255-GPOS-00096, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000096-CTR-000175, SRG-APP-000097-CTR-000180, 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
ism | 0582
stigref | SV-258169r991556_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*log_format\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "log_format = ENRICHED" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653100
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6
      - auditd_log_format
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Resolve information before writing to audit logs
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*log_format\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*log_format\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*log_format\s*=\s*
          line: log_format = ENRICHED
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653100
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6
      - auditd_log_format
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Set type of computer node name logging in audit logs [ref]

To configure Audit daemon to use a unique identifier as computer node name in the audit events, set `name_format` to `hostname|fqd|numeric` in `/etc/audit/auditd.conf`.
Warning: Whenever the variable

    var_auditd_name_format

uses a multiple value option, for example

    A|B|C

, the first value will be used when remediating this rule.

Rationale: | If option `name_format` is left at its default value of `none`, audit events from different computers may be hard to distinguish.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_name_format

References:

nist | CM-6, AU-3
ospp | FAU_GEN.1.2
os-srg | SRG-OS-000039-GPOS-00017, SRG-OS-000342-GPOS-00133, SRG-OS-000479-GPOS-00224
ism | 0582
pcidss4 | 10.2.2, 10.2
stigref | SV-258161r958416_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    var_auditd_name_format='hostname|fqd|numeric'

    var_auditd_name_format="$(echo $var_auditd_name_format | cut -d \| -f 1)"

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*name_format\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "name_format = $var_auditd_name_format" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653060
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.2
      - auditd_name_format
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_auditd_name_format # promote to variable
      set_fact:
        var_auditd_name_format: !!str hostname|fqd|numeric
      tags:
        - always

    - name: Set type of computer node name logging in audit logs - Define Value to Be
        Used in the Remediation
      ansible.builtin.set_fact: auditd_name_format_split="{{ var_auditd_name_format.split('|')[0]
        }}"
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653060
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.2
      - auditd_name_format
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set type of computer node name logging in audit logs
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*name_format\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*name_format\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*name_format\s*=\s*
          line: name_format = {{ auditd_name_format_split }}
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653060
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.2
      - auditd_name_format
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

#### Rule Appropriate Action Must be Setup When the Internal Audit Event Queue is Full [ref]

The audit system should have an action setup in the event the internal event queue becomes full. To setup an overflow action edit `/etc/audit/auditd.conf`. Set `overflow_action` to one of the following values: `syslog`, `single`, `halt`.
Rationale: | The audit system should have an action setup in the event the internal event queue becomes full so that no data is lost.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_overflow_action

References:

nist | AU-4(1)
os-srg | SRG-OS-000342-GPOS-00133, SRG-OS-000479-GPOS-00224
stigref | SV-258162r958754_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*overflow_action\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "overflow_action = syslog" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653065
      - NIST-800-53-AU-4(1)
      - auditd_overflow_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Appropriate Action Must be Setup When the Internal Audit Event Queue is Full
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*overflow_action\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*overflow_action\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*overflow_action\s*=\s*
          line: overflow_action = syslog
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653065
      - NIST-800-53-AU-4(1)
      - auditd_overflow_action
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Write Audit Logs to the Disk [ref]

To configure Audit daemon to write Audit logs to the disk, set `write_logs` to `yes` in `/etc/audit/auditd.conf`. This is the default setting.
Rationale: | If `write_logs` isn't set to `yes`, the Audit logs will not be written to the disk.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_auditd_write_logs

References:

nist | CM-6
os-srg | SRG-OS-000480-GPOS-00227
ism | 0582
stigref | SV-258170r991589_rule

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q audit && rpm --quiet -q kernel-core; then

    if [ -e "/etc/audit/auditd.conf" ] ; then

        LC_ALL=C sed -i "/^\s*write_logs\s*=\s*/Id" "/etc/audit/auditd.conf"
    else
        touch "/etc/audit/auditd.conf"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/audit/auditd.conf"

    cp "/etc/audit/auditd.conf" "/etc/audit/auditd.conf.bak"
    # Insert at the end of the file
    printf '%s\n' "write_logs = yes" >> "/etc/audit/auditd.conf"
    # Clean up after ourselves.
    rm "/etc/audit/auditd.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:
      - DISA-STIG-RHEL-09-653105
      - NIST-800-53-CM-6
      - auditd_write_logs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Write Audit Logs to the Disk
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*write_logs\s*=\s*
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*write_logs\s*=\s*
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/audit/auditd.conf
        ansible.builtin.lineinfile:
          path: /etc/audit/auditd.conf
          create: true
          regexp: (?i)(?i)^\s*write_logs\s*=\s*
          line: write_logs = yes
          state: present
      when:
      - '"audit" in ansible_facts.packages'
      - '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653105
      - NIST-800-53-CM-6
      - auditd_write_logs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Remediation Kubernetes snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        storage:
          files:
          - contents:
              source: data:,{{ %23%0A%23%20This%20file%20controls%20the%20configuration%20of%20the%20audit%20daemon%0A%23%0A%0Alocal_events%20%3D%20yes%0Awrite_logs%20%3D%20yes%0Alog_file%20%3D%20/var/log/audit/audit.log%0Alog_group%20%3D%20root%0Alog_format%20%3D%20ENRICHED%0Aflush%20%3D%20%7B%7B.var_auditd_flush%7D%7D%0Afreq%20%3D%2050%0Amax_log_file%20%3D%20%7B%7B.var_auditd_max_log_file%7D%7D%0Anum_logs%20%3D%20%7B%7B.var_auditd_num_logs%7D%7D%0Apriority_boost%20%3D%204%0Aname_format%20%3D%20hostname%0A%23%23name%20%3D%20mydomain%0Amax_log_file_action%20%3D%20%7B%7B.var_auditd_max_log_file_action%7D%7D%0Aspace_left%20%3D%20%7B%7B.var_auditd_space_left%7D%7D%0Aspace_left_action%20%3D%20%7B%7B.var_auditd_space_left_action%7D%7D%0Averify_email%20%3D%20yes%0Aaction_mail_acct%20%3D%20%7B%7B.var_auditd_action_mail_acct%7D%7D%0Aadmin_space_left%20%3D%2050%0Aadmin_space_left_action%20%3D%20syslog%0Adisk_full_action%20%3D%20%7B%7B.var_auditd_disk_full_action%7D%7D%0Adisk_error_action%20%3D%20%7B%7B.var_auditd_disk_error_action%7D%7D%0Ause_libwrap%20%3D%20yes%0A%23%23tcp_listen_port%20%3D%2060%0Atcp_listen_queue%20%3D%205%0Atcp_max_per_addr%20%3D%201%0A%23%23tcp_client_ports%20%3D%201024-65535%0Atcp_client_max_idle%20%3D%200%0Atransport%20%3D%20TCP%0Akrb5_principal%20%3D%20auditd%0A%23%23krb5_key_file%20%3D%20/etc/audit/audit.key%0Adistribute_network%20%3D%20no%0Aq_depth%20%3D%20400%0Aoverflow_action%20%3D%20syslog%0Amax_restarts%20%3D%2010%0Aplugin_dir%20%3D%20/etc/audit/plugins.d }}
            mode: 0640
            path: /etc/audit/auditd.conf
            overwrite: true

Group System Accounting with auditd Group contains 1 rule
[ref] The audit service provides substantial capabilities for recording system activities. This section deals with permissions of auditd related files.

#### 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

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; 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:
      - DISA-STIG-RHEL-09-653115
      - 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: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653115
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - DISA-STIG-RHEL-09-653115
      - NIST-800-53-AU-12(b)
      - configure_strategy
      - file_permissions_etc_audit_auditd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Install audispd-plugins Package [ref]

The `audispd-plugins` package can be installed with the following command:

    $ sudo dnf install audispd-plugins

Rationale: | `audispd-plugins` provides plugins for the real-time interface to the audit subsystem, `audispd`. These plugins can do things like relay events to remote machines or analyze events for suspicious behavior.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_audispd-plugins_installed

References:

os-srg | SRG-OS-000342-GPOS-00133
pcidss4 | 10.3.3, 10.3
stigref | SV-258175r1045310_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    dnf install audispd-plugins

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package install audispd-plugins

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "audispd-plugins" ; then
        dnf install -y "audispd-plugins"
    fi

    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 Anaconda snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package --add=audispd-plugins

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-653130
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_audispd-plugins_installed

    - name: Ensure audispd-plugins is installed
      ansible.builtin.package:
        name: audispd-plugins
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653130
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.3
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_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
ism | 0582, 0846
pcidss4 | 10.2.1, 10.2
bsi | SYS.1.1.A10
cis | 6.3.1.1
stigref | SV-258151r1045298_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    dnf install audit

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package install audit

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core; then

    if ! rpm -q --quiet "audit" ; then
        dnf install -y "audit"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_audit

    class install_audit {
      package { 'audit':
        ensure => 'installed',
      }
    }

Remediation Anaconda snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    package --add=audit

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - DISA-STIG-RHEL-09-653010
      - 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 audit is installed
      ansible.builtin.package:
        name: audit
        state: present
      when: '"kernel-core" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653010
      - 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 = "audit"
    version = "*"

#### Rule Enable auditd Service [ref]

The `auditd` service is an essential userspace component of the Linux Auditing System, as it is responsible for writing audit records to disk. The `auditd` service can be enabled with the following command:

    $ sudo systemctl enable auditd.service

Rationale:

Without establishing what type of events occurred, it would be difficult to establish, correlate, and investigate the events leading up to an outage or attack. Ensuring the `auditd` service is active ensures audit records generated by the kernel are appropriately recorded.
Additionally, a properly configured audit subsystem ensures that actions of individual system users can be uniquely traced to those users so they can be held accountable for their actions.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_auditd_enabled

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.3.1, 3.3.2, 3.3.6
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(5)(ii)(C), 164.310(a)(2)(iv), 164.310(d)(2)(iii), 164.312(b)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nerc-cip | CIP-004-6 R3.3, CIP-007-3 R6.5
nist | AC-2(g), AU-3, AU-10, AU-2(d), AU-12(c), AU-14(1), AC-6(9), CM-6(a), SI-4(23)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
ospp | FAU_GEN.1
pcidss | Req-10.1

os-srg

SRG-OS-000062-GPOS-00031, SRG-OS-000037-GPOS-00015, SRG-OS-000038-GPOS-00016, SRG-OS-000039-GPOS-00017, SRG-OS-000040-GPOS-00018, SRG-OS-000041-GPOS-00019, SRG-OS-000042-GPOS-00021, SRG-OS-000051-GPOS-00024, SRG-OS-000054-GPOS-00025, SRG-OS-000122-GPOS-00063, SRG-OS-000254-GPOS-00095, SRG-OS-000255-GPOS-00096, SRG-OS-000337-GPOS-00129, SRG-OS-000348-GPOS-00136, SRG-OS-000349-GPOS-00137, SRG-OS-000350-GPOS-00138, SRG-OS-000351-GPOS-00139, SRG-OS-000352-GPOS-00140, SRG-OS-000353-GPOS-00141, SRG-OS-000354-GPOS-00142, SRG-OS-000358-GPOS-00145, SRG-OS-000365-GPOS-00152, SRG-OS-000392-GPOS-00172, SRG-OS-000475-GPOS-00220

app-srg-ctr | SRG-APP-000095-CTR-000170, SRG-APP-000409-CTR-000990, SRG-APP-000508-CTR-001300, SRG-APP-000510-CTR-001310
anssi | R33, R73
ism | 1409
pcidss4 | 10.2.1, 10.2
bsi | SYS.1.1.A10
cis | 6.3.1.4
stigref | SV-258152r1015127_rule

Remediation script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    service enable auditd

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q audit; }; 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
      - DISA-STIG-RHEL-09-653015
      - 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:
        - '"audit" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-653015
      - 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:
      - '"kernel-core" in ansible_facts.packages'
      - '"audit" in ansible_facts.packages'

Remediation Kubernetes snippet ⇲

    ---
    apiVersion: machineconfiguration.openshift.io/v1
    kind: MachineConfig
    spec:
      config:
        ignition:
          version: 3.1.0
        systemd:
          units:
          - name: auditd.service
            enabled: true

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. To ensure that `audit=1` is added as a kernel command line argument to newly installed kernels, add `audit=1` to the default Grub2 command line for Linux operating systems. Modify the line within `/etc/default/grub` as shown below:

    GRUB_CMDLINE_LINUX="... audit=1 ..."

Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --args="audit=1"

If the system is distributed as a bootable container image, GRUB2 can't be configured using the method described above, but the following method needs to be used instead. The kernel arguments should be set in `/usr/lib/bootc/kargs.d` in a TOML file that has the following form:

    # /usr/lib/bootc/kargs.d/10-example.toml
    kargs = ["audit=1"]

For more details on configuring kernel arguments in bootable container images, please refer to Bootc documentation.

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
pcidss4 | 10.7.2, 10.7
bsi | SYS.1.1.A10
cis | 6.3.1.2
stigref | SV-257796r1044847_rule

Remediation script ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    bootloader audit=1

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q grub2-common; }; then

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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

        grubby --update-kernel=ALL --args=audit=1

    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
      - DISA-STIG-RHEL-09-212055
      - 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 if audit argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-212055
      - 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 if audit argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-212055
      - 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: /sbin/grubby --update-kernel=ALL --args="audit=1"
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - (grubby_info.stdout is not search('audit=1')) or ((etc_default_grub['content']
        | b64decode) is not search('audit=1'))
      tags:
      - CJIS-5.4.1.1
      - DISA-STIG-RHEL-09-212055
      - 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

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "audit=1"

#### 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. To ensure that `audit_backlog_limit=8192` is added as a kernel command line argument to newly installed kernels, add `audit_backlog_limit=8192` to the default Grub2 command line for Linux operating systems. Modify the line within `/etc/default/grub` as shown below:

    GRUB_CMDLINE_LINUX="... audit_backlog_limit=8192 ..."

Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --args="audit_backlog_limit=8192"

If the system is distributed as a bootable container image, GRUB2 can't be configured using the method described above, but the following method needs to be used instead. The kernel arguments should be set in `/usr/lib/bootc/kargs.d` in a TOML file that has the following form:

    # /usr/lib/bootc/kargs.d/10-example.toml
    kargs = ["audit_backlog_limit=8192"]

For more details on configuring kernel arguments in bootable container images, please refer to Bootc documentation.

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
pcidss4 | 10.7.2, 10.7
bsi | SYS.1.1.A10
cis | 6.3.1.3
stigref | SV-258173r1101933_rule

Remediation script ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    bootloader audit_backlog_limit=8192

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if rpm --quiet -q kernel-core && { rpm --quiet -q grub2-common; }; then

    var_audit_backlog_limit='8192'

    if { rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; } ; 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

        grubby --update-kernel=ALL --args=audit_backlog_limit=$var_audit_backlog_limit

    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:
      - DISA-STIG-RHEL-09-653120
      - 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 if audit_backlog_limit argument is already present in /etc/default/grub
      ansible.builtin.slurp:
        src: /etc/default/grub
      register: etc_default_grub
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653120
      - 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 if audit_backlog_limit argument is already present
      ansible.builtin.command: /sbin/grubby --info=ALL
      register: grubby_info
      check_mode: false
      changed_when: false
      failed_when: false
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - DISA-STIG-RHEL-09-653120
      - 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: /sbin/grubby --update-kernel=ALL --args="audit_backlog_limit={{
        var_audit_backlog_limit }}"
      when:
      - '"kernel-core" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - (grubby_info.stdout is not search('audit_backlog_limit=' ~ var_audit_backlog_limit))
        or ((etc_default_grub['content'] | b64decode) is not search('audit_backlog_limit='
        ~ var_audit_backlog_limit))
      tags:
      - DISA-STIG-RHEL-09-653120
      - 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

Remediation OSBuild Blueprint snippet ⇲

    [customizations.kernel]
    append = "audit_backlog_limit=8192"

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.