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

> with profile Health Insurance Portability and Accountability Act (HIPAA)
> The HIPAA Security Rule establishes U.S. national standards to protect individuals’ electronic personal health information that is created, received, used, or maintained by a covered entity. The Security Rule requires appropriate administrative, physical and technical safeguards to ensure the confidentiality, integrity, and security of electronic protected health information. This profile configures Red Hat Enterprise Linux 7 to the HIPAA Security Rule identified for securing of electronic protected health information.

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 7. 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 config_item="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 italics="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 italics="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 for Red Hat Enterprise Linux 7, which provides required settings for US Department of Defense systems, is one example of a baseline created from this guidance.
Do not attempt to implement any of the settings in this guide without first testing them in a non-operational environment. The creators of this guidance assume no responsibility whatsoever for its use by other parties, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic.

Profile Title | Health Insurance Portability and Accountability Act (HIPAA)
Profile ID | xccdf_org.ssgproject.content_profile_hipaa

## Revision History

Current version: 0.1.39

- draft (as of 2018-07-26)

## Platforms

- cpe:/o:redhat:enterprise_linux:7
- cpe:/o:redhat:enterprise_linux:7::client
- cpe:/o:redhat:enterprise_linux:7::computenode

## Table of Contents

1. Services

1. Obsolete Services
2. Cron and At Daemons
3. Network Routing
4. Base Services
5. NFS and RPC
6. SSH Server

2. System Settings

1. Configure Syslog
2. Network Configuration and Firewalls
3. SELinux
4. Account and Access Control
5. File Permissions and Masks
6. System Accounting with <tt>auditd</tt>
7. Installing and Maintaining Software

## Checklist

contains 149 rules

### Services [ref]group

The best protection against vulnerable software is running less software. This section describes how to review the software which Red Hat Enterprise Linux 7 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 7 system and provides guidance about which ones can be safely disabled.
Red Hat Enterprise Linux 7 provides a convenient minimal install option that essentially installs the bare necessities for a functional system. When building Red Hat Enterprise Linux 7 systems, it is highly recommended to select the minimal packages and then build up the system from there.

contains 37 rules

### Obsolete Services [ref]group

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

contains 16 rules

### Rlogin, Rsh, and Rexec [ref]group

The Berkeley r-commands are legacy services which allow cleartext remote access and have an insecure trust model.

contains 6 rules

#### Uninstall rsh Package [ref]rule

The `rsh` package contains the client commands for the rsh services

Rationale:

These legacy clients contain numerous security exposures and have been replaced with the more secure SSH package. Even if the server is removed, it is best to ensure the clients are also removed to prevent users from inadvertently attempting to use these commands and therefore exposing their credentials. Note that removing the `rsh` package removes the clients for `rsh`,`rcp`, and `rlogin`.

Severity: unknown

Identifiers: CCE-27274-0

References: 2.3.2, 3.1.13, 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), A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove rsh

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure rsh is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - rsh
      tags:
        - package_rsh_removed
        - unknown_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27274-0
        - NIST-800-171-3.1.13

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_rsh

    class remove_rsh {
      package { 'rsh':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=rsh

#### Disable rlogin Service [ref]rule

The `rlogin` service, which is available with the `rsh-server` package and runs as a service through xinetd or separately as a systemd socket, should be disabled. If using xinetd, set `disable` to `yes` in `/etc/xinetd.d/rlogin`. If using systemd, The `rlogin` socket can be disabled with the following command:

    $ sudo systemctl disable rlogin.socket

Rationale:

The rlogin service uses unencrypted network communications, which means that data from the login session, including passwords and all other information transmitted during the session, can be stolen by eavesdroppers on the network.

Severity: high

Identifiers: CCE-27336-7

References: 2.2.17, 3.1.13, 3.4.7, CCI-001436, 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), AC-17(8), CM-7, IA-5(1)(c)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    grep -qi disable /etc/xinetd.d/rlogin && \
      sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/rlogin

    #
    # Disable rlogin.socket for all systemd targets
    #
    systemctl disable rlogin.socket

    #
    # Stop rlogin.socket if currently running
    #
    systemctl stop rlogin.socket

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service rlogin
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - rlogin
      tags:
        - service_rlogin_disabled
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27336-7
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-53-IA-5(1)(c)
        - NIST-800-171-3.1.13
        - NIST-800-171-3.4.7

#### Disable rexec Service [ref]rule

The `rexec` service, which is available with the `rsh-server` package and runs as a service through xinetd or separately as a systemd socket, should be disabled. If using xinetd, set `disable` to `yes` in `/etc/xinetd.d/rexec`. If using systemd, The `rexec` socket can be disabled with the following command:

    $ sudo systemctl disable rexec.socket

Rationale:

The rexec service uses unencrypted network communications, which means that data from the login session, including passwords and all other information transmitted during the session, can be stolen by eavesdroppers on the network.

Severity: high

Identifiers: CCE-27408-4

References: 2.2.17, 3.1.13, 3.4.7, CCI-000068, CCI-001436, 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), AC-17(8), CM-7

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    grep -qi disable /etc/xinetd.d/rexec && \
      sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/rexec

    #
    # Disable rexec.socket for all systemd targets
    #
    systemctl disable rexec.socket

    #
    # Stop rexec.socket if currently running
    #
    systemctl stop rexec.socket

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service rexec
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - rexec
      tags:
        - service_rexec_disabled
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27408-4
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-171-3.1.13
        - NIST-800-171-3.4.7

#### Disable rsh Service [ref]rule

The `rsh` service, which is available with the `rsh-server` package and runs as a service through xinetd or separately as a systemd socket, should be disabled. If using xinetd, set `disable` to `yes` in `/etc/xinetd.d/rsh`. If using systemd, The `rsh` socket can be disabled with the following command:

    $ sudo systemctl disable rsh.socket

Rationale:

The rsh service uses unencrypted network communications, which means that data from the login session, including passwords and all other information transmitted during the session, can be stolen by eavesdroppers on the network.

Severity: high

Identifiers: CCE-27337-5

References: 2.2.17, 3.1.13, 3.4.7, CCI-000068, CCI-001436, 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), AC-17(8), CM-7, IA-5(1)(c)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    grep -qi disable /etc/xinetd.d/rsh && \
      sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/rsh

    #
    # Disable rsh.socket for all systemd targets
    #
    systemctl disable rsh.socket

    #
    # Stop rsh.socket if currently running
    #
    systemctl stop rsh.socket

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service rsh
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - rsh
      tags:
        - service_rsh_disabled
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27337-5
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-53-IA-5(1)(c)
        - NIST-800-171-3.1.13
        - NIST-800-171-3.4.7

#### Uninstall rsh-server Package [ref]rule

The `rsh-server` package can be uninstalled with the following command:

    $ sudo yum erase rsh-server

Rationale:

The `rsh-server` service provides unencrypted remote access service which does not provide for the confidentiality and integrity of user passwords or the remote session and has very weak authentication. If a privileged user were to login using this service, the privileged user password could be compromised. The `rsh-server` package provides several obsolete and insecure network services. Removing it decreases the risk of those services' accidental (or intentional) activation.

Severity: high

Identifiers: CCE-27342-5

References: RHEL-07-020000, SV-86591r1_rule, CCI-000381, 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), A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3, AC-17(8), CM-7(a), SRG-OS-000095-GPOS-00049

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove rsh-server

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure rsh-server is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - rsh-server
      tags:
        - package_rsh-server_removed
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27342-5
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7(a)
        - DISA-STIG-RHEL-07-020000

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_rsh-server

    class remove_rsh-server {
      package { 'rsh-server':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=rsh-server

#### Remove Rsh Trust Files [ref]rule

The files `/etc/hosts.equiv` and `~/.rhosts` (in each user's home directory) list remote hosts and users that are trusted by the local system when using the rshd daemon. To remove these files, run the following command to delete them from any location:

    $ sudo rm /etc/hosts.equiv

    $ rm ~/.rhosts

Rationale:

Trust files are convenient, but when used in conjunction with the R-services, they can allow unauthenticated access to a system.

Severity: high

Identifiers: CCE-27406-8

References: 6.2.14, CCI-001436, 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), AC-17(8), CM-7

Remediation Shell script: (show)

    find /home -maxdepth 2 -type f -name .rhosts -exec rm -f '{}' \;

    if [ -f /etc/hosts.equiv ]; then
    	/bin/rm -f /etc/hosts.equiv
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - block:
        - name: "Detect shosts.equiv Files on the System"
          find:
              paths: /
              recurse: yes
              patterns: shosts.equiv
          check_mode: no
          register: shosts_equiv_locations

        - name: "Remove Rsh Trust Files"
          file:
              path: "{{ item.path }}"
              state: absent
          with_items: "{{ shosts_equiv_locations.files }}"
          when: shosts_equiv_locations
      tags:
        - no_rsh_trust_files
        - high_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27406-8
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7

### Telnet [ref]group

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.

contains 3 rules

#### Remove telnet Clients [ref]rule

The telnet client allows users to start connections to other systems via the telnet protocol.

Rationale:

The `telnet` protocol is insecure and unencrypted. The use of an unencrypted transmission medium could allow an unauthorized user to steal credentials. The `ssh` package provides an encrypted session and stronger security and is included in Red Hat Enterprise Linux.

Severity: low

Identifiers: CCE-27305-2

References: 2.3.4, 3.1.13, 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), A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove telnet

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure telnet is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - telnet
      tags:
        - package_telnet_removed
        - low_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27305-2
        - NIST-800-171-3.1.13

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_telnet

    class remove_telnet {
      package { 'telnet':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=telnet

#### Disable telnet Service [ref]rule

The `telnet` service configuration file `/etc/xinetd.d/telnet` is not created automatically. If it was created manually, check the `/etc/xinetd.d/telnet` file and ensure that `disable = no` is changed to read `disable = yes` as follows below:

    # description: The telnet server serves telnet sessions; it uses \\
    #       unencrypted username/password pairs for authentication.
    service telnet
    {
            flags           = REUSE
            socket_type     = stream

            wait            = no
            user            = root
            server          = /usr/sbin/in.telnetd
            log_on_failure  += USERID
            disable         = yes
    }

If the `/etc/xinetd.d/telnet` file does not exist, make sure that the activation of the `telnet` service on system boot is disabled via the following command: The `rexec` socket can be disabled with the following command:

    $ sudo systemctl disable rexec.socket

Rationale:

The telnet protocol uses unencrypted network communication, which means that data from the login session, including passwords and all other information transmitted during the session, can be stolen by eavesdroppers on the network. The telnet protocol is also subject to man-in-the-middle attacks.

Severity: high

Identifiers: CCE-27401-9

References: 2.2.18, 3.1.13, 3.4.7, 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), AC-17(8), CM-7, IA-5(1)(c)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    grep -qi disable /etc/xinetd.d/telnet && \
      sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/telnet

    #
    # Disable telnet.socket for all systemd targets
    #
    systemctl disable telnet.socket

    #
    # Stop telnet.socket if currently running
    #
    systemctl stop telnet.socket

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service telnet
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - telnet
      tags:
        - service_telnet_disabled
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27401-9
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-53-IA-5(1)(c)
        - NIST-800-171-3.1.13
        - NIST-800-171-3.4.7

#### Uninstall telnet-server Package [ref]rule

The `telnet-server` package can be uninstalled with the following command:

    $ sudo yum erase 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 unsecure. 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

Identifiers: CCE-27165-0

References: RHEL-07-021710, SV-86701r1_rule, 2.1.1, CCI-000381, 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), A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3, AC-17(8), CM-7(a), SRG-OS-000095-GPOS-00049

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove telnet-server

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure telnet-server is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - telnet-server
      tags:
        - package_telnet-server_removed
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27165-0
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7(a)
        - DISA-STIG-RHEL-07-021710

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_telnet-server

    class remove_telnet-server {
      package { 'telnet-server':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=telnet-server

### NIS [ref]group

The Network Information Service (NIS), also known as 'Yellow Pages' (YP), and its successor NIS+ have been made obsolete by Kerberos, LDAP, and other modern centralized authentication services. NIS should not be used because it suffers from security problems inherent in its design, such as inadequate protection of important authentication information.

contains 3 rules

#### Disable ypbind Service [ref]rule

The `ypbind` service, which allows the system to act as a client in a NIS or NIS+ domain, should be disabled. The `ypbind` service can be disabled with the following command:

    $ sudo systemctl disable ypbind.service

Rationale:

Disabling the `ypbind` service ensures the system is not acting as a client in a NIS or NIS+ domain. This service should be disabled unless in use.

Severity: medium

Identifiers: CCE-27385-4

References: CCI-000305, 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), AC-17(8), CM-7

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable ypbind

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service ypbind
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - ypbind
      tags:
        - service_ypbind_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27385-4
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7

#### Remove NIS Client [ref]rule

The Network Information Service (NIS), formerly known as Yellow Pages, is a client-server directory service protocol used to distribute system configuration files. The NIS client (`ypbind`) was used to bind a system to an NIS server and receive the distributed configuration files.

Rationale:

The NIS service is inherently an insecure system that has been vulnerable to DOS attacks, buffer overflows and has poor authentication for querying NIS maps. NIS generally has been replaced by such protocols as Lightweight Directory Access Protocol (LDAP). It is recommended that the service be removed.

Severity: unknown

Identifiers: CCE-27396-1

References: 2.3.1, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove ypbind

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure ypbind is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - ypbind
      tags:
        - package_ypbind_removed
        - unknown_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27396-1

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_ypbind

    class remove_ypbind {
      package { 'ypbind':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=ypbind

#### Uninstall ypserv Package [ref]rule

The `ypserv` package can be uninstalled with the following command:

    $ sudo yum erase ypserv

Rationale:

The NIS service provides an unencrypted authentication service which does not provide for the confidentiality and integrity of user passwords or the remote session. Removing the `ypserv` package decreases the risk of the accidental (or intentional) activation of NIS or NIS+ services.

Severity: high

Identifiers: CCE-27399-5

References: RHEL-07-020010, SV-86593r1_rule, 2.2.16, CCI-000381, 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), AC-17(8), CM-7(a), SRG-OS-000095-GPOS-00049

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove ypserv

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure ypserv is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - ypserv
      tags:
        - package_ypserv_removed
        - high_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27399-5
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7(a)
        - DISA-STIG-RHEL-07-020010

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_ypserv

    class remove_ypserv {
      package { 'ypserv':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=ypserv

### Xinetd [ref]group

The `xinetd` service acts as a dedicated listener for some network services (mostly, obsolete ones) and can be used to provide access controls and perform some logging. It has been largely obsoleted by other features, and it is not installed by default. The older Inetd service is not even available as part of Red Hat Enterprise Linux 7.

contains 2 rules

#### Disable xinetd Service [ref]rule

The `xinetd` service can be disabled with the following command:

    $ sudo systemctl disable xinetd.service

Rationale:

The xinetd service provides a dedicated listener service for some programs, which is no longer necessary for commonly-used network services. Disabling it ensures that these uncommon services are not running, and also prevents attacks against xinetd itself.

Severity: medium

Identifiers: CCE-27443-1

References: 2.1.7, 3.4.7, CCI-000305, 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), AC-17(8), CM-7

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable xinetd

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service xinetd
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - xinetd
      tags:
        - service_xinetd_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27443-1
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-171-3.4.7

#### Uninstall xinetd Package [ref]rule

The `xinetd` package can be uninstalled with the following command:

    $ sudo yum erase xinetd

Rationale:

Removing the `xinetd` package decreases the risk of the xinetd service's accidental (or intentional) activation.

Severity: unknown

Identifiers: CCE-27354-0

References: CCI-000305, 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), AC-17(8), CM-7

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove xinetd

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure xinetd is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - xinetd
      tags:
        - package_xinetd_removed
        - unknown_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27354-0
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_xinetd

    class remove_xinetd {
      package { 'xinetd':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=xinetd

### Chat/Messaging Services [ref]group

The talk software makes it possible for users to send and receive messages across systems through a terminal session.

contains 2 rules

#### Uninstall talk Package [ref]rule

The `talk` package contains the client program for the Internet talk protocol, which allows the user to chat with other users on different systems. Talk is a communication program which copies lines from one terminal to the terminal of another user. The `talk` package can be removed with the following command:

    $ sudo yum erase talk

Rationale:

The talk software presents a security risk as it uses unencrypted protocols for communications. Removing the `talk` package decreases the risk of the accidental (or intentional) activation of talk client program.

Severity: unknown

Identifiers: CCE-27432-4

References: 2.3.3, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove talk

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure talk is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - talk
      tags:
        - package_talk_removed
        - unknown_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27432-4

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_talk

    class remove_talk {
      package { 'talk':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=talk

#### Uninstall talk-server Package [ref]rule

The `talk-server` package can be removed with the following command:

    $ sudo yum erase talk-server

Rationale:

The talk software presents a security risk as it uses unencrypted protocols for communications. Removing the `talk-server` package decreases the risk of the accidental (or intentional) activation of talk services.

Severity: medium

Identifiers: CCE-27210-4

References: 2.2.21, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to remove packages on RHEL, Fedora, Debian, and possibly other systems.
    #
    # Example Call(s):
    #
    #     package_remove telnet-server
    #
    function package_remove {

    # Load function arguments into local variables
    local package="$1"

    # Check sanity of the input
    if [ $# -ne "1" ]
    then
      echo "Usage: package_remove 'package_name'"
      echo "Aborting."
      exit 1
    fi

    if which dnf ; then
      if rpm -q --quiet "$package"; then
        dnf remove -y "$package"
      fi
    elif which yum ; then
      if rpm -q --quiet "$package"; then
        yum remove -y "$package"
      fi
    elif which apt-get ; then
      apt-get remove -y "$package"
    else
      echo "Failed to detect available packaging system, tried dnf, yum and apt-get!"
      echo "Aborting."
      exit 1
    fi

    }

    package_remove talk-server

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Ensure talk-server is removed
      package:
        name="{{item}}"
        state=absent
      with_items:
        - talk-server
      tags:
        - package_talk-server_removed
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27210-4

Remediation Puppet snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    include remove_talk-server

    class remove_talk-server {
      package { 'talk-server':
        ensure => 'purged',
      }
    }

Remediation Anaconda snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    package --remove=talk-server

### Cron and At Daemons [ref]group

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.

contains 1 rule

#### Enable cron Service [ref]rule

The `crond` service is used to execute commands at preconfigured times. It is required by almost all systems to perform necessary maintenance tasks, such as notifying root of system activity. The `crond` service can be enabled with the following command:

    $ sudo systemctl enable crond.service

Rationale:

Due to its usage for maintenance and security-supporting tasks, enabling the cron daemon is essential.

Severity: medium

Identifiers: CCE-27323-5

References: 5.1.1, 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), CM-7

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command enable crond

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    - name: Enable service crond
      service:
        name="{{item}}"
        enabled="yes"
        state="started"
      with_items:
        - crond
      tags:
        - service_crond_enabled
        - medium_severity
        - enable_strategy
        - low_complexity
        - low_disruption
        - CCE-27323-5
        - NIST-800-53-CM-7

### Network Routing [ref]group

A router is a very desirable target for a potential adversary because they fulfill a variety of infrastructure networking roles such as access to network segments, gateways to other networks, filtering, etc. Therefore, if one is required, the system acting as a router should be dedicated to that purpose alone and be stored in a physically secure location. The system's default routing software is Quagga, and provided in an RPM package of the same name.

contains 1 rule

### Disable Quagga if Possible [ref]group

If Quagga was installed and activated, but the system does not need to act as a router, then it should be disabled and removed.

contains 1 rule

#### Disable Quagga Service [ref]rule

The `zebra` service can be disabled with the following command:

    $ sudo systemctl disable zebra.service

Rationale:

Routing protocol daemons are typically used on routers to exchange network topology information with other routers. If routing daemons are used when not required, system network information may be unnecessarily transmitted across the network.

Severity: medium

Identifiers: CCE-27191-6

References: CCI-000366, 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), SC-32, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable zebra

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service zebra
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - zebra
      tags:
        - service_zebra_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27191-6
        - NIST-800-53-SC-32

### Base Services [ref]group

This section addresses the base services that are installed on a Red Hat Enterprise Linux 7 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.

contains 1 rule

#### Disable KDump Kernel Crash Analyzer (kdump) [ref]rule

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

Identifiers: CCE-80258-7

References: RHEL-07-021300, SV-86681r1_rule, CCI-000366, 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), AC-17(8), CM-7, CM-6(b), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable kdump

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service kdump
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - kdump
      tags:
        - service_kdump_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-80258-7
        - NIST-800-53-AC-17(8)
        - NIST-800-53-CM-7
        - NIST-800-53-CM-6(b)
        - DISA-STIG-RHEL-07-021300

### NFS and RPC [ref]group

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.

contains 1 rule

### Configure NFS Servers [ref]group

The steps in this section are appropriate for systems which operate as NFS servers.

contains 1 rule

#### Use Kerberos Security on All Exports [ref]rule

Using Kerberos on all exported mounts prevents a malicious client or user from impersonating a system user. To cryptography authenticate users to the NFS server, add `sec=krb5:krb5i:krb5p` to each export in `/etc/exports`.

Rationale:

When an NFS server is configured to use AUTH_SYS a selected userid and groupid are used to handle requests from the remote user. The userid and groupid could mistakenly or maliciously be set incorrectly. The AUTH_GSS method of authentication uses certificates on the server and client systems to more securely authenticate the remote mount request.

Severity: medium

Identifiers: CCE-27464-7

References: CCI-000366, 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), AC-14(1), SRG-OS-000480-GPOS-00227

### SSH Server [ref]group

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, http://www.openssh.org. Its server program is called `sshd` and provided by the RPM package `openssh-server`.

contains 17 rules

### Configure OpenSSH Server if Necessary [ref]group

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.

contains 17 rules

#### Disable SSH Support for User Known Hosts [ref]rule

SSH can allow system users user host-based authentication to connect to systems if a cache of the remote systems public keys are available. This should be disabled.
To ensure this behavior is disabled, add or correct the following line in `/etc/ssh/sshd_config`:

    IgnoreUserKnownHosts yes

Rationale:

Configuring this setting for the SSH daemon provides additional assurance that remove login via SSH will require a password, even in the event of misconfiguration elsewhere.

Severity: medium

Identifiers: CCE-80372-6

References: FIA_AFL.1, RHEL-07-040380, SV-86873r2_rule, 3.1.12, CCI-000366, 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), CM-6(a), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^IgnoreUserKnownHosts' 'yes' 'CCE-80372-6' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Disable SSH Support for User Known Hosts"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^IgnoreUserKnownHosts
        line: IgnoreUserKnownHosts yes
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_disable_user_known_hosts
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80372-6
        - NIST-800-53-CM-6(a)
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040380

#### Disable SSH Access via Empty Passwords [ref]rule

To explicitly disallow SSH login from accounts with empty passwords, add or correct the following line in `/etc/ssh/sshd_config`:

    PermitEmptyPasswords no

Any accounts with empty passwords should be disabled immediately, and PAM configuration should prevent users from being able to assign themselves empty passwords.Rationale:

Configuring this setting for the SSH daemon provides additional assurance that remote login via SSH will require a password, even in the event of misconfiguration elsewhere.

Severity: high

Identifiers: CCE-27471-2

References: FIA_AFL.1, RHEL-07-010300, SV-86563r2_rule, 5.2.9, 5.5.6, 3.1.1, 3.1.5, CCI-000366, 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), AC-3, AC-6, CM-6(b), SRG-OS-000480-GPOS-00229

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^PermitEmptyPasswords' 'no' 'CCE-27471-2' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Disable SSH Access via Empty Passwords
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^PermitEmptyPasswords
        line: PermitEmptyPasswords no
        validate: sshd -t -f %s
      tags:
        - sshd_disable_empty_passwords
        - high_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27471-2
        - NIST-800-53-AC-3
        - NIST-800-53-AC-6
        - NIST-800-53-CM-6(b)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-010300

#### Set SSH Client Alive Count [ref]rule

To ensure the SSH idle timeout occurs precisely when the `ClientAliveCountMax` is set, edit `/etc/ssh/sshd_config` as follows:

    ClientAliveCountMax 0

Rationale:

This ensures a user login will be terminated as soon as the `ClientAliveCountMax` is reached.

Severity: medium

Identifiers: CCE-27082-7

References: RHEL-07-040340, SV-86865r3_rule, 5.2.12, 5.5.6, 3.1.11, CCI-001133, CCI-002361, 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), AC-2(5), SA-8, AC-12, SRG-OS-000163-GPOS-00072, SRG-OS-000279-GPOS-00109

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^ClientAliveCountMax' '0' 'CCE-27082-7' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Set SSH Client Alive Count
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^ClientAliveCountMax
        line: ClientAliveCountMax 0
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_set_keepalive
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27082-7
        - NIST-800-53-AC-2(5)
        - NIST-800-53-SA-8
        - NIST-800-53-AC-12
        - NIST-800-171-3.1.11
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040340

#### Disable SSH Support for Rhosts RSA Authentication [ref]rule

SSH can allow authentication through the obsolete rsh command through the use of the authenticating user's SSH keys. This should be disabled.
To ensure this behavior is disabled, add or correct the following line in `/etc/ssh/sshd_config`:

    RhostsRSAAuthentication no

Rationale:

Configuring this setting for the SSH daemon provides additional assurance that remove login via SSH will require a password, even in the event of misconfiguration elsewhere.

Severity: medium

Identifiers: CCE-80373-4

References: FIA_AFL.1, RHEL-07-040330, SV-86863r3_rule, 3.1.12, CCI-000366, 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), CM-6(a), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^RhostsRSAAuthentication' 'no' 'CCE-80373-4' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Disable SSH Support for Rhosts RSA Authentication
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^RhostsRSAAuthentication
        line: RhostsRSAAuthentication no
        validate: sshd -t -f %s
      tags:
        - sshd_disable_rhosts_rsa
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80373-4
        - NIST-800-53-CM-6(a)
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040330

#### Enable SSH Warning Banner [ref]rule

To enable the warning banner and ensure it is consistent across the system, add or correct the following line in `/etc/ssh/sshd_config`:

    Banner /etc/issue

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

Identifiers: CCE-27314-4

References: FMT_MOF_EXT.1, RHEL-07-040170, SV-86849r3_rule, 5.2.16, 5.5.6, 3.1.9, CCI-000048, CCI-000050, CCI-001384, CCI-001385, CCI-001386, CCI-001387, CCI-001388, 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), AC-8(a), AC-8(b), AC-8(c)(1), AC-8(c)(2), AC-8(c)(3), SRG-OS-000023-GPOS-00006, SRG-OS-000024-GPOS-00007, SRG-OS-000228-GPOS-00088

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^Banner' '/etc/issue' 'CCE-27314-4' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Enable SSH Warning Banner
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^Banner
        line: Banner /etc/issue
        validate: sshd -t -f %s
      tags:
        - sshd_enable_warning_banner
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27314-4
        - NIST-800-53-AC-8(a)
        - NIST-800-53-AC-8(b)
        - NIST-800-53-AC-8(c)(1)
        - NIST-800-53-AC-8(c)(2)
        - NIST-800-53-AC-8(c)(3)
        - NIST-800-171-3.1.9
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040170

#### Use Only FIPS 140-2 Validated MACs [ref]rule

Limit the MACs to those hash algorithms which are FIPS-approved. The following line in `/etc/ssh/sshd_config` demonstrates use of FIPS-approved MACs:

    MACs hmac-sha2-512,hmac-sha2-256

Only the following message authentication codes are FIPS 140-2 certified on RHEL 7:
- hmac-sha1
- hmac-sha2-256
- hmac-sha2-512
- hmac-sha1-etm@openssh.com
- hmac-sha2-256-etm@openssh.com
- hmac-sha2-512-etm@openssh.com
Any combination of the above MACs will pass this check. Official FIPS 140-2 paperwork for RHEL7 can be found at http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp2630.pdf.Rationale:

DoD Information Systems are required to use FIPS-approved cryptographic hash functions. The only SSHv2 hash algorithms meeting this requirement is SHA2.

Severity: medium

Identifiers: CCE-27455-5

References: RHEL-07-040400, SV-86877r2_rule, 5.2.12, 3.1.13, 3.13.11, 3.13.8, CCI-001453, 164.308(b)(1), 164.308(b)(2), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii), 164.314(b)(2)(i), AC-17(2), IA-7, SC-13, SRG-OS-000250-GPOS-00093

Remediation Shell script: (show)

    sshd_approved_macs="(N/A)"
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^MACs' "$sshd_approved_macs" 'CCE-27455-5' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Use Only Approved MACs"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^MACs
        line: MACs hmac-sha2-512,hmac-sha2-256,hmac-sha1
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_use_approved_macs
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27455-5
        - NIST-800-53-AC-17(2)
        - NIST-800-53-IA-7
        - NIST-800-53-SC-13
        - NIST-800-171-3.1.13
        - NIST-800-171-3.13.11
        - NIST-800-171-3.13.8
        - DISA-STIG-RHEL-07-040400

#### Disable Kerberos Authentication [ref]rule

Unless needed, SSH should not permit extraneous or unnecessary authentication mechanisms like Kerberos. To disable Kerberos authentication, add or correct the following line in the `/etc/ssh/sshd_config` file:

    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. Vulnerabilities in the system's Kerberos implementations may be subject to exploitation.

Severity: medium

Identifiers: CCE-80221-5

References: FIA_AFL.1, RHEL-07-040440, SV-86885r2_rule, 3.1.12, CCI-000368, CCI-000318, CCI-001812, CCI-001813, CCI-001814, 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), CM-6(c), SRG-OS-000364-GPOS-00151

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^KerberosAuthentication' 'no' 'CCE-80221-5' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Disable Kerberos Authentication"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: (?i)^#?kerberosauthentication
        line: KerberosAuthentication no
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_disable_kerb_auth
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80221-5
        - NIST-800-53-CM-6(c)
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040440

#### Allow Only SSH Protocol 2 [ref]rule

Only SSH protocol version 2 connections should be permitted. The default setting in `/etc/ssh/sshd_config` is correct, and can be verified by ensuring that the following line appears:

    Protocol 2

Rationale:

SSH protocol version 1 is an insecure implementation of the SSH protocol and has many well-known vulnerability exploits. Exploits of the SSH daemon could provide immediate root access to the system.

Severity: high

Identifiers: CCE-27320-1

References: RHEL-07-040390, SV-86875r3_rule, 5.2.2, 5.5.6, 3.1.13, 3.5.4, CCI-000197, CCI-000366, 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), AC-17(8).1(ii), IA-5(1)(c), SRG-OS-000074-GPOS-00042, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^Protocol' '2' 'CCE-27320-1' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Allow Only SSH Protocol 2"
      lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: "^Protocol [0-9]"
        line: "Protocol 2"
        validate: sshd -t -f %s
      #notify: :reload ssh
      tags:
        - sshd_allow_only_protocol2
        - high_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27320-1
        - NIST-800-53-AC-17(8).1(ii)
        - NIST-800-53-IA-5(1)(c)
        - NIST-800-171-3.1.13
        - NIST-800-171-3.5.4
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040390

#### Disable SSH Support for .rhosts Files [ref]rule

SSH can emulate the behavior of the obsolete rsh command in allowing users to enable insecure access to their accounts via `.rhosts` files.
To ensure this behavior is disabled, add or correct the following line in `/etc/ssh/sshd_config`:

    IgnoreRhosts yes

Rationale:

SSH trust relationships mean a compromise on one host can allow an attacker to move trivially to other hosts.

Severity: medium

Identifiers: CCE-27377-1

References: FIA_AFL.1, RHEL-07-040350, SV-86867r2_rule, 5.2.6, 5.5.6, 3.1.12, CCI-000366, AC-3, CM-6(a), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^IgnoreRhosts' 'yes' 'CCE-27377-1' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Disable SSH Support for .rhosts Files
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^IgnoreRhosts
        line: IgnoreRhosts yes
        validate: sshd -t -f %s
      tags:
        - sshd_disable_rhosts
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27377-1
        - NIST-800-53-AC-3
        - NIST-800-53-CM-6(a)
        - NIST-800-171-3.1.12
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040350

#### Do Not Allow SSH Environment Options [ref]rule

To ensure users are not able to override environment options to the SSH daemon, add or correct the following line in `/etc/ssh/sshd_config`:

    PermitUserEnvironment no

Rationale:

SSH environment options potentially allow users to bypass access restriction in some configurations.

Severity: medium

Identifiers: CCE-27363-1

References: RHEL-07-010460, SV-86581r2_rule, 5.2.10, 5.5.6, 3.1.12, CCI-000366, 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), CM-6(b), SRG-OS-000480-GPOS-00229

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^PermitUserEnvironment' 'no' 'CCE-27363-1' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Do Not Allow SSH Environment Options
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^PermitUserEnvironment
        line: PermitUserEnvironment no
        validate: sshd -t -f %s
      tags:
        - sshd_do_not_permit_user_env
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27363-1
        - NIST-800-53-CM-6(b)
        - NIST-800-171-3.1.12
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-010460

#### Use Only FIPS 140-2 Validated Ciphers [ref]rule

Limit the ciphers to those algorithms which are FIPS-approved. Counter (CTR) mode is also preferred over cipher-block chaining (CBC) mode. The following line in `/etc/ssh/sshd_config` demonstrates use of FIPS 140-2 validated ciphers:

    Ciphers aes128-ctr,aes192-ctr,aes256-ctr

The following ciphers are FIPS 140-2 certified on RHEL 7:
- aes128-ctr
- aes192-ctr
- aes256-ctr
- aes128-cbc
- aes192-cbc
- aes256-cbc
- 3des-cbc
- rijndael-cbc@lysator.liu.se
Any combination of the above ciphers will pass this check. Official FIPS 140-2 paperwork for RHEL7 can be found at http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp2630.pdf.Rationale:

Unapproved mechanisms that are used for authentication to the cryptographic module are not verified and therefore cannot be relied upon to provide confidentiality or integrity, and system data may be compromised.
Operating systems utilizing encryption are required to use FIPS-compliant mechanisms for authenticating to cryptographic modules.
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.

Severity: medium

Identifiers: CCE-27295-5

References: RHEL-07-040110, SV-86845r2_rule, 5.2.10, 5.5.6, 3.1.13, 3.13.11, 3.13.8, CCI-000068, CCI-000366, CCI-000803, 164.308(b)(1), 164.308(b)(2), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii), 164.314(b)(2)(i), AC-3, AC-17(2), AU-10(5), CM-6(b), IA-5(1)(c), IA-7, SRG-OS-000033-GPOS-00014, SRG-OS-000120-GPOS-00061, SRG-OS-000125-GPOS-00065, SRG-OS-000250-GPOS-00093, SRG-OS-000393-GPOS-00173

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^Ciphers' 'aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc' 'CCE-27295-5' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Use Only Approved Ciphers
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^Ciphers
        line: Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_use_approved_ciphers
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27295-5
        - NIST-800-53-AC-3
        - NIST-800-53-AC-17(2)
        - NIST-800-53-AU-10(5)
        - NIST-800-53-CM-6(b)
        - NIST-800-53-IA-5(1)(c)
        - NIST-800-53-IA-7
        - NIST-800-171-3.1.13
        - NIST-800-171-3.13.11
        - NIST-800-171-3.13.8
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040110

#### Disable Host-Based Authentication [ref]rule

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.
To disable host-based authentication, add or correct the following line in `/etc/ssh/sshd_config`:

    HostbasedAuthentication no

Rationale:

SSH trust relationships mean a compromise on one host can allow an attacker to move trivially to other hosts.

Severity: medium

Identifiers: CCE-27413-4

References: FIA_AFL.1, RHEL-07-010470, SV-86583r2_rule, 5.2.7, 5.5.6, 3.1.12, CCI-000366, 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), AC-3, CM-6(b), SRG-OS-000480-GPOS-00229

Remediation Shell script: (show)

    grep -q ^HostbasedAuthentication /etc/ssh/sshd_config && \
      sed -i "s/HostbasedAuthentication.*/HostbasedAuthentication no/g" /etc/ssh/sshd_config
    if ! [ $? -eq 0 ]; then
        echo "HostbasedAuthentication no" >> /etc/ssh/sshd_config
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Disable Host-Based Authentication
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: ^HostbasedAuthentication
        line: HostbasedAuthentication no
      tags:
        - disable_host_auth
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27413-4
        - NIST-800-53-AC-3
        - NIST-800-53-CM-6(b)
        - NIST-800-171-3.1.12
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-010470

#### Enable Use of Strict Mode Checking [ref]rule

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. To enable StrictModes in SSH, add or correct the following line in the `/etc/ssh/sshd_config` file:

    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

Identifiers: CCE-80222-3

References: RHEL-07-040450, SV-86887r2_rule, 3.1.12, CCI-000366, 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), AC-6, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^StrictModes' 'yes' 'CCE-80222-3' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Enable Use of Strict Mode Checking"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: (?i)^#?strictmodes
        line: StrictModes yes
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_enable_strictmodes
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80222-3
        - NIST-800-53-AC-6
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040450

#### Enable Use of Privilege Separation [ref]rule

When enabled, SSH will create an unprivileged child process that has the privilege of the authenticated user. To enable privilege separation in SSH, add or correct the following line in the `/etc/ssh/sshd_config` file:

    UsePrivilegeSeparation sandbox

Rationale:

SSH daemon privilege separation causes the SSH process to drop root privileges when not needed which would decrease the impact of software vulnerabilities in the unprivileged section.

Severity: medium

Identifiers: CCE-80223-1

References: RHEL-07-040460, SV-86889r2_rule, 3.1.12, CCI-000366, 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), AC-6, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^UsePrivilegeSeparation' 'sandbox' 'CCE-80223-1' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Enable use of Privilege Separation"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: (?i)^#?useprivilegeseparation
        line: UsePrivilegeSeparation sandbox
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_use_priv_separation
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80223-1
        - NIST-800-53-AC-6
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040460

#### Disable GSSAPI Authentication [ref]rule

Unless needed, SSH should not permit extraneous or unnecessary authentication mechanisms like GSSAPI. To disable GSSAPI authentication, add or correct the following line in the `/etc/ssh/sshd_config` file:

    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

Identifiers: CCE-80220-7

References: FIA_AFL.1, RHEL-07-040430, SV-86883r2_rule, 3.1.12, CCI-000368, CCI-000318, CCI-001812, CCI-001813, CCI-001814, 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), CM-6(c), SRG-OS-000364-GPOS-00151

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^GSSAPIAuthentication' 'no' 'CCE-80220-7' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Disable GSSAPI Authentication"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: (?i)^#?gssapiauthentication
        line: GSSAPIAuthentication no
        validate: sshd -t -f %s
      #notify: sshd -t -f %s
      tags:
        - sshd_disable_gssapi_auth
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80220-7
        - NIST-800-53-CM-6(c)
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040430

#### Disable Compression Or Set Compression to delayed [ref]rule

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

or

    Compression delayed

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 wih root privileges.

Severity: medium

Identifiers: CCE-80224-9

References: RHEL-07-040470, SV-86891r2_rule, 3.1.12, CCI-000366, 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), CM-6(b), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/ssh/sshd_config' '^Compression' 'no' 'CCE-80224-9' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Disable Compression or Set Compression to delayed"
      lineinfile:
        create: yes
        dest: /etc/ssh/sshd_config
        regexp: (?i)^#?compression
        line: Compression delayed
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_disable_compression
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80224-9
        - NIST-800-53-CM-6(b)
        - NIST-800-171-3.1.12
        - DISA-STIG-RHEL-07-040470

#### Disable SSH Root Login [ref]rule

The root user should never be allowed to login to a system directly over a network. To disable root login via SSH, add or correct the following line in `/etc/ssh/sshd_config`:

    PermitRootLogin no

Rationale:

Even though the communications channel may be encrypted, an additional layer of security is gained by extending the policy of not logging directly on as root. In addition, logging in with a user-specific account provides individual accountability of actions performed on the system and also helps to minimize direct attack attempts on root's password.

Severity: medium

Identifiers: CCE-27445-6

References: FIA_AFL.1, RHEL-07-040370, SV-86871r2_rule, 5.2.8, 5.5.6, 3.1.1, 3.1.5, CCI-000366, 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), AC-3, AC-6(2), IA-2(1), IA-2(5), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    SSHD_CONFIG='/etc/ssh/sshd_config'

    # Obtain line number of first uncommented case-insensitive occurrence of Match
    # block directive (possibly prefixed with whitespace) present in $SSHD_CONFIG
    FIRST_MATCH_BLOCK=$(sed -n '/^[[:space:]]*Match[^\n]*/I{=;q}' $SSHD_CONFIG)

    # Obtain line number of first uncommented case-insensitive occurence of
    # PermitRootLogin directive (possibly prefixed with whitespace) present in
    # $SSHD_CONFIG
    FIRST_PERMIT_ROOT_LOGIN=$(sed -n '/^[[:space:]]*PermitRootLogin[^\n]*/I{=;q}' $SSHD_CONFIG)

    # Case: Match block directive not present in $SSHD_CONFIG
    if [ -z "$FIRST_MATCH_BLOCK" ]
    then

        # Case: PermitRootLogin directive not present in $SSHD_CONFIG yet
        if [ -z "$FIRST_PERMIT_ROOT_LOGIN" ]
        then
            # Append 'PermitRootLogin no' at the end of $SSHD_CONFIG
            echo -e "\nPermitRootLogin no" >> $SSHD_CONFIG

        # Case: PermitRootLogin directive present in $SSHD_CONFIG already
        else
            # Replace first uncommented case-insensitive occurrence
            # of PermitRootLogin directive
            sed -i "$FIRST_PERMIT_ROOT_LOGIN s/^[[:space:]]*PermitRootLogin.*$/PermitRootLogin no/I" $SSHD_CONFIG
        fi

    # Case: Match block directive present in $SSHD_CONFIG
    else

        # Case: PermitRootLogin directive not present in $SSHD_CONFIG yet
        if [ -z "$FIRST_PERMIT_ROOT_LOGIN" ]
        then
            # Prepend 'PermitRootLogin no' before first uncommented
            # case-insensitive occurrence of Match block directive
            sed -i "$FIRST_MATCH_BLOCK s/^\([[:space:]]*Match[^\n]*\)/PermitRootLogin no\n\1/I" $SSHD_CONFIG

        # Case: PermitRootLogin directive present in $SSHD_CONFIG and placed
        #       before first Match block directive
        elif [ "$FIRST_PERMIT_ROOT_LOGIN" -lt "$FIRST_MATCH_BLOCK" ]
        then
            # Replace first uncommented case-insensitive occurrence
            # of PermitRootLogin directive
            sed -i "$FIRST_PERMIT_ROOT_LOGIN s/^[[:space:]]*PermitRootLogin.*$/PermitRootLogin no/I" $SSHD_CONFIG

        # Case: PermitRootLogin directive present in $SSHD_CONFIG and placed
        # after first Match block directive
        else
             # Prepend 'PermitRootLogin no' before first uncommented
             # case-insensitive occurrence of Match block directive
             sed -i "$FIRST_MATCH_BLOCK s/^\([[:space:]]*Match[^\n]*\)/PermitRootLogin no\n\1/I" $SSHD_CONFIG
        fi
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Disable SSH Root Login"
      lineinfile:
        create: yes
        dest: "/etc/ssh/sshd_config"
        regexp: "^PermitRootLogin"
        line: "PermitRootLogin no"
        insertafter: '(?i)^#?authentication'
        validate: sshd -t -f %s
      #notify: restart sshd
      tags:
        - sshd_disable_root_login
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27445-6
        - NIST-800-53-AC-3
        - NIST-800-53-AC-6(2)
        - NIST-800-53-IA-2(1)
        - NIST-800-53-IA-2(5)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5
        - CJIS-5.5.6
        - DISA-STIG-RHEL-07-040370

### System Settings [ref]group

Contains rules that check correct system settings.

contains 112 rules

### Configure Syslog [ref]group

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

contains 1 rule

### Rsyslog Logs Sent To Remote Host [ref]group

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.

contains 1 rule

#### Ensure Logs Sent To Remote Host [ref]rule

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 `loghost.example.com` 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:

    *.* @loghost.example.com

To use TCP for log message delivery:

    *.* @@loghost.example.com

To use RELP for log message delivery:

    *.* :omrelp:loghost.example.com

There must be a resolvable DNS CNAME or Alias record set to "(N/A)" for logs to be sent correctly to the centralized logging utility.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: unknown

Identifiers: CCE-27343-3

References: FAU_GEN.1.1.c, RHEL-07-031000, SV-86833r1_rule, 4.2.1.4, CCI-000366, CCI-001348, CCI-000136, CCI-001851, 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), A.12.3.1, AU-3(2), AU-4(1), AU-9, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    rsyslog_remote_loghost_address="(N/A)"
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/rsyslog.conf' '^\*\.\*' "@@$rsyslog_remote_loghost_address" 'CCE-27343-3' '%s %s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: XCCDF Value rsyslog_remote_loghost_address # promote to variable
      set_fact:
        rsyslog_remote_loghost_address: (N/A)
      tags:
        - always

    - name: "Set rsyslog remote loghost"
      lineinfile:
        dest: /etc/rsyslog.conf
        regexp: "^\\*\\.\\*"
        line: "*.* @@{{ rsyslog_remote_loghost_address }}"
        create: yes
      tags:
        - rsyslog_remote_loghost
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27343-3
        - NIST-800-53-AU-3(2)
        - NIST-800-53-AU-4(1)
        - NIST-800-53-AU-9
        - DISA-STIG-RHEL-07-031000

### Network Configuration and Firewalls [ref]group

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.

contains 1 rule

### IPSec Support [ref]group

Support for Internet Protocol Security (IPsec) is provided in Red Hat Enterprise Linux 7 with Libreswan.

contains 1 rule

#### Verify Any Configured IPSec Tunnel Connections [ref]rule

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.

Rationale:

IP tunneling mechanisms can be used to bypass network filtering.

Severity: medium

Identifiers: CCE-80171-2

References: RHEL-07-040820, SV-86941r1_rule, CCI-000336, 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), AC-4, SRG-OS-000480-GPOS-00227

### SELinux [ref]group

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 7, has been sufficiently developed and debugged that it should be usable on almost any Red Hat 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 system, unless that system has unusual requirements which make a stronger policy appropriate.
For more information on SELinux, see https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide

contains 7 rules

### SELinux - Booleans [ref]group

Enable or Disable runtime customization of SELinux system policies without having to reload or recompile the SELinux policy.

contains 3 rules

#### disable the selinuxuser_execstack SELinux Boolean [ref]rule

By default, the SELinux boolean `selinuxuser_execstack` is enabled. This setting should be disabled as unconfined executables should not be able to make their stack executable. To disable the `selinuxuser_execstack` SELinux boolean, run the following command:

    $ sudo setsebool -P selinuxuser_execstack off

Rationale:

Severity: medium

Identifiers: CCE-RHEL7-CCE-TBD

References: RHEL-07-TBD, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    var_selinuxuser_execstack="(N/A)"

    setsebool -P selinuxuser_execstack $var_selinuxuser_execstack

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    - name: XCCDF Value var_selinuxuser_execstack # promote to variable
      set_fact:
        var_selinuxuser_execstack: (N/A)
      tags:
        - always

    - name: Ensure libsemanage-python installed
      package:
        name: libsemanage-python
        state: latest

    - name: Set SELinux boolean selinuxuser_execstack accordingly
      seboolean:
        name: selinuxuser_execstack
        state: "{{ var_selinuxuser_execstack }}"
        persistent: yes
      tags:
        - sebool_selinuxuser_execstack
        - medium_severity
        - enable_strategy
        - low_complexity
        - low_disruption
        - CCE-RHEL7-CCE-TBD
        - DISA-STIG-RHEL-07-TBD

#### Enable the selinuxuser_execmod SELinux Boolean [ref]rule

By default, the SELinux boolean `selinuxuser_execmod` is enabled. If this setting is disabled, it should be enabled. To enable the `selinuxuser_execmod` SELinux boolean, run the following command:

    $ sudo setsebool -P selinuxuser_execmod on

Rationale:

Severity: medium

Identifiers: CCE-RHEL7-CCE-TBD

References: RHEL-07-TBD, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    var_selinuxuser_execmod="(N/A)"

    setsebool -P selinuxuser_execmod $var_selinuxuser_execmod

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    - name: XCCDF Value var_selinuxuser_execmod # promote to variable
      set_fact:
        var_selinuxuser_execmod: (N/A)
      tags:
        - always

    - name: Ensure libsemanage-python installed
      package:
        name: libsemanage-python
        state: latest

    - name: Set SELinux boolean selinuxuser_execmod accordingly
      seboolean:
        name: selinuxuser_execmod
        state: "{{ var_selinuxuser_execmod }}"
        persistent: yes
      tags:
        - sebool_selinuxuser_execmod
        - medium_severity
        - enable_strategy
        - low_complexity
        - low_disruption
        - CCE-RHEL7-CCE-TBD
        - DISA-STIG-RHEL-07-TBD

#### Disable the selinuxuser_execheap SELinux Boolean [ref]rule

By default, the SELinux boolean `selinuxuser_execheap` is disabled. If this setting is enabled, it should be disabled. To disable the `selinuxuser_execheap` SELinux boolean, run the following command:

    $ sudo setsebool -P selinuxuser_execheap off

Rationale:

Severity: medium

Identifiers: CCE-RHEL7-CCE-TBD

References: RHEL-07-TBD, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    var_selinuxuser_execheap="(N/A)"

    setsebool -P selinuxuser_execheap $var_selinuxuser_execheap

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    - name: XCCDF Value var_selinuxuser_execheap # promote to variable
      set_fact:
        var_selinuxuser_execheap: (N/A)
      tags:
        - always

    - name: Ensure libsemanage-python installed
      package:
        name: libsemanage-python
        state: latest

    - name: Set SELinux boolean selinuxuser_execheap accordingly
      seboolean:
        name: selinuxuser_execheap
        state: "{{ var_selinuxuser_execheap }}"
        persistent: yes
      tags:
        - sebool_selinuxuser_execheap
        - medium_severity
        - enable_strategy
        - low_complexity
        - low_disruption
        - CCE-RHEL7-CCE-TBD
        - DISA-STIG-RHEL-07-TBD

#### Configure SELinux Policy [ref]rule

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: high

Identifiers: CCE-27279-9

References: RHEL-07-020220, SV-86615r3_rule, 1.6.1.3, 3.1.2, 3.7.2, CCI-002696, 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), AC-3, AC-3(3), AC-3(4), AC-4, AC-6, AU-9, SI-6(a), SRG-OS-000445-GPOS-00199

Remediation Shell script: (show)

    var_selinux_policy_name="targeted"
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/sysconfig/selinux' '^SELINUXTYPE=' $var_selinux_policy_name 'CCE-27279-9' '%s=%s'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: XCCDF Value var_selinux_policy_name # promote to variable
      set_fact:
        var_selinux_policy_name: targeted
      tags:
        - always

    - name: "Configure SELinux Policy"
      lineinfile:
        path: /etc/sysconfig/selinux
        regexp: '^SELINUXTYPE='
        line: "SELINUXTYPE={{ var_selinux_policy_name }}"
        create: yes
      tags:
        - selinux_policytype
        - high_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27279-9
        - NIST-800-53-AC-3
        - NIST-800-53-AC-3(3)
        - NIST-800-53-AC-3(4)
        - NIST-800-53-AC-4
        - NIST-800-53-AC-6
        - NIST-800-53-AU-9
        - NIST-800-53-SI-6(a)
        - NIST-800-171-3.1.2
        - NIST-800-171-3.7.2
        - DISA-STIG-RHEL-07-020220

#### Ensure SELinux Not Disabled in /etc/default/grub [ref]rule

SELinux can be disabled at boot time by an argument in `/etc/default/grub`. Remove any instances of `selinux=0` from the kernel arguments in that file to prevent SELinux from being disabled at boot.

Rationale:

Disabling a major host protection feature, such as SELinux, at boot time prevents it from confining system services at boot time. Further, it increases the chances that it will remain off during system operation.

Severity: medium

Identifiers: CCE-26961-3

References: 1.6.1.1, 3.1.2, 3.7.2, CCI-000022, CCI-000032, 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), AC-3, AC-3(3), AC-3(4), AC-4, AC-6, AU-9, SI-6(a)

Remediation Shell script: (show)

    sed -i --follow-symlinks "s/selinux=0//gI" /etc/default/grub /etc/grub2.cfg /etc/grub.d/*
    sed -i --follow-symlinks "s/enforcing=0//gI" /etc/default/grub /etc/grub2.cfg /etc/grub.d/*

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Ensure SELinux Not Disabled in /etc/default/grub
      replace:
        dest: /etc/default/grub
        regexp: selinux=0
      tags:
        - enable_selinux_bootloader
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-26961-3
        - NIST-800-53-AC-3
        - NIST-800-53-AC-3(3)
        - NIST-800-53-AC-3(4)
        - NIST-800-53-AC-4
        - NIST-800-53-AC-6
        - NIST-800-53-AU-9
        - NIST-800-53-SI-6(a)
        - NIST-800-171-3.1.2
        - NIST-800-171-3.7.2

#### Ensure No Daemons are Unconfined by SELinux [ref]rule

Daemons for which the SELinux policy does not contain rules will inherit the context of the parent process. Because daemons are launched during startup and descend from the `init` process, they inherit the `initrc_t` context.
To check for unconfined daemons, run the following command:

    $ sudo ps -eZ | egrep "initrc" | egrep -vw "tr|ps|egrep|bash|awk" | tr ':' ' ' | awk '{ print $NF }'

It should produce no output in a well-configured system.Rationale:

Daemons which run with the `initrc_t` context may cause AVC denials, or allow privileges that the daemon does not require.

Severity: medium

Identifiers: CCE-27288-0

References: 1.6.1.6, 3.1.2, 3.1.5, 3.7.2, 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), AC-6, AU-9, CM-7

#### Ensure SELinux State is Enforcing [ref]rule

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

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

Identifiers: CCE-27334-2

References: RHEL-07-020210, SV-86613r2_rule, 1.6.1.2, 3.1.2, 3.7.2, CCI-002165, CCI-002696, 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), AC-3, AC-3(3), AC-3(4), AC-4, AC-6, AU-9, SI-6(a), SRG-OS-000445-GPOS-00199

Remediation Shell script: (show)

    var_selinux_state="enforcing"
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state 'CCE-27334-2' '%s=%s'

    fixfiles onboot
    fixfiles -f relabel

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: XCCDF Value var_selinux_state # promote to variable
      set_fact:
        var_selinux_state: enforcing
      tags:
        - always

    - name: "Ensure SELinux State is Enforcing"
      lineinfile:
        path: /etc/sysconfig/selinux
        regexp: '^SELINUX='
        line: "SELINUX={{ var_selinux_state }}"
        create: yes
      tags:
        - selinux_state
        - high_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27334-2
        - NIST-800-53-AC-3
        - NIST-800-53-AC-3(3)
        - NIST-800-53-AC-3(4)
        - NIST-800-53-AC-4
        - NIST-800-53-AC-6
        - NIST-800-53-AU-9
        - NIST-800-53-SI-6(a)
        - NIST-800-171-3.1.2
        - NIST-800-171-3.7.2
        - DISA-STIG-RHEL-07-020210

### Account and Access Control [ref]group

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

contains 14 rules

### Protect Accounts by Restricting Password-Based Login [ref]group

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.

contains 4 rules

### Restrict Root Logins [ref]group

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.

contains 3 rules

#### Restrict Serial Port Root Logins [ref]rule

To restrict root logins on serial ports, ensure lines of this form do not appear in `/etc/securetty`:

    ttyS0
    ttyS1

Rationale:

Preventing direct root login to serial port interfaces helps ensure accountability for actions taken on the systems using the root account.

Severity: unknown

Identifiers: CCE-27268-2

References: 3.1.1, 3.1.5, CCI-000770, 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), AC-6(2)

Remediation Shell script: (show)

    sed -i '/ttyS/d' /etc/securetty

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Restrict Serial Port Root Logins"
      lineinfile:
        dest: /etc/securetty
        regexp: 'ttyS[0-9]'
        state: absent
      tags:
        - restrict_serial_port_logins
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27268-2
        - NIST-800-53-AC-6(2)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5

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

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

    $ sudo echo > /etc/securetty

Rationale:

Disabling direct root logins ensures proper accountability and multifactor authentication to privileged accounts. Users will first login, then escalate to privileged (root) access via su / sudo. This is required for FISMA Low and FISMA Moderate systems.

Severity: medium

Identifiers: CCE-27294-8

References: 5.5, 3.1.1, 3.1.6, 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), IA-2(1)

Remediation Shell script: (show)

    echo > /etc/securetty

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Direct root Logins Not Allowed"
      shell: echo > /etc/securetty
      tags:
        - no_direct_root_logins
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27294-8
        - NIST-800-53-IA-2(1)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.6

#### Restrict Virtual Console Root Logins [ref]rule

To restrict root logins through the (deprecated) virtual console devices, ensure lines of this form do not appear in `/etc/securetty`:

    vc/1
    vc/2
    vc/3
    vc/4

Rationale:

Preventing direct root login to virtual console devices helps ensure accountability for actions taken on the system using the root account.

Severity: medium

Identifiers: CCE-27318-5

References: 3.1.1, 3.1.5, CCI-000770, 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), AC-6(2)

Remediation Shell script: (show)

    sed -i '/^vc\//d' /etc/securetty

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: "Restrict Virtual Console Root Logins"
      lineinfile:
        dest: /etc/securetty
        regexp: '^vc'
        state: absent
      tags:
        - securetty_root_login_console_only
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27318-5
        - NIST-800-53-AC-6(2)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5

### Verify Proper Storage and Existence of Password Hashes [ref]group

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.

contains 1 rule

#### Prevent Log In to Accounts With Empty Password [ref]rule

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` option in `/etc/pam.d/system-auth` to prevent logins with empty passwords.

Rationale:

If an account has an empty password, anyone could log in and run commands with the privileges of that account. Accounts with empty passwords should never be used in operational environments.

Severity: high

Identifiers: CCE-27286-4

References: FIA_AFL.1, RHEL-07-010290, SV-86561r2_rule, 5.5.2, 3.1.1, 3.1.5, CCI-000366, 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), AC-6, IA-5(b), IA-5(c), IA-5(1)(a), Req-8.2.3, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    sed --follow-symlinks -i 's/\<nullok\>//g' /etc/pam.d/system-auth
    sed --follow-symlinks -i 's/\<nullok\>//g' /etc/pam.d/password-auth

Remediation Ansible snippet: (show)

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

    - name: "Prevent Log In to Accounts With Empty Password - system-auth"
      replace:
        dest: /etc/pam.d/system-auth
        follow: yes
        regexp: 'nullok'
      tags:
        - no_empty_passwords
        - high_severity
        - configure_strategy
        - low_complexity
        - medium_disruption
        - CCE-27286-4
        - NIST-800-53-AC-6
        - NIST-800-53-IA-5(b)
        - NIST-800-53-IA-5(c)
        - NIST-800-53-IA-5(1)(a)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5
        - PCI-DSS-Req-8.2.3
        - CJIS-5.5.2
        - DISA-STIG-RHEL-07-010290

    - name: "Prevent Log In to Accounts With Empty Password - password-auth"
      replace:
        dest: /etc/pam.d/password-auth
        follow: yes
        regexp: 'nullok'
      tags:
        - no_empty_passwords
        - high_severity
        - configure_strategy
        - low_complexity
        - medium_disruption
        - CCE-27286-4
        - NIST-800-53-AC-6
        - NIST-800-53-IA-5(b)
        - NIST-800-53-IA-5(c)
        - NIST-800-53-IA-5(1)(a)
        - NIST-800-171-3.1.1
        - NIST-800-171-3.1.5
        - PCI-DSS-Req-8.2.3
        - CJIS-5.5.2
        - DISA-STIG-RHEL-07-010290

### Protect Physical Console Access [ref]group

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.

contains 10 rules

### Set Boot Loader Password [ref]group

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

contains 5 rules

#### Verify /boot/grub2/grub.cfg Group Ownership [ref]rule

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

Identifiers: CCE-26812-8

References: 1.4.1, 5.5.2.2, 3.4.5, CCI-000225, 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), AC-6(7), Req-7.1

Remediation Shell script: (show)

    chgrp root /boot/grub2/grub.cfg

#### Verify /boot/grub2/grub.cfg User Ownership [ref]rule

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

Identifiers: CCE-26860-7

References: 1.4.1, 5.5.2.2, 3.4.5, CCI-000225, 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), AC-6(7), Req-7.1

Remediation Shell script: (show)

    chown root /boot/grub2/grub.cfg

#### Verify /boot/grub2/grub.cfg Permissions [ref]rule

File permissions for `/boot/grub2/grub.cfg` should be set to 600. To properly set the permissions of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chmod 600 /boot/grub2/grub.cfg

Rationale:

Proper permissions ensure that only the root user can modify important boot parameters.

Severity: medium

Identifiers: CCE-27054-6

References: 1.4.1, 3.4.5, CCI-000225, 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), AC-6(7)

Remediation Shell script: (show)

    chmod 600 /boot/grub2/grub.cfg

#### Set Boot Loader Password [ref]rule

The grub2 boot loader should have a superuser account and password protection enabled to protect boot-time settings.
To do so, select a superuser account name and password and and modify the `/etc/grub.d/01_users` configuration file with the new account name.
Since plaintext passwords are a security risk, generate a hash for the pasword by running the following command:

    $ grub2-setpassword

When prompted, enter the password that was selected.
NOTE: It is recommended 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/root/bootuser/g /etc/grub.d/01_users

To meet FISMA Moderate, the bootloader superuser account and password MUST differ from the root account and password. Once the superuser account and password have been added, update the `grub.cfg` file by running:

    grub2-mkconfig -o /boot/grub2/grub.cfg

NOTE: 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. For more information on how to configure the grub2 superuser account and password, please refer to

- https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sec-Protecting_GRUB_2_with_a_Password.html
.

Severity: high

Identifiers: CCE-27309-4

References: FIA_AFL.1, RHEL-07-010480, SV-86585r4_rule, 1.4.2, 3.4.5, CCI-000213, 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), IA-2(1), IA-5(e), AC-3, SRG-OS-000080-GPOS-00048

#### Set the UEFI Boot Loader Password [ref]rule

The grub2 boot loader should have a superuser account and password protection enabled to protect boot-time settings.
To do so, select a superuser account name and password and and modify the `/etc/grub.d/01_users` configuration file with the new account name.
Since plaintext passwords are a security risk, generate a hash for the pasword by running the following command:

    $ grub2-setpassword

When prompted, enter the password that was selected.
NOTE: It is recommended 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/root/bootuser/g /etc/grub.d/01_users

To meet FISMA Moderate, the bootloader superuser account and password MUST differ from the root account and password. Once the superuser account and password have been added, update the `grub.cfg` file by running:

    grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg

NOTE: 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. For more information on how to configure the grub2 superuser account and password, please refer to

- https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sec-Protecting_GRUB_2_with_a_Password.html
.

Severity: medium

Identifiers: CCE-80354-4

References: FIA_AFL.1, RHEL-07-010490, SV-86587r3_rule, 1.4.2, 3.4.5, CCI-000213, 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), AC-3, SRG-OS-000080-GPOS-00048

#### Verify that Interactive Boot is Disabled [ref]rule

Red Hat Enterprise Linux systems support an "interactive boot" option that can be used to prevent services from being started. On a Red Hat Enterprise Linux 7 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.Rationale:

Using interactive boot, the console user could disable auditing, firewalls, or other services, weakening system security.

Severity: medium

Identifiers: CCE-27335-9

References: FIA_AFL.1, 3.1.2, 3.4.5, CCI-000213, 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), SC-2, AC-3

Remediation Shell script: (show)

    # Systemd confirm_spawn regex to search for and delete if found
    CONFIRM_SPAWN_REGEX="systemd.confirm_spawn=\(1\|yes\|true\|on\)"

    # Modify both the GRUB_CMDLINE_LINUX and GRUB_CMDLINE_LINUX_DEFAULT directives
    for grubcmdline in "GRUB_CMDLINE_LINUX" "GRUB_CMDLINE_LINUX_DEFAULT"
    do
      # Remove 'systemd.confirm_spawn' argument from /etc/default/grub if found
      if grep -q "^${grubcmdline}=\".*${CONFIRM_SPAWN_REGEX}.*\"" /etc/default/grub
      then
        # Remove all three possible occurrences of CONFIRM_SPAWN_REGEX:
        # At the start
        sed -i "s/\"${CONFIRM_SPAWN_REGEX} /\"/" /etc/default/grub
        # At the end
        sed -i "s/ ${CONFIRM_SPAWN_REGEX}\"$/\"/" /etc/default/grub
        # In the middle
        sed -i "s/ ${CONFIRM_SPAWN_REGEX}//" /etc/default/grub
      fi
    done
    # Remove 'systemd.confirm_spawn' kernel argument also from runtime settings
    /sbin/grubby --update-kernel=ALL --remove-args="systemd.confirm_spawn"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name:  Verify that Interactive Boot is Disabled
      lineinfile:
        create: yes
        dest: /etc/default/grub
        regexp: ^systemd.confirm_spawn=
        line: systemd.confirm_spawn=no
        state: present
      tags:
        - disable_interactive_boot
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27335-9
        - NIST-800-53-SC-2
        - NIST-800-53-AC-3
        - NIST-800-171-3.1.2
        - NIST-800-171-3.4.5

#### Disable Ctrl-Alt-Del Burst Action [ref]rule

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

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

Identifiers: CCE-80449-2

References: 3.4.5, CCI-000366, 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), AC-6, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/systemd/system.conf' '^CtrlAltDelBurstAction=' 'none' 'CCE-80449-2' '%s=%s'

#### Require Authentication for Single User Mode [ref]rule

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, no authentication is performed if single-user mode is selected.
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

Identifiers: CCE-27287-2

References: FIA_AFL.1, RHEL-07-010481, SV-92519r1_rule, 1.4.3, 3.1.1, 3.4.5, CCI-000213, 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), IA-2(1), AC-3, SRG-OS-000080-GPOS-00048, RHEL-07-010481, SV-92519r1_rule

Remediation Shell script: (show)

    grep -q "^ExecStart=\-.*/sbin/sulogin" /usr/lib/systemd/system/rescue.service
    if ! [ $? -eq 0 ]; then
        sed -i "s/ExecStart=-.*-c \"/&\/sbin\/sulogin; /g" /usr/lib/systemd/system/rescue.service
    fi

#### Disable Ctrl-Alt-Del Reboot Activation [ref]rule

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

Identifiers: CCE-27511-5

References: RHEL-07-020230, SV-86617r1_rule, 3.4.5, CCI-000366, 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), AC-6, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    # The process to disable ctrl+alt+del has changed in RHEL7.
    # Reference: https://access.redhat.com/solutions/1123873
    systemctl mask ctrl-alt-del.target

#### Disable debug-shell SystemD Service [ref]rule

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 disabled. The `debug-shell` service can be disabled with the following command:

    $ sudo systemctl disable 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

Identifiers: CCE-80206-6

References: FIA_AFL.1, 3.4.5, 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)

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable debug-shell

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service debug-shell
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - debug-shell
      tags:
        - service_debug-shell_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-80206-6
        - NIST-800-171-3.4.5

### File Permissions and Masks [ref]group

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 7 installations:

    $ mount -t xfs | awk '{print $3}'

For any systems that use a different local filesystem type, modify this command as appropriate.

contains 6 rules

### Restrict Dynamic Mounting and Unmounting of Filesystems [ref]group

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

contains 2 rules

#### Disable Modprobe Loading of USB Storage Driver [ref]rule

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 a file in the directory `/etc/modprobe.d`:

    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

Identifiers: CCE-27277-3

References: RHEL-07-020100, SV-86607r2_rule, 3.1.21, CCI-000366, CCI-000778, CCI-001958, 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), AC-19(a), AC-19(d), AC-19(e), IA-3, SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-0016, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    if grep --silent "^install usb-storage" /etc/modprobe.d/usb-storage.conf ; then
    	sed -i 's/^install usb-storage.*/install usb-storage /bin/true/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/true" >> /etc/modprobe.d/usb-storage.conf
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Ensure kernel module 'usb-storage' is disabled
      lineinfile:
        create=yes
        dest="/etc/modprobe.d/{{item}}.conf"
        regexp="{{item}}"
        line="install {{item}} /bin/true"
      with_items:
        - usb-storage
      tags:
        - kernel_module_usb-storage_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - medium_disruption
        - CCE-27277-3
        - NIST-800-53-AC-19(a)
        - NIST-800-53-AC-19(d)
        - NIST-800-53-AC-19(e)
        - NIST-800-53-IA-3
        - NIST-800-171-3.1.21
        - DISA-STIG-RHEL-07-020100

#### Disable the Automounter [ref]rule

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

Identifiers: CCE-27498-5

References: RHEL-07-020110, SV-86609r1_rule, 1.1.22, 3.4.6, CCI-000366, CCI-000778, CCI-001958, 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), AC-19(a), AC-19(d), AC-19(e), IA-3, SRG-OS-000114-GPOS-00059, SRG-OS-000378-GPOS-00163, SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command disable autofs

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | disable

    - name: Disable service autofs
      service:
        name="{{item}}"
        enabled="no"
        state="stopped"
      register: service_result
      failed_when: "service_result|failed and ('Could not find the requested service' not in service_result.msg)"
      with_items:
        - autofs
      tags:
        - service_autofs_disabled
        - medium_severity
        - disable_strategy
        - low_complexity
        - low_disruption
        - CCE-27498-5
        - NIST-800-53-AC-19(a)
        - NIST-800-53-AC-19(d)
        - NIST-800-53-AC-19(e)
        - NIST-800-53-IA-3
        - NIST-800-171-3.4.6
        - DISA-STIG-RHEL-07-020110

### Restrict Programs from Dangerous Execution Patterns [ref]group

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.

contains 4 rules

### Disable Core Dumps [ref]group

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`, 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.

contains 1 rule

#### Disable Core Dumps for SUID programs [ref]rule

To set the runtime status of the `fs.suid_dumpable` kernel parameter, run the following command:

    $ sudo sysctl -w fs.suid_dumpable=0

If this is not the system's default value, add the following line to `/etc/sysctl.conf`:

    fs.suid_dumpable = 0

Rationale:

The core dump of a setuid program is more likely to contain sensitive data, as the program itself runs with greater privileges than the user who initiated execution of the program. Disabling the ability for any setuid program to write a core file decreases the risk of unauthorized access of such data.

Severity: unknown

Identifiers: CCE-26900-1

References: 1.5.1, 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), SI-11

Remediation Shell script: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    #
    # Set runtime for fs.suid_dumpable
    #
    /sbin/sysctl -q -n -w fs.suid_dumpable=0

    #
    # If fs.suid_dumpable present in /etc/sysctl.conf, change value to "0"
    #	else, add "fs.suid_dumpable = 0" to /etc/sysctl.conf
    #
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/sysctl.conf' '^fs.suid_dumpable' "0" 'CCE-26900-1'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Ensure sysctl fs.suid_dumpable is set to 0
      sysctl:
        name: fs.suid_dumpable
        value: 0
        state: present
        reload: yes
      tags:
        - sysctl_fs_suid_dumpable
        - unknown_severity
        - disable_strategy
        - low_complexity
        - medium_disruption
        - CCE-26900-1
        - NIST-800-53-SI-11

### Enable ExecShield [ref]group

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

contains 2 rules

#### Enable ExecShield [ref]rule

By default on Red Hat Enterprise Linux 7 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`. For Red Hat Enterprise Linux 7 32-bit systems, `sysctl` can be used to enable ExecShield.

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

Identifiers: CCE-27211-2

References: 1.5.2, 3.1.7, CCI-002530, 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), SC-39

Remediation Shell script: (show)

    if [ $(getconf LONG_BIT) = "32" ] ; then
      #
      # Set runtime for kernel.exec-shield
      #
      sysctl -q -n -w kernel.exec-shield=1

      #
      # If kernel.exec-shield present in /etc/sysctl.conf, change value to "1"
      #	else, add "kernel.exec-shield = 1" to /etc/sysctl.conf
      #
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

      replace_or_append '/etc/sysctl.conf' '^kernel.exec-shield' '1' 'CCE-27211-2'
    fi

    if [ $(getconf LONG_BIT) = "64" ] ; then
      if grep --silent noexec /boot/grub2/grub*.cfg ; then
            sed -i "s/noexec.*//g" /etc/default/grub
            sed -i "s/noexec.*//g" /etc/grub.d/*
            GRUBCFG=`ls | grep '.cfg$'`
            grub2-mkconfig -o /boot/grub2/$GRUBCFG
      fi
    fi

#### Enable Randomized Layout of Virtual Address Space [ref]rule

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

If this is not the system's default value, add the following line to `/etc/sysctl.conf`:

    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

Identifiers: CCE-27127-0

References: 1.5.1, 3.1.7, CCI-000366, 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), SC-30(2), SRG-OS-000480-GPOS-00227, RHEL-07-040201, SV-92521r1_rule

Remediation Shell script: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' 'CCE-27127-0'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Ensure sysctl kernel.randomize_va_space is set to 2
      sysctl:
        name: kernel.randomize_va_space
        value: 2
        state: present
        reload: yes
      tags:
        - sysctl_kernel_randomize_va_space
        - medium_severity
        - disable_strategy
        - low_complexity
        - medium_disruption
        - CCE-27127-0
        - NIST-800-53-SC-30(2)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-040201

#### Restrict Access to Kernel Message Buffer [ref]rule

To set the runtime status of the `kernel.dmesg_restrict` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.dmesg_restrict=1

If this is not the system's default value, add the following line to `/etc/sysctl.conf`:

    kernel.dmesg_restrict = 1

Rationale:

Unprivileged access to the kernel syslog can expose sensitive kernel address information.

Severity: unknown

Identifiers: CCE-27050-4

References: 3.1.5, CCI-001314, 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), SI-11

Remediation Shell script: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    #
    # Set runtime for kernel.dmesg_restrict
    #
    /sbin/sysctl -q -n -w kernel.dmesg_restrict=1

    #
    # If kernel.dmesg_restrict present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.dmesg_restrict = 1" to /etc/sysctl.conf
    #
    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/sysctl.conf' '^kernel.dmesg_restrict' "1" 'CCE-27050-4'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Ensure sysctl kernel.dmesg_restrict is set to 1
      sysctl:
        name: kernel.dmesg_restrict
        value: 1
        state: present
        reload: yes
      tags:
        - sysctl_kernel_dmesg_restrict
        - unknown_severity
        - disable_strategy
        - low_complexity
        - medium_disruption
        - CCE-27050-4
        - NIST-800-53-SI-11
        - NIST-800-171-3.1.5

### System Accounting with <tt>auditd</tt> [ref]group

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 Fedora Documentation available at `https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide/sect-Security-Enhanced_Linux-Troubleshooting-Fixing_Problems.html#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"`.

contains 73 rules

### Configure <tt>auditd</tt> Data Retention [ref]group

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.

contains 2 rules

#### Configure auditd flush priority [ref]rule

The `auditd` service can be configured to synchronously write audit event data to disk. Add or correct the following line in `/etc/audit/auditd.conf` to ensure that audit event data is fully synchronized with the log files on the disk:

    flush = (N/A)

Rationale:

Audit data should be synchronously written to disk to ensure log integrity. These parameters assure that all audit event data is fully synchronized with the log files on the disk.

Severity: unknown

Identifiers: CCE-27331-8

References: 3.3.1, CCI-001576, 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), AU-9, AU-12(1)

Remediation Shell script: (show)

    var_auditd_flush="(N/A)"

    AUDITCONFIG=/etc/audit/auditd.conf

    # if flush is present, flush param edited to var_auditd_flush
    # else flush param is defined by var_auditd_flush
    #
    # the freq param is only used value 'incremental' and will be
    # commented out if flush != incremental
    #
    # if flush == incremental && freq param is not defined, it
    # will be defined as the package-default value of 20

    grep -q ^flush $AUDITCONFIG && \
      sed -i 's/^flush.*/flush = '"$var_auditd_flush"'/g' $AUDITCONFIG
    if ! [ $? -eq 0 ]; then
      echo "flush = $var_auditd_flush" >> $AUDITCONFIG
    fi

    if ! [ "$var_auditd_flush" == "incremental" ]; then
      sed -i 's/^freq/##freq/g' $AUDITCONFIG
    elif [ "$var_auditd_flush" == "incremental" ]; then
      grep -q freq $AUDITCONFIG && \
        sed -i 's/^#\+freq/freq/g' $AUDITCONFIG
      if ! [ $? -eq 0 ]; then
        echo "freq = 20" >> $AUDITCONFIG
      fi
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    - name: Configure auditd Flush Priority
      lineinfile:
        dest: /etc/audit/auditd.conf
        regexp: '.*flush.*'
        line: flush = data
      #notify: reload auditd
      tags:
        - auditd_data_retention_flush
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27331-8
        - NIST-800-53-AU-9
        - NIST-800-53-AU-12(1)
        - NIST-800-171-3.3.1

#### Configure auditd to use audispd's syslog plugin [ref]rule

To configure the `auditd` service to use the `syslog` plug-in of the `audispd` audit event multiplexor, set the `active` line in `/etc/audisp/plugins.d/syslog.conf` to `yes`. Restart the `auditd` service:

    $ sudo service auditd restart

Rationale:

The auditd service does not include the ability to send audit records to a centralized server for management directly. It does, however, include a plug-in for audit event multiplexor (audispd) to pass audit records to the local syslog server

Severity: medium

Identifiers: CCE-27341-7

References: FAU_GEN.1.1.c, 5.4.1.1, 3.3.1, CCI-000136, 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), AU-1(b), AU-3(2), IR-5, Req-10.5.3

Remediation Shell script: (show)

    grep -q ^active /etc/audisp/plugins.d/syslog.conf && \
      sed -i "s/active.*/active = yes/g" /etc/audisp/plugins.d/syslog.conf
    if ! [ $? -eq 0 ]; then
        echo "active = yes" >> /etc/audisp/plugins.d/syslog.conf
    fi

### Configure <tt>auditd</tt> Rules for Comprehensive Auditing [ref]group

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

contains 69 rules

### Record Information on Kernel Modules Loading and Unloading [ref]group

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:

    -w /usr/sbin/insmod -p x -k modules
    -w /usr/sbin/rmmod -p x -k modules
    -w /usr/sbin/modprobe -p x -k modules
    -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`.

contains 5 rules

#### Ensure auditd Collects Information on Kernel Module Unloading - rmmod [ref]rule

To capture invocation of rmmod, utility used to remove modules from kernel, add the following line:

    -w /usr/sbin/rmmod -p x -k 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

Identifiers: CCE-80416-1

References: FAU_GEN.1.1.c, RHEL-07-030850, SV-86817r3_rule, 5.2.17, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/usr/sbin/rmmod" "x" "modules"
    fix_audit_watch_rule "augenrules" "/usr/sbin/rmmod" "x" "modules"

#### Ensure auditd Collects Information on Kernel Module Unloading - delete_module [ref]rule

To capture kernel module unloading events, use following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S delete_module -F key=modules

Place to add the line depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the line to file `/etc/audit/audit.rules`.Rationale:

The removal of kernel modules can be used to alter the behavior of the kernel and potentially introduce malicious code into kernel space. It is important to have an audit trail of modules that have been introduced into the kernel.

Severity: medium

Identifiers: CCE-80415-3

References: FAU_GEN.1.1.c, RHEL-07-030830, SV-86813r3_rule, 5.2.17, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S delete_module \(-F key=\|-k \).*"
    	GROUP="modules"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S delete_module -k modules"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Ensure auditd Collects Information on Kernel Module Loading - insmod [ref]rule

To capture invocation of insmod, utility used to insert modules into kernel, use the following line:

    -w /usr/sbin/insmod -p x -k 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

Identifiers: CCE-80446-8

References: FAU_GEN.1.1.c, RHEL-07-030840, SV-86815r3_rule, 5.2.17, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/usr/sbin/insmod" "x" "modules"
    fix_audit_watch_rule "augenrules" "/usr/sbin/insmod" "x" "modules"

#### Ensure auditd Collects Information on Kernel Module Loading and Unloading - modprobe [ref]rule

To capture invocation of modprobe, utility used to insert / remove modules from kernel, add the following line:

    -w /usr/sbin/modprobe -p x -k 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

Identifiers: CCE-80417-9

References: FAU_GEN.1.1.c, RHEL-07-030860, SV-86819r3_rule, 5.2.17, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/usr/sbin/modprobe" "x" "modules"
    fix_audit_watch_rule "augenrules" "/usr/sbin/modprobe" "x" "modules"

#### Ensure auditd Collects Information on Kernel Module Loading - init_module [ref]rule

To capture kernel module loading events, use following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S init_module -F key=modules

Place to add the line depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the line to file `/etc/audit/audit.rules`.Rationale:

The addition of kernel modules can be used to alter the behavior of the kernel and potentially introduce malicious code into kernel space. It is important to have an audit trail of modules that have been introduced into the kernel.

Severity: medium

Identifiers: CCE-80414-6

References: FAU_GEN.1.1.c, RHEL-07-030820, SV-86811r3_rule, 5.2.17, 3.1.7, CCI-000172, AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S init_module \(-F key=\|-k \).*"
    	GROUP="modules"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S init_module -k modules"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

### Record Attempts to Alter Logon and Logout Events [ref]group

The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to watch for attempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/run/faillock/ -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file in order to watch for unattempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/run/faillock/ -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

contains 3 rules

#### Record Attempts to Alter Logon and Logout Events - lastlog [ref]rule

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

Identifiers: CCE-80384-1

References: FAU_GEN.1.1.c, RHEL-07-030620, SV-86771r2_rule, 5.2.8, 3.1.7, CCI-000172, CCI-002884, CCI-000126, 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), AC-17(7), AU-1(b), AU-12(a), AU-12(c), IR-5, Req-10.2.3, SRG-OS-000392-GPOS-00172, SRG-OS-000470-GPOS-00214, SRG-OS-000473-GPOS-00218

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/log/lastlog" "wa" "logins"
    fix_audit_watch_rule "augenrules" "/var/log/lastlog" "wa" "logins"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit lastlog tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k logins$"
        patterns: "*.rules"
      register: find_lastlog

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/logins.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/logins.rules
      when: find_lastlog.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_lastlog.files | map(attribute='path') | list | first }}"
      when: find_lastlog.matched > 0

    - name: Inserts/replaces the lastlog rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /var/log/lastlog -p wa -k logins"
        create: yes
      tags:
        - audit_rules_login_events_lastlog
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80384-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030620

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the lastlog rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /var/log/lastlog -p wa -k logins"
      tags:
        - audit_rules_login_events_lastlog
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80384-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030620

#### Record Attempts to Alter Logon and Logout Events - faillock [ref]rule

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/run/faillock/ -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file in order to watch for unattempted manual edits of files involved in storing logon events:

    -w /var/run/faillock/ -p wa -k logins

Rationale:

Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.

Severity: medium

Identifiers: CCE-80383-3

References: FAU_GEN.1.1.c, RHEL-07-030610, SV-86769r3_rule, 5.2.8, 3.1.7, CCI-000172, CCI-002884, CCI-000126, 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), AC-17(7), AU-1(b), AU-12(a), AU-12(c), IR-5, Req-10.2.3, SRG-OS-000392-GPOS-00172, SRG-OS-000470-GPOS-00214, SRG-OS-000473-GPOS-00218

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/run/faillock" "wa" "logins"
    fix_audit_watch_rule "augenrules" "/var/run/faillock" "wa" "logins"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit faillock tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k logins$"
        patterns: "*.rules"
      register: find_faillock

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/logins.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/logins.rules
      when: find_faillock.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_faillock.files | map(attribute='path') | list | first }}"
      when: find_faillock.matched > 0

    - name: Inserts/replaces the faillock rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /var/run/faillock -p wa -k logins"
        create: yes
      tags:
        - audit_rules_login_events_faillock
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80383-3
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030610

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the faillock rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /var/run/faillock -p wa -k logins"
      tags:
        - audit_rules_login_events_faillock
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80383-3
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030610

#### Record Attempts to Alter Logon and Logout Events - tallylog [ref]rule

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

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

Rationale:

Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.

Severity: medium

Identifiers: CCE-80382-5

References: FAU_GEN.1.1.c, RHEL-07-030600, SV-86767r2_rule, 5.2.8, 3.1.7, CCI-000172, CCI-002884, CCI-000126, 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), AC-17(7), AU-1(b), AU-12(a), AU-12(c), IR-5, Req-10.2.3, SRG-OS-000392-GPOS-00172, SRG-OS-000470-GPOS-00214, SRG-OS-000473-GPOS-00218

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/log/tallylog" "wa" "logins"
    fix_audit_watch_rule "augenrules" "/var/log/tallylog" "wa" "logins"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit tallylog tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k logins$"
        patterns: "*.rules"
      register: find_tallylog

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/logins.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/logins.rules
      when: find_tallylog.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_tallylog.files | map(attribute='path') | list | first }}"
      when: find_tallylog.matched > 0

    - name: Inserts/replaces the tallylog rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /var/log/tallylog -p wa -k logins"
        create: yes
      tags:
        - audit_rules_login_events_tallylog
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80382-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030600

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the tallylog rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /var/log/tallylog -p wa -k logins"
      tags:
        - audit_rules_login_events_tallylog
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80382-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.3
        - DISA-STIG-RHEL-07-030600

### Records Events that Modify Date and Time Information [ref]group

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time. All changes to the system time should be audited.

contains 5 rules

#### Record Attempts to Alter Time Through stime [ref]rule

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d` for both 32 bit and 64 bit systems:

    -a always,exit -F arch=b32 -S stime -F key=audit_time_rules

Since the 64 bit version of the "stime" system call is not defined in the audit lookup table, the corresponding "-F arch=b64" form of this rule is not expected to be defined on 64 bit systems (the aforementioned "-F arch=b32" stime rule form itself is sufficient for both 32 bit and 64 bit systems). If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file for both 32 bit and 64 bit systems:

    -a always,exit -F arch=b32 -S stime -F key=audit_time_rules

Since the 64 bit version of the "stime" system call is not defined in the audit lookup table, the corresponding "-F arch=b64" form of this rule is not expected to be defined on 64 bit systems (the aforementioned "-F arch=b32" stime rule form itself is sufficient for both 32 bit and 64 bit systems). The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined system calls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale:

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.

Severity: unknown

Identifiers: CCE-27299-7

References: 5.4.1.1, 3.1.7, CCI-001487, CCI-000169, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.4.2.b

Remediation Shell script: (show)

    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    # Perform the remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    # system calls on Red Hat Enterprise Linux 7 or Fedora OSes
    function rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation {

    # Retrieve hardware architecture of the underlying system
    [ $(getconf LONG_BIT) = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do

    	PATTERN="-a always,exit -F arch=${ARCH} -S .* -k *"
    	# Create expected audit group and audit rule form for particular system call & architecture
    	if [ ${ARCH} = "b32" ]
    	then
    		# stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
    		# so append it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\|stime\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -S stime -k audit_time_rules"
    	elif [ ${ARCH} = "b64" ]
    	then
    		# stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
    		# therefore don't add it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -k audit_time_rules"
    	fi
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    }

    rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation

#### Record attempts to alter time through settimeofday [ref]rule

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S settimeofday -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S settimeofday -F key=audit_time_rules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S settimeofday -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S settimeofday -F key=audit_time_rules

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined syscalls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale:

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.

Severity: unknown

Identifiers: CCE-27216-1

References: 5.2.4, 5.4.1.1, 3.1.7, CCI-001487, CCI-000169, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.4.2.b

Remediation Shell script: (show)

    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    # Perform the remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    # system calls on Red Hat Enterprise Linux 7 or Fedora OSes
    function rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation {

    # Retrieve hardware architecture of the underlying system
    [ $(getconf LONG_BIT) = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do

    	PATTERN="-a always,exit -F arch=${ARCH} -S .* -k *"
    	# Create expected audit group and audit rule form for particular system call & architecture
    	if [ ${ARCH} = "b32" ]
    	then
    		# stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
    		# so append it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\|stime\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -S stime -k audit_time_rules"
    	elif [ ${ARCH} = "b64" ]
    	then
    		# stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
    		# therefore don't add it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -k audit_time_rules"
    	fi
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    }

    rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation

#### Record Attempts to Alter the localtime File [ref]rule

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`:

    -w /etc/localtime -p wa -k audit_time_rules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -w /etc/localtime -p wa -k audit_time_rules

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport and should always be used.Rationale:

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.

Severity: unknown

Identifiers: CCE-27310-2

References: 5.2.4, 5.4.1.1, 3.1.7, CCI-001487, CCI-000169, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(b), IR-5, Req-10.4.2.b

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    fix_audit_watch_rule "augenrules" "/etc/localtime" "wa" "audit_time_rules"

#### Record Attempts to Alter Time Through clock_settime [ref]rule

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S clock_settime -F a0=0x0 -F key=time-change

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S clock_settime -F a0=0x0 -F key=time-change

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S clock_settime -F a0=0x0 -F key=time-change

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S clock_settime -F a0=0x0 -F key=time-change

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined syscalls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale:

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.

Severity: unknown

Identifiers: CCE-27219-5

References: 5.2.4, 5.4.1.1, 3.1.7, CCI-001487, CCI-000169, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.4.2.b

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S clock_settime -F a0=.* \(-F key=\|-k \).*"
    	GROUP="clock_settime"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S clock_settime -F a0=0x0 -k time-change"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Record attempts to alter time through adjtimex [ref]rule

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S adjtimex -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S adjtimex -F key=audit_time_rules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S adjtimex -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S adjtimex -F key=audit_time_rules

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined syscalls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale:

Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.

Severity: unknown

Identifiers: CCE-27290-6

References: 5.2.4, 5.4.1.1, 3.1.7, CCI-001487, CCI-000169, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.4.2.b

Remediation Shell script: (show)

    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    # Perform the remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    # system calls on Red Hat Enterprise Linux 7 or Fedora OSes
    function rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation {

    # Retrieve hardware architecture of the underlying system
    [ $(getconf LONG_BIT) = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do

    	PATTERN="-a always,exit -F arch=${ARCH} -S .* -k *"
    	# Create expected audit group and audit rule form for particular system call & architecture
    	if [ ${ARCH} = "b32" ]
    	then
    		# stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
    		# so append it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\|stime\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -S stime -k audit_time_rules"
    	elif [ ${ARCH} = "b64" ]
    	then
    		# stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
    		# therefore don't add it to the list of time group system calls to be audited
    		GROUP="\(adjtimex\|settimeofday\)"
    		FULL_RULE="-a always,exit -F arch=${ARCH} -S adjtimex -S settimeofday -k audit_time_rules"
    	fi
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    }

    rhel7_fedora_perform_audit_adjtimex_settimeofday_stime_remediation

### Record Events that Modify the System's Discretionary Access Controls [ref]group

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!=4294967295 -F key=perm_mod
        -a always,exit -F arch=b32 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod
        -a always,exit -F arch=b32 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=perm_mod
        -a always,exit -F arch=b64 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod
        -a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod

contains 13 rules

#### Record Events that Modify the System's Discretionary Access Controls - fchown [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27356-5

References: FAU_GEN.1.1.c, RHEL-07-030380, SV-86723r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fchown.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fchown tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fchown

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fchown.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fchown.files | map(attribute='path') | list | first }}"
      when: find_fchown.matched > 0

    - name: Inserts/replaces the fchown rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27356-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030380

    - name: Inserts/replaces the fchown rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27356-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030380
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fchown rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27356-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030380

    - name: Inserts/replaces the fchown rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27356-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030380

#### Record Events that Modify the System's Discretionary Access Controls - setxattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27213-8

References: FAU_GEN.1.1.c, RHEL-07-030440, SV-86735r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S setxattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S setxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit setxattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_setxattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_setxattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_setxattr.files | map(attribute='path') | list | first }}"
      when: find_setxattr.matched > 0

    - name: Inserts/replaces the setxattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S setxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_setxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27213-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030440

    - name: Inserts/replaces the setxattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S setxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_setxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27213-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030440
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the setxattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S setxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_setxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27213-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030440

    - name: Inserts/replaces the setxattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S setxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_setxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27213-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030440

#### Record Events that Modify the System's Discretionary Access Controls - chown [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27364-9

References: FAU_GEN.1.1.c, RHEL-07-030370, SV-86721r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S chown.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S chown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit chown tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_chown

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_chown.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_chown.files | map(attribute='path') | list | first }}"
      when: find_chown.matched > 0

    - name: Inserts/replaces the chown rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_chown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27364-9
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030370

    - name: Inserts/replaces the chown rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_chown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27364-9
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030370
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the chown rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_chown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27364-9
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030370

    - name: Inserts/replaces the chown rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_chown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27364-9
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030370

#### Record Events that Modify the System's Discretionary Access Controls - lsetxattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27280-7

References: FAU_GEN.1.1.c, RHEL-07-030460, SV-86739r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S lsetxattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S lsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit lsetxattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_lsetxattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_lsetxattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_lsetxattr.files | map(attribute='path') | list | first }}"
      when: find_lsetxattr.matched > 0

    - name: Inserts/replaces the lsetxattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S lsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_lsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27280-7
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030460

    - name: Inserts/replaces the lsetxattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S lsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27280-7
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030460
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the lsetxattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S lsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_lsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27280-7
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030460

    - name: Inserts/replaces the lsetxattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S lsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27280-7
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030460

#### Record Events that Modify the System's Discretionary Access Controls - lchown [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27083-5

References: FAU_GEN.1.1.c, RHEL-07-030390, SV-86725r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S lchown.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit lchown tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_lchown

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_lchown.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_lchown.files | map(attribute='path') | list | first }}"
      when: find_lchown.matched > 0

    - name: Inserts/replaces the lchown rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_lchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27083-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030390

    - name: Inserts/replaces the lchown rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27083-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030390
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the lchown rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_lchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27083-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030390

    - name: Inserts/replaces the lchown rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lchown
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27083-5
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030390

#### Record Events that Modify the System's Discretionary Access Controls - chmod [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27339-1

References: FAU_GEN.1.1.c, RHEL-07-030410, SV-86729r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S chmod.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S chmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit chmod tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_chmod

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_chmod.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_chmod.files | map(attribute='path') | list | first }}"
      when: find_chmod.matched > 0

    - name: Inserts/replaces the chmod rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_chmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27339-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030410

    - name: Inserts/replaces the chmod rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_chmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27339-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030410
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the chmod rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_chmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27339-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030410

    - name: Inserts/replaces the chmod rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_chmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27339-1
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030410

#### Record Events that Modify the System's Discretionary Access Controls - removexattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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

Identifiers: CCE-27367-2

References: FAU_GEN.1.1.c, RHEL-07-030470, SV-86741r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S removexattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S removexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit removexattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_removexattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_removexattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_removexattr.files | map(attribute='path') | list | first }}"
      when: find_removexattr.matched > 0

    - name: Inserts/replaces the removexattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S removexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_removexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27367-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030470

    - name: Inserts/replaces the removexattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S removexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_removexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27367-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030470
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the removexattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S removexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_removexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27367-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030470

    - name: Inserts/replaces the removexattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S removexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_removexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27367-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030470

#### Record Events that Modify the System's Discretionary Access Controls - fchmod [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27393-8

References: FAU_GEN.1.1.c, RHEL-07-030420, SV-86731r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fchmod.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fchmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fchmod tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fchmod

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fchmod.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fchmod.files | map(attribute='path') | list | first }}"
      when: find_fchmod.matched > 0

    - name: Inserts/replaces the fchmod rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fchmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27393-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030420

    - name: Inserts/replaces the fchmod rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27393-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030420
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fchmod rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fchmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27393-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030420

    - name: Inserts/replaces the fchmod rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchmod
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27393-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030420

#### Record Events that Modify the System's Discretionary Access Controls - fchownat [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27387-0

References: FAU_GEN.1.1.c, RHEL-07-030400, SV-86727r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fchownat.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fchownat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fchownat tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fchownat

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fchownat.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fchownat.files | map(attribute='path') | list | first }}"
      when: find_fchownat.matched > 0

    - name: Inserts/replaces the fchownat rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fchownat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27387-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030400

    - name: Inserts/replaces the fchownat rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchownat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27387-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030400
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fchownat rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fchownat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27387-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030400

    - name: Inserts/replaces the fchownat rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchownat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27387-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030400

#### Record Events that Modify the System's Discretionary Access Controls - fremovexattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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

Identifiers: CCE-27353-2

References: FAU_GEN.1.1.c, RHEL-07-030480, SV-86743r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fremovexattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fremovexattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fremovexattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fremovexattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fremovexattr.files | map(attribute='path') | list | first }}"
      when: find_fremovexattr.matched > 0

    - name: Inserts/replaces the fremovexattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27353-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030480

    - name: Inserts/replaces the fremovexattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27353-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030480
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fremovexattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27353-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030480

    - name: Inserts/replaces the fremovexattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27353-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030480

#### Record Events that Modify the System's Discretionary Access Controls - lremovexattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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

Identifiers: CCE-27410-0

References: FAU_GEN.1.1.c, RHEL-07-030490, SV-86745r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S lremovexattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S lremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit lremovexattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_lremovexattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_lremovexattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_lremovexattr.files | map(attribute='path') | list | first }}"
      when: find_lremovexattr.matched > 0

    - name: Inserts/replaces the lremovexattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S lremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_lremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27410-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030490

    - name: Inserts/replaces the lremovexattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S lremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27410-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030490
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the lremovexattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S lremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_lremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27410-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030490

    - name: Inserts/replaces the lremovexattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S lremovexattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_lremovexattr
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27410-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030490

#### Record Events that Modify the System's Discretionary Access Controls - fsetxattr [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27389-6

References: FAU_GEN.1.1.c, RHEL-07-030450, SV-86737r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fsetxattr.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fsetxattr tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fsetxattr

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fsetxattr.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fsetxattr.files | map(attribute='path') | list | first }}"
      when: find_fsetxattr.matched > 0

    - name: Inserts/replaces the fsetxattr rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27389-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030450

    - name: Inserts/replaces the fsetxattr rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27389-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030450
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fsetxattr rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27389-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030450

    - name: Inserts/replaces the fsetxattr rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fsetxattr -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fsetxattr
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27389-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030450

#### Record Events that Modify the System's Discretionary Access Controls - fchmodat [ref]rule

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=perm_mod

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: unknown

Identifiers: CCE-27388-8

References: FAU_GEN.1.1.c, RHEL-07-030430, SV-86733r3_rule, 5.2.10, 5.4.1.1, 3.1.7, CCI-000126, CCI-000172, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5, SRG-OS-000064-GPOS-00033, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S fchmodat.*"
    	GROUP="perm_mod"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S fchmodat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit fchmodat tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_fchmodat

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_fchmodat.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_fchmodat.files | map(attribute='path') | list | first }}"
      when: find_fchmodat.matched > 0

    - name: Inserts/replaces the fchmodat rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      tags:
        - audit_rules_dac_modification_fchmodat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27388-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030430

    - name: Inserts/replaces the fchmodat rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
        create: yes
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchmodat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27388-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030430
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the fchmodat rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      tags:
        - audit_rules_dac_modification_fchmodat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27388-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030430

    - name: Inserts/replaces the fchmodat rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=4294967295 -F key=perm_mod"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_dac_modification_fchmodat
        - unknown_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27388-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.5.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030430

### Record Execution Attempts to Run SELinux Privileged Commands [ref]group

At a minimum, the audit system should collect the execution of SELinux privileged commands for all users and root.

contains 4 rules

#### Record Any Attempts to Run restorecon [ref]rule

At a minimum, the audit system should collect any execution attempt of the `restorecon` command 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 path=/usr/sbin/restorecon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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 path=/usr/sbin/restorecon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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

Identifiers: CCE-80394-0

References: FAU_GEN.1.1.c, 3.1.7, CCI-000172, CCI-002884, 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), AU-12(c), SRG-OS-000392-GPOS-00172, SRG-OS-000463-GPOS-00207, SRG-OS-000465-GPOS-00209

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/restorecon\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/restorecon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/restorecon.*$"
        patterns: "*.rules"
      register: find_restorecon

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_restorecon.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_restorecon.files | map(attribute='path') | list | first }}"
      when: find_restorecon.matched > 0

    - name: Inserts/replaces the restorecon rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/restorecon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_restorecon
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80394-0
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7

    # Inserts/replaces the restorecon rule in /etc/audit/audit.rules

    - name: Inserts/replaces the restorecon rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/restorecon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_restorecon
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80394-0
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7

#### Record Any Attempts to Run setsebool [ref]rule

At a minimum, the audit system should collect any execution attempt of the `setsebool` command 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 path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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 path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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

Identifiers: CCE-80392-4

References: FAU_GEN.1.1.c, RHEL-07-030570, SV-86761r3_rule, 3.1.7, CCI-000172, CCI-002884, 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), AU-12(c), SRG-OS-000392-GPOS-00172, SRG-OS-000463-GPOS-00207, SRG-OS-000465-GPOS-00209

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/setsebool\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/setsebool.*$"
        patterns: "*.rules"
      register: find_setsebool

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_setsebool.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_setsebool.files | map(attribute='path') | list | first }}"
      when: find_setsebool.matched > 0

    - name: Inserts/replaces the setsebool rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_setsebool
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80392-4
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030570

    # Inserts/replaces the setsebool rule in /etc/audit/audit.rules

    - name: Inserts/replaces the setsebool rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/setsebool -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_setsebool
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80392-4
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030570

#### Record Any Attempts to Run semanage [ref]rule

At a minimum, the audit system should collect any execution attempt of the `semanage` command 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 path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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 path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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

Identifiers: CCE-80391-6

References: FAU_GEN.1.1.c, RHEL-07-030560, SV-86759r3_rule, 3.1.7, CCI-000172, CCI-002884, 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), AU-12(c), SRG-OS-000392-GPOS-00172, SRG-OS-000463-GPOS-00207, SRG-OS-000465-GPOS-00209

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/semanage\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/semanage.*$"
        patterns: "*.rules"
      register: find_semanage

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_semanage.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_semanage.files | map(attribute='path') | list | first }}"
      when: find_semanage.matched > 0

    - name: Inserts/replaces the semanage rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_semanage
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80391-6
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030560

    # Inserts/replaces the semanage rule in /etc/audit/audit.rules

    - name: Inserts/replaces the semanage rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/semanage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_semanage
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80391-6
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030560

#### Record Any Attempts to Run chcon [ref]rule

At a minimum, the audit system should collect any execution attempt of the `chcon` command 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 path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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 path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged-priv_change

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

Identifiers: CCE-80393-2

References: FAU_GEN.1.1.c, RHEL-07-030580, SV-86763r3_rule, 3.1.7, CCI-000172, CCI-002884, 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), AU-12(c), SRG-OS-000392-GPOS-00172, SRG-OS-000463-GPOS-00207, SRG-OS-000465-GPOS-00209

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/chcon\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/chcon.*$"
        patterns: "*.rules"
      register: find_chcon

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_chcon.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_chcon.files | map(attribute='path') | list | first }}"
      when: find_chcon.matched > 0

    - name: Inserts/replaces the chcon rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_chcon
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80393-2
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030580

    # Inserts/replaces the chcon rule in /etc/audit/audit.rules

    - name: Inserts/replaces the chcon rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/chcon -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_execution_chcon
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80393-2
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030580

### Record File Deletion Events by User [ref]group

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat -F auid>=1000 -F auid!=4294967295 -F key=delete

contains 5 rules

#### Ensure auditd Collects File Deletion Events by User - rmdir [ref]rule

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=4294967295 -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

Identifiers: CCE-80412-0

References: FAU_GEN.1.1.c, RHEL-07-030900, SV-86827r3_rule, 5.2.14, 3.1.7, CCI-000366, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, MA-4(1)(a), Req-10.2.7, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S rmdir.*"
    	GROUP="delete"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S rmdir -F auid>=1000 -F auid!=4294967295 -F key=delete"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Ensure auditd Collects File Deletion Events by User - unlinkat [ref]rule

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=4294967295 -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

Identifiers: CCE-27206-2

References: FAU_GEN.1.1.c, RHEL-07-030920, SV-86831r3_rule, 5.2.14, 3.1.7, CCI-000366, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, MA-4(1)(a), Req-10.2.7, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S unlinkat.*"
    	GROUP="delete"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S unlinkat -F auid>=1000 -F auid!=4294967295 -F key=delete"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Ensure auditd Collects File Deletion Events by User - rename [ref]rule

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=4294967295 -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

Identifiers: CCE-27206-2

References: FAU_GEN.1.1.c, RHEL-07-030880, SV-86823r3_rule, 5.2.14, 3.1.7, CCI-000366, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, MA-4(1)(a), Req-10.2.7, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S rename.*"
    	GROUP="delete"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S rename -F auid>=1000 -F auid!=4294967295 -F key=delete"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Ensure auditd Collects File Deletion Events by User - renameat [ref]rule

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=4294967295 -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

Identifiers: CCE-80413-8

References: FAU_GEN.1.1.c, RHEL-07-030890, SV-86825r3_rule, 5.2.14, 3.1.7, CCI-000366, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, MA-4(1)(a), Req-10.2.7, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S renameat.*"
    	GROUP="delete"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S renameat -F auid>=1000 -F auid!=4294967295 -F key=delete"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Ensure auditd Collects File Deletion Events by User - unlink [ref]rule

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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=4294967295 -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 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=4294967295 -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

Identifiers: CCE-27206-2

References: FAU_GEN.1.1.c, RHEL-07-030910, SV-86829r3_rule, 5.2.14, 3.1.7, CCI-000366, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, MA-4(1)(a), Req-10.2.7, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S unlink.*"
    	GROUP="delete"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S unlink -F auid>=1000 -F auid!=4294967295 -F key=delete"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

### Record Information on the Use of Privileged Commands [ref]group

At a minimum, the audit system should collect the execution of privileged commands for all users and root.

contains 16 rules

#### Ensure auditd Collects Information on the Use of Privileged Commands - crontab [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80410-4

References: RHEL-07-030800, SV-86807r2_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/crontab\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/crontab.*$"
        patterns: "*.rules"
      register: find_crontab

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_crontab.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_crontab.files | map(attribute='path') | list | first }}"
      when: find_crontab.matched > 0

    - name: Inserts/replaces the crontab rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_crontab
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80410-4
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030800

    # Inserts/replaces the crontab rule in /etc/audit/audit.rules

    - name: Inserts/replaces the crontab rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_crontab
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80410-4
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030800

#### Ensure auditd Collects Information on the Use of Privileged Commands - passwd [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80395-7

References: FAU_GEN.1.1.c, RHEL-07-030630, SV-86773r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/passwd\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/passwd.*$"
        patterns: "*.rules"
      register: find_passwd

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_passwd.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_passwd.files | map(attribute='path') | list | first }}"
      when: find_passwd.matched > 0

    - name: Inserts/replaces the passwd rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_passwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80395-7
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030630

    # Inserts/replaces the passwd rule in /etc/audit/audit.rules

    - name: Inserts/replaces the passwd rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_passwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80395-7
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030630

#### Ensure auditd Collects Information on the Use of Privileged Commands - gpasswd [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80397-3

References: FAU_GEN.1.1.c, RHEL-07-030650, SV-86777r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/gpasswd\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/gpasswd.*$"
        patterns: "*.rules"
      register: find_gpasswd

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_gpasswd.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_gpasswd.files | map(attribute='path') | list | first }}"
      when: find_gpasswd.matched > 0

    - name: Inserts/replaces the gpasswd rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_gpasswd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80397-3
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030650

    # Inserts/replaces the gpasswd rule in /etc/audit/audit.rules

    - name: Inserts/replaces the gpasswd rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_gpasswd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80397-3
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030650

#### Ensure auditd Collects Information on the Use of Privileged Commands - unix_chkpwd [ref]rule

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/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295 -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/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295 -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 threast.
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

Identifiers: CCE-80396-5

References: FAU_GEN.1.1.c, RHEL-07-030640, SV-86775r4_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/unix_chkpwd\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/unix_chkpwd.*$"
        patterns: "*.rules"
      register: find_unix_chkpwd

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_unix_chkpwd.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_unix_chkpwd.files | map(attribute='path') | list | first }}"
      when: find_unix_chkpwd.matched > 0

    - name: Inserts/replaces the unix_chkpwd rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_unix_chkpwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80396-5
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030640

    # Inserts/replaces the unix_chkpwd rule in /etc/audit/audit.rules

    - name: Inserts/replaces the unix_chkpwd rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_unix_chkpwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80396-5
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030640

#### Ensure auditd Collects Information on the Use of Privileged Commands - postqueue [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80407-0

References: RHEL-07-030770, SV-86801r2_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/postqueue\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/postqueue -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/postqueue.*$"
        patterns: "*.rules"
      register: find_postqueue

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_postqueue.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_postqueue.files | map(attribute='path') | list | first }}"
      when: find_postqueue.matched > 0

    - name: Inserts/replaces the postqueue rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/postqueue -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_postqueue
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80407-0
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030770

    # Inserts/replaces the postqueue rule in /etc/audit/audit.rules

    - name: Inserts/replaces the postqueue rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/postqueue -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_postqueue
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80407-0
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030770

#### Ensure auditd Collects Information on the Use of Privileged Commands - userhelper [ref]rule

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/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295 -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/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295 -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 threast.
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

Identifiers: CCE-80399-9

References: FAU_GEN.1.1.c, RHEL-07-030670, SV-86781r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/userhelper\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/userhelper.*$"
        patterns: "*.rules"
      register: find_userhelper

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_userhelper.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_userhelper.files | map(attribute='path') | list | first }}"
      when: find_userhelper.matched > 0

    - name: Inserts/replaces the userhelper rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_userhelper
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80399-9
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030670

    # Inserts/replaces the userhelper rule in /etc/audit/audit.rules

    - name: Inserts/replaces the userhelper rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_userhelper
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80399-9
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030670

#### Ensure auditd Collects Information on the Use of Privileged Commands - ssh-keysign [ref]rule

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!=4294967295 -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/key-sign -F perm=x -F auid>=1000 -F auid!=4294967295 -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 threast.
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

Identifiers: CCE-80408-8

References: FAU_GEN.1.1.c, RHEL-07-030780, SV-86803r2_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/libexec/openssh/ssh-keysign\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/libexec/openssh/ssh-keysign -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/libexec/openssh/ssh-keysign.*$"
        patterns: "*.rules"
      register: find_ssh_keysign

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_ssh_keysign.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_ssh_keysign.files | map(attribute='path') | list | first }}"
      when: find_ssh_keysign.matched > 0

    - name: Inserts/replaces the ssh_keysign rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/libexec/openssh/ssh-keysign -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_ssh_keysign
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80408-8
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030780

    # Inserts/replaces the ssh_keysign rule in /etc/audit/audit.rules

    - name: Inserts/replaces the ssh_keysign rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/libexec/openssh/ssh-keysign -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_ssh_keysign
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80408-8
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030780

#### Ensure auditd Collects Information on the Use of Privileged Commands - sudo [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80401-3

References: FAU_GEN.1.1.c, RHEL-07-030690, SV-86785r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/sudo\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/sudo.*$"
        patterns: "*.rules"
      register: find_sudo

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_sudo.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_sudo.files | map(attribute='path') | list | first }}"
      when: find_sudo.matched > 0

    - name: Inserts/replaces the sudo rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_sudo
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80401-3
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030690

    # Inserts/replaces the sudo rule in /etc/audit/audit.rules

    - name: Inserts/replaces the sudo rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_sudo
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80401-3
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030690

#### Ensure auditd Collects Information on the Use of Privileged Commands - su [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80400-5

References: FAU_GEN.1.1.c, RHEL-07-030680, SV-86783r4_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/su\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/su -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/su.*$"
        patterns: "*.rules"
      register: find_su

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_su.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_su.files | map(attribute='path') | list | first }}"
      when: find_su.matched > 0

    - name: Inserts/replaces the su rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/su -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_su
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80400-5
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030680

    # Inserts/replaces the su rule in /etc/audit/audit.rules

    - name: Inserts/replaces the su rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/su -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_su
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80400-5
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030680

#### Ensure auditd Collects Information on the Use of Privileged Commands - pam_timestamp_check [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80411-2

References: RHEL-07-030810, SV-86809r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/pam_timestamp_check\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/pam_timestamp_check -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/pam_timestamp_check.*$"
        patterns: "*.rules"
      register: find_pam_timestamp_check

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_pam_timestamp_check.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_pam_timestamp_check.files | map(attribute='path') | list | first }}"
      when: find_pam_timestamp_check.matched > 0

    - name: Inserts/replaces the pam_timestamp_check rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/pam_timestamp_check -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_pam_timestamp_check
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80411-2
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030810

    # Inserts/replaces the pam_timestamp_check rule in /etc/audit/audit.rules

    - name: Inserts/replaces the pam_timestamp_check rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/pam_timestamp_check -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_pam_timestamp_check
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80411-2
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030810

#### Ensure auditd Collects Information on the Use of Privileged Commands - sudoedit [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80402-1

References: FAU_GEN.1.1.c, RHEL-07-030730, SV-86793r4_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/sudoedit\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/sudoedit.*$"
        patterns: "*.rules"
      register: find_sudoedit

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_sudoedit.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_sudoedit.files | map(attribute='path') | list | first }}"
      when: find_sudoedit.matched > 0

    - name: Inserts/replaces the sudoedit rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_sudoedit
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80402-1
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030730

    # Inserts/replaces the sudoedit rule in /etc/audit/audit.rules

    - name: Inserts/replaces the sudoedit rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_sudoedit
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80402-1
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030730

#### Ensure auditd Collects Information on the Use of Privileged Commands - newgrp [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80403-9

References: FAU_GEN.1.1.c, RHEL-07-030710, SV-86789r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/newgrp\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/newgrp.*$"
        patterns: "*.rules"
      register: find_newgrp

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_newgrp.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_newgrp.files | map(attribute='path') | list | first }}"
      when: find_newgrp.matched > 0

    - name: Inserts/replaces the newgrp rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_newgrp
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80403-9
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030710

    # Inserts/replaces the newgrp rule in /etc/audit/audit.rules

    - name: Inserts/replaces the newgrp rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_newgrp
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80403-9
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030710

#### Ensure auditd Collects Information on the Use of Privileged Commands - chage [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80398-1

References: RHEL-07-030660, SV-86779r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/chage\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/chage.*$"
        patterns: "*.rules"
      register: find_chage

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_chage.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_chage.files | map(attribute='path') | list | first }}"
      when: find_chage.matched > 0

    - name: Inserts/replaces the chage rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_chage
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80398-1
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030660

    # Inserts/replaces the chage rule in /etc/audit/audit.rules

    - name: Inserts/replaces the chage rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_chage
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80398-1
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030660

#### Ensure auditd Collects Information on the Use of Privileged Commands - umount [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80405-4

References: RHEL-07-030750, SV-86797r4_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/umount\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/umount -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/umount.*$"
        patterns: "*.rules"
      register: find_umount

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_umount.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_umount.files | map(attribute='path') | list | first }}"
      when: find_umount.matched > 0

    - name: Inserts/replaces the umount rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/umount -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_umount
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80405-4
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030750

    # Inserts/replaces the umount rule in /etc/audit/audit.rules

    - name: Inserts/replaces the umount rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/umount -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_umount
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80405-4
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030750

#### Ensure auditd Collects Information on the Use of Privileged Commands - postdrop [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80406-2

References: RHEL-07-030760, SV-86799r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/sbin/postdrop\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/sbin/postdrop -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/sbin/postdrop.*$"
        patterns: "*.rules"
      register: find_postdrop

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_postdrop.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_postdrop.files | map(attribute='path') | list | first }}"
      when: find_postdrop.matched > 0

    - name: Inserts/replaces the postdrop rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/sbin/postdrop -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_postdrop
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80406-2
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030760

    # Inserts/replaces the postdrop rule in /etc/audit/audit.rules

    - name: Inserts/replaces the postdrop rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/sbin/postdrop -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_postdrop
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80406-2
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030760

#### Ensure auditd Collects Information on the Use of Privileged Commands - chsh [ref]rule

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!=4294967295 -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!=4294967295 -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 threast.
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

Identifiers: CCE-80404-7

References: RHEL-07-030720, SV-86791r3_rule, 3.1.7, CCI-000135, CCI-000172, CCI-002884, 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), AU-3(1), AU-12(c), SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    PATTERN="-a always,exit -F path=/usr/bin/chsh\\s*.*"
    GROUP="privileged"
    FULL_RULE="-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | restrict

    # Inserts/replaces the rule in /etc/audit/rules.d

    - name: Search /etc/audit/rules.d for audit rule entries
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "^.*path=/usr/bin/chsh.*$"
        patterns: "*.rules"
      register: find_chsh

    - name: Use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_chsh.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_chsh.files | map(attribute='path') | list | first }}"
      when: find_chsh.matched > 0

    - name: Inserts/replaces the chsh rule in rules.d
      lineinfile:
        path: "{{ all_files[0] }}"
        line: '-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_chsh
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80404-7
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030720

    # Inserts/replaces the chsh rule in /etc/audit/audit.rules

    - name: Inserts/replaces the chsh rule in audit.rules
      lineinfile:
        path: /etc/audit/audit.rules
        line: '-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=4294967295 -F key=privileged'
        create: yes
      tags:
        - audit_rules_privileged_commands_chsh
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80404-7
        - NIST-800-53-AU-3(1)
        - NIST-800-53-AU-12(c)
        - NIST-800-171-3.1.7
        - DISA-STIG-RHEL-07-030720

### Record Unauthorized Access Attempts Events to Files (unsuccessful) [ref]group

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!=4294967295 -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!=4294967295 -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!=4294967295 -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!=4294967295 -F key=access

contains 6 rules

#### Record Unauthorized Access Attempts to Files (unsuccessful) - open [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80386-6

References: FAU_GEN.1.1.c, RHEL-07-030510, SV-86749r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S open -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S open -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S open -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit open tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_open

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_open.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_open.files | map(attribute='path') | list | first }}"
      when: find_open.matched > 0

    - name: Inserts/replaces the open rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_open
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80386-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030510

    - name: Inserts/replaces the open rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_open
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80386-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030510
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the open rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_open
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80386-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030510

    - name: Inserts/replaces the open rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_open
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80386-6
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030510

#### Record Unauthorized Access Attempts to Files (unsuccessful) - open_by_handle_at [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80388-2

References: FAU_GEN.1.1.c, RHEL-07-030530, SV-86753r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S open_by_handle_at -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S open_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S open_by_handle_at -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit open_by_handle_at tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_open_by_handle_at

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_open_by_handle_at.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_open_by_handle_at.files | map(attribute='path') | list | first }}"
      when: find_open_by_handle_at.matched > 0

    - name: Inserts/replaces the open_by_handle_at rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S open_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_open_by_handle_at
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80388-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030530

    - name: Inserts/replaces the open_by_handle_at rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S open_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_open_by_handle_at
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80388-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030530
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the open_by_handle_at rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S open_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_open_by_handle_at
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80388-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030530

    - name: Inserts/replaces the open_by_handle_at rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S open_by_handle_at -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S open_by_handle_at -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_open_by_handle_at
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80388-2
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030530

#### Record Unauthorized Access Attempts to Files (unsuccessful) - creat [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80385-8

References: FAU_GEN.1.1.c, RHEL-07-030500, SV-86747r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S creat -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S creat -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit creat tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_creat

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_creat.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_creat.files | map(attribute='path') | list | first }}"
      when: find_creat.matched > 0

    - name: Inserts/replaces the creat rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_creat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80385-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030500

    - name: Inserts/replaces the creat rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_creat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80385-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030500
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the creat rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_creat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80385-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030500

    - name: Inserts/replaces the creat rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_creat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80385-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030500

#### Record Unauthorized Access Attempts to Files (unsuccessful) - ftruncate [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S ftruncate -F exiu=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80390-8

References: FAU_GEN.1.1.c, RHEL-07-030550, SV-86757r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S ftruncate -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S ftruncate -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit ftruncate tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_ftruncate

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_ftruncate.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_ftruncate.files | map(attribute='path') | list | first }}"
      when: find_ftruncate.matched > 0

    - name: Inserts/replaces the ftruncate rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_ftruncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80390-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030550

    - name: Inserts/replaces the ftruncate rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_ftruncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80390-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030550
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the ftruncate rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_ftruncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80390-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030550

    - name: Inserts/replaces the ftruncate rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_ftruncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80390-8
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030550

#### Record Unauthorized Access Attempts to Files (unsuccessful) - truncate [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80389-0

References: FAU_GEN.1.1.c, RHEL-07-030540, SV-86755r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S truncate -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S truncate -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit truncate tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_truncate

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_truncate.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_truncate.files | map(attribute='path') | list | first }}"
      when: find_truncate.matched > 0

    - name: Inserts/replaces the truncate rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_truncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80389-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030540

    - name: Inserts/replaces the truncate rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_truncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80389-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030540
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the truncate rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_truncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80389-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030540

    - name: Inserts/replaces the truncate rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_truncate
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80389-0
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030540

#### Record Unauthorized Access Attempts to Files (unsuccessful) - openat [ref]rule

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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -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!=4294967295 -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access

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

Identifiers: CCE-80387-4

References: FAU_GEN.1.1.c, RHEL-07-030520, SV-86751r3_rule, 5.2.10, 3.1.7, CCI-000172, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.4, Req-10.2.1, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S openat -F exit=-EACCES.*"
    	GROUP="access"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
            PATTERN="-a always,exit -F arch=$ARCH -S openat -F exit=-EPERM.*"
            GROUP="access"
            FULL_RULE="-a always,exit -F arch=$ARCH -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
            # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

            fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
            fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit openat tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other DAC audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-F key=perm_mod$"
        patterns: "*.rules"
      register: find_openat

    - name: If existing DAC ruleset not found, use /etc/audit/rules.d/access.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/access.rules
      when: find_openat.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_openat.files | map(attribute='path') | list | first }}"
      when: find_openat.matched > 0

    - name: Inserts/replaces the openat rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_openat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80387-4
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030520

    - name: Inserts/replaces the openat rule in rules.d when on x86_64
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "{{ item }}"
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_openat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80387-4
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030520
    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the openat rule in /etc/audit/audit.rules when on x86
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      tags:
        - audit_rules_unsuccessful_file_modification_openat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80387-4
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030520

    - name: Inserts/replaces the openat rule in audit.rules when on x86_64
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
        create: yes
      with_items:
        - "-a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -F key=access"
        - "-a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -F key=access"
      when: audit_arch == 'b64'
      tags:
        - audit_rules_unsuccessful_file_modification_openat
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80387-4
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.4
        - PCI-DSS-Req-10.2.1
        - DISA-STIG-RHEL-07-030520

#### Record Events that Modify User/Group Information - /etc/shadow [ref]rule

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 capture events that modify account changes:

    -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` file, in order to capture events that modify account changes:

    -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

Identifiers: CCE-80431-0

References: FAU_GEN.1.1.c, RHEL-07-030873, SV-87823r3_rule, 5.2.5, 5.4.1.1, 3.1.7, CCI-000018, CCI-000172, CCI-001403, CCI-002130, 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), AC-2(4), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.5, SRG-OS-000004-GPOS-00004

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/shadow" "wa" "audit_rules_usergroup_modification"
    fix_audit_watch_rule "augenrules" "/etc/shadow" "wa" "audit_rules_usergroup_modification"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit shadow tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k audit_rules_usergroup_modification$"
        patterns: "*.rules"
      register: find_shadow

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_shadow.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_shadow.files | map(attribute='path') | list | first }}"
      when: find_shadow.matched > 0

    - name: Inserts/replaces the shadow rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /etc/shadow -p wa -k audit_rules_usergroup_modification"
        create: yes
      tags:
        - audit_rules_usergroup_modification_shadow
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80431-0
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030873

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the shadow rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /etc/shadow -p wa -k audit_rules_usergroup_modification"
      tags:
        - audit_rules_usergroup_modification_shadow
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80431-0
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030873

#### Record Attempts to Alter Process and Session Initiation Information [ref]rule

The audit system already collects process information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to watch for attempted manual edits of files involved in storing such process information:

    -w /var/run/utmp -p wa -k session
    -w /var/log/btmp -p wa -k session
    -w /var/log/wtmp -p wa -k session

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file in order to watch for attempted manual edits of files involved in storing such process information:

    -w /var/run/utmp -p wa -k session
    -w /var/log/btmp -p wa -k session
    -w /var/log/wtmp -p wa -k session

Rationale:

Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.

Severity: unknown

Identifiers: CCE-27301-1

References: FAU_GEN.1.1.c, 5.2.9, 5.4.1.1, 3.1.7, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.3

Remediation Shell script: (show)

    # Perform the remediation
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/run/utmp" "wa" "session"
    fix_audit_watch_rule "augenrules" "/var/run/utmp" "wa" "session"
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/log/btmp" "wa" "session"
    fix_audit_watch_rule "augenrules" "/var/log/btmp" "wa" "session"
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/var/log/wtmp" "wa" "session"
    fix_audit_watch_rule "augenrules" "/var/log/wtmp" "wa" "session"

#### Shutdown System When Auditing Failures Occur [ref]rule

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`:

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

Identifiers: CCE-80381-7

References: RHEL-07-030010, SV-86705r3_rule, 3.3.1, 3.3.4, CCI-000139, 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), AU-5, AU-5(a), SRG-OS-000046-GPOS-00022, SRG-OS-000047-GPOS-00023

Remediation Shell script: (show)

    # Traverse all of:
    #
    # /etc/audit/audit.rules,			(for auditctl case)
    # /etc/audit/rules.d/*.rules			(for augenrules case)
    #
    # files to check if '-f .*' setting is present in that '*.rules' file already.
    # If found, delete such occurrence since auditctl(8) manual page instructs the
    # '-f 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 '-f 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 to halt system upon audit failure per security requirements' >> $AUDIT_FILE
    	echo '-f 2' >> $AUDIT_FILE
    done

#### Ensure auditd Collects System Administrator Actions [ref]rule

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 line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/sudoers -p wa -k actions
    -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 line to `/etc/audit/audit.rules` file:

    -w /etc/sudoers -p wa -k actions
    -w /etc/sudoers.d/ -p wa -k actions

Rationale:

The actions taken by system administrators should be audited to keep a record of what was executed on the system, as well as, for accountability purposes.

Severity: unknown

Identifiers: CCE-27461-3

References: FAU_GEN.1.1.c, RHEL-07-030700, SV-86787r4_rule, 5.4.1.1, 3.1.7, CCI-000126, CCI-000130, CCI-000135, CCI-000172, CCI-002884, 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), AC-2(7)(b), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), iAU-3(1), AU-12(a), AU-12(c), IR-5, Req-10.2.2, Req-10.2.5.b, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/sudoers" "wa" "actions"
    fix_audit_watch_rule "augenrules" "/etc/sudoers" "wa" "actions"

#### Record Events that Modify the System's Network Environment [ref]rule

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S sethostname,setdomainname -F key=audit_rules_networkconfig_modification
    -w /etc/issue -p wa -k audit_rules_networkconfig_modification
    -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
    -w /etc/hosts -p wa -k audit_rules_networkconfig_modification
    -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file, setting ARCH to either b32 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S sethostname,setdomainname -F key=audit_rules_networkconfig_modification
    -w /etc/issue -p wa -k audit_rules_networkconfig_modification
    -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
    -w /etc/hosts -p wa -k audit_rules_networkconfig_modification
    -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification

Rationale:

The network environment should not be modified by anything other than administrator action. Any change to network parameters should be audited.

Severity: unknown

Identifiers: CCE-27076-9

References: 5.2.6, 5.4.1.1, 3.1.7, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S .* -k *"
    	# Use escaped BRE regex to specify rule group
    	GROUP="set\(host\|domain\)name"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S sethostname -S setdomainname -k audit_rules_networkconfig_modification"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

    # Then perform the remediations for the watch rules
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/issue" "wa" "audit_rules_networkconfig_modification"
    fix_audit_watch_rule "augenrules" "/etc/issue" "wa" "audit_rules_networkconfig_modification"
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/issue.net" "wa" "audit_rules_networkconfig_modification"
    fix_audit_watch_rule "augenrules" "/etc/issue.net" "wa" "audit_rules_networkconfig_modification"
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/hosts" "wa" "audit_rules_networkconfig_modification"
    fix_audit_watch_rule "augenrules" "/etc/hosts" "wa" "audit_rules_networkconfig_modification"
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/sysconfig/network" "wa" "audit_rules_networkconfig_modification"
    fix_audit_watch_rule "augenrules" "/etc/sysconfig/network" "wa" "audit_rules_networkconfig_modification"

#### Record Events that Modify User/Group Information - /etc/gshadow [ref]rule

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 capture events that modify account changes:

    -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` file, in order to capture events that modify account changes:

    -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

Identifiers: CCE-80432-8

References: FAU_GEN.1.1.c, RHEL-07-030872, SV-87819r3_rule, 5.2.5, 5.4.1.1, 3.1.7, CCI-000018, CCI-000172, CCI-001403, CCI-002130, 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), AC-2(4), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.5, SRG-OS-000004-GPOS-00004

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/gshadow" "wa" "audit_rules_usergroup_modification"
    fix_audit_watch_rule "augenrules" "/etc/gshadow" "wa" "audit_rules_usergroup_modification"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit gshadow tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k audit_rules_usergroup_modification$"
        patterns: "*.rules"
      register: find_gshadow

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_gshadow.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_gshadow.files | map(attribute='path') | list | first }}"
      when: find_gshadow.matched > 0

    - name: Inserts/replaces the gshadow rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /etc/gshadow -p wa -k audit_rules_usergroup_modification"
        create: yes
      tags:
        - audit_rules_usergroup_modification_gshadow
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80432-8
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030872

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the gshadow rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /etc/gshadow -p wa -k audit_rules_usergroup_modification"
      tags:
        - audit_rules_usergroup_modification_gshadow
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80432-8
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030872

#### Record Events that Modify User/Group Information - /etc/security/opasswd [ref]rule

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 capture events that modify account changes:

    -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` file, in order to capture events that modify account changes:

    -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

Identifiers: CCE-80430-2

References: FAU_GEN.1.1.c, RHEL-07-030874, SV-87825r4_rule, 5.2.5, 5.4.1.1, 3.1.7, CCI-000018, CCI-000172, CCI-001403, CCI-002130, 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), AC-2(4), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.5, SRG-OS-000004-GPOS-00004

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/security/opasswd" "wa" "audit_rules_usergroup_modification"
    fix_audit_watch_rule "augenrules" "/etc/security/opasswd" "wa" "audit_rules_usergroup_modification"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit opasswd tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k audit_rules_usergroup_modification$"
        patterns: "*.rules"
      register: find_opasswd

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_opasswd.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_opasswd.files | map(attribute='path') | list | first }}"
      when: find_opasswd.matched > 0

    - name: Inserts/replaces the opasswd rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification"
        create: yes
      tags:
        - audit_rules_usergroup_modification_opasswd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80430-2
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030874

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the opasswd rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification"
      tags:
        - audit_rules_usergroup_modification_opasswd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80430-2
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030874

#### Ensure auditd Collects Information on Exporting to Media (successful) [ref]rule

At a minimum, the audit system should collect media exportation events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S mount -F auid>=1000 -F auid!=4294967295 -F key=export

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 or b64 as appropriate for your system:

    -a always,exit -F arch=ARCH -S mount -F auid>=1000 -F auid!=4294967295 -F key=export

Rationale:

The unauthorized exportation of data to external media could result in an information leak where classified information, Privacy Act information, and intellectual property could be lost. An audit trail should be created each time a filesystem is mounted to help identify and guard against information loss.

Severity: medium

Identifiers: CCE-27447-2

References: RHEL-07-030740, SV-86795r5_rule, 5.2.13, 5.4.1.1, 3.1.7, CCI-000135, CCI-002884, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-3(1), AU-12(a), AU-12(c), IR-5, Req-10.2.7, SRG-OS-000042-GPOS-00020, SRG-OS-000392-GPOS-00172

Remediation Shell script: (show)

    # 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
    	PATTERN="-a always,exit -F arch=$ARCH -S .* -F auid>=1000 -F auid!=4294967295 -k *"
    	GROUP="mount"
    	FULL_RULE="-a always,exit -F arch=$ARCH -S mount -F auid>=1000 -F auid!=4294967295 -k export"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix syscall audit rule for given system call. It is
    # based on example audit syscall rule definitions as outlined in
    # /usr/share/doc/audit-2.3.7/stig.rules file provided with the audit
    # package. It will combine multiple system calls belonging to the same
    # syscall group into one audit rule (rather than to create audit rule per
    # different system call) to avoid audit infrastructure performance penalty
    # in the case of 'one-audit-rule-definition-per-one-system-call'. See:
    #
    #   https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html
    #
    # for further details.
    #
    # Expects five arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules
    # * audit rules' pattern		audit rule skeleton for same syscall
    # * syscall group			greatest common string this rule shares
    # 					with other rules from the same group
    # * architecture			architecture this rule is intended for
    # * full form of new rule to add	expected full form of audit rule as to be
    # 					added into audit.rules file
    #
    # Note: The 2-th up to 4-th arguments are used to determine how many existing
    # audit rules will be inspected for resemblance with the new audit rule
    # (5-th argument) the function is going to add. The rule's similarity check
    # is performed to optimize audit.rules definition (merge syscalls of the same
    # group into one rule) to avoid the "single-syscall-per-audit-rule" performance
    # penalty.
    #
    # Example call:
    #
    #	See e.g. 'audit_rules_file_deletion_events.sh' remediation script
    #
    function fix_audit_syscall_rule {

    # Load function arguments into local variables
    local tool="$1"
    local pattern="$2"
    local group="$3"
    local arch="$4"
    local full_rule="$5"

    # Check sanity of the input
    if [ $# -ne "5" ]
    then
    	echo "Usage: fix_audit_syscall_rule 'tool' 'pattern' 'group' 'arch' 'full rule'"
    	echo "Aborting."
    	exit 1
    fi

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

    retval=0

    # First check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	return 1
    # If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # file to the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules' )
    # 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
    elif [ "$tool" == 'augenrules' ]
    then
    	# Extract audit $key from audit rule so we can use it later
    	key=$(expr "$full_rule" : '.*-k[[:space:]]\([^[:space:]]\+\)' '|' "$full_rule" : '.*-F[[:space:]]key=\([^[:space:]]\+\)')
    	# Check if particular audit rule is already defined
    	IFS=$'\n' matches=($(sed -s -n -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d;F" /etc/audit/rules.d/*.rules))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS
    	for match in "${matches[@]}"
    	do
    		files_to_inspect=("${files_to_inspect[@]}" "${match}")
    	done
    	# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    fi

    #
    # Indicator that we want to append $full_rule into $audit_file by default
    local append_expected_rule=0

    for audit_file in "${files_to_inspect[@]}"
    do

    	# Filter existing $audit_file rules' definitions to select those that:
    	# * follow the rule pattern, and
    	# * meet the hardware architecture requirement, and
    	# * are current syscall group specific
    	IFS=$'\n' existing_rules=($(sed -e "\;${pattern};!d" -e "/${arch}/!d" -e "/${group}/!d"  "$audit_file"))
    	if [ $? -ne 0 ]
    	then
    		retval=1
    	fi
    	# Reset IFS back to default
    	unset IFS

    	# Process rules found case-by-case
    	for rule in "${existing_rules[@]}"
    	do
    		# Found rule is for same arch & key, but differs (e.g. in count of -S arguments)
    		if [ "${rule}" != "${full_rule}" ]
    		then
    			# If so, isolate just '(-S \w)+' substring of that rule
    			rule_syscalls=$(echo $rule | grep -o -P '(-S \w+ )+')
    			# Check if list of '-S syscall' arguments of that rule is subset
    			# of '-S syscall' list of expected $full_rule
    			if grep -q -- "$rule_syscalls" <<< "$full_rule"
    			then
    				# Rule is covered (i.e. the list of -S syscalls for this rule is
    				# subset of -S syscalls of $full_rule => existing rule can be deleted
    				# Thus delete the rule from audit.rules & our array
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				existing_rules=("${existing_rules[@]//$rule/}")
    			else
    				# Rule isn't covered by $full_rule - it besides -S syscall arguments
    				# for this group contains also -S syscall arguments for other syscall
    				# group. Example: '-S lchown -S fchmod -S fchownat' => group='chown'
    				# since 'lchown' & 'fchownat' share 'chown' substring
    				# Therefore:
    				# * 1) delete the original rule from audit.rules
    				# (original '-S lchown -S fchmod -S fchownat' rule would be deleted)
    				# * 2) delete the -S syscall arguments for this syscall group, but
    				# keep those not belonging to this syscall group
    				# (original '-S lchown -S fchmod -S fchownat' would become '-S fchmod'
    				# * 3) append the modified (filtered) rule again into audit.rules
    				# if the same rule not already present
    				#
    				# 1) Delete the original rule
    				sed -i -e "\;${rule};d" "$audit_file"
    				if [ $? -ne 0 ]
    				then
    					retval=1
    				fi
    				# 2) Delete syscalls for this group, but keep those from other groups
    				# Convert current rule syscall's string into array splitting by '-S' delimiter
    				IFS=$'-S' read -a rule_syscalls_as_array <<< "$rule_syscalls"
    				# Reset IFS back to default
    				unset IFS
    				# Declare new empty string to hold '-S syscall' arguments from other groups
    				new_syscalls_for_rule=''
    				# Walk through existing '-S syscall' arguments
    				for syscall_arg in "${rule_syscalls_as_array[@]}"
    				do
    					# Skip empty $syscall_arg values
    					if [ "$syscall_arg" == '' ]
    					then
    						continue
    					fi
    					# If the '-S syscall' doesn't belong to current group add it to the new list
    					# (together with adding '-S' delimiter back for each of such item found)
    					if grep -q -v -- "$group" <<< "$syscall_arg"
    					then
    						new_syscalls_for_rule="$new_syscalls_for_rule -S $syscall_arg"
    					fi
    				done
    				# Replace original '-S syscall' list with the new one for this rule
    				updated_rule=${rule//$rule_syscalls/$new_syscalls_for_rule}
    				# Squeeze repeated whitespace characters in rule definition (if any) into one
    				updated_rule=$(echo "$updated_rule" | tr -s '[:space:]')
    				# 3) Append the modified / filtered rule again into audit.rules
    				#    (but only in case it's not present yet to prevent duplicate definitions)
    				if ! grep -q -- "$updated_rule" "$audit_file"
    				then
    					echo "$updated_rule" >> "$audit_file"
    				fi
    			fi
    		else
    			# $audit_file already contains the expected rule form for this
    			# architecture & key => don't insert it second time
    			append_expected_rule=1
    		fi
    	done

    	# We deleted all rules that were subset of the expected one for this arch & key.
    	# Also isolated rules containing system calls not from this system calls group.
    	# Now append the expected rule if it's not present in $audit_file yet
    	if [[ ${append_expected_rule} -eq "0" ]]
    	then
    		echo "$full_rule" >> "$audit_file"
    	fi
    done

    return $retval

    }

    	fix_audit_syscall_rule "auditctl" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    	fix_audit_syscall_rule "augenrules" "$PATTERN" "$GROUP" "$ARCH" "$FULL_RULE"
    done

#### Make the auditd Configuration Immutable [ref]rule

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

Identifiers: CCE-27097-5

References: 4.1.18, 5.4.1.1, 3.3.1, 3.4.3, 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), AC-6, AU-1(b), AU-2(a), AU-2(c), AU-2(d), IR-5, Req-10.5.2

Remediation Shell script: (show)

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

#### Record Events that Modify User/Group Information - /etc/passwd [ref]rule

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 capture events that modify account changes:

    -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` file, in order to capture events that modify account changes:

    -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

Identifiers: CCE-80435-1

References: FAU_GEN.1.1.c, RHEL-07-030870, SV-86821r4_rule, 5.2.5, 5.4.1.1, 3.1.7, CCI-000018, CCI-000172, CCI-001403, CCI-002130, 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), AC-2(4), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.5, SRG-OS-000004-GPOS-00004, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000476-GPOS-00221

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/passwd" "wa" "audit_rules_usergroup_modification"
    fix_audit_watch_rule "augenrules" "/etc/passwd" "wa" "audit_rules_usergroup_modification"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit passwd tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k audit_rules_usergroup_modification$"
        patterns: "*.rules"
      register: find_passwd

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_passwd.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_passwd.files | map(attribute='path') | list | first }}"
      when: find_passwd.matched > 0

    - name: Inserts/replaces the passwd rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /etc/passwd -p wa -k audit_rules_usergroup_modification"
        create: yes
      tags:
        - audit_rules_usergroup_modification_passwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80435-1
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030870

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the passwd rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /etc/passwd -p wa -k audit_rules_usergroup_modification"
      tags:
        - audit_rules_usergroup_modification_passwd
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80435-1
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030870

#### Record Events that Modify the System's Mandatory Access Controls [ref]rule

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`:

    -w /etc/selinux/ -p wa -k MAC-policy

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -w /etc/selinux/ -p wa -k MAC-policy

Rationale:

The system's mandatory access policy (SELinux) should not be arbitrarily changed by anything other than administrator action. All changes to MAC policy should be audited.

Severity: unknown

Identifiers: CCE-27168-4

References: FAU_GEN.1.1.c, 5.2.7, 5.4.1.1, 3.1.8, 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), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.5.5

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/selinux/" "wa" "MAC-policy"
    fix_audit_watch_rule "augenrules" "/etc/selinux/" "wa" "MAC-policy"

#### Record Events that Modify User/Group Information - /etc/group [ref]rule

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 capture events that modify account changes:

    -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` file, in order to capture events that modify account changes:

    -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

Identifiers: CCE-80433-6

References: FAU_GEN.1.1.c, RHEL-07-030871, SV-87817r2_rule, 5.2.5, 5.4.1.1, 3.1.7, CCI-000018, CCI-000172, CCI-001403, CCI-002130, 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), AC-2(4), AC-17(7), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-12(a), AU-12(c), IR-5, Req-10.2.5, SRG-OS-000004-GPOS-00004

Remediation Shell script: (show)

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # Function to fix audit file system object watch rule for given path:
    # * if rule exists, also verifies the -w bits match the requirements
    # * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
    #   audit rules file, depending on the tool which was used to load audit rules
    #
    # Expects four arguments (each of them is required) in the form of:
    # * audit tool				tool used to load audit rules,
    # 					either 'auditctl', or 'augenrules'
    # * path                        	value of -w audit rule's argument
    # * required access bits        	value of -p audit rule's argument
    # * key                         	value of -k audit rule's argument
    #
    # Example call:
    #
    #       fix_audit_watch_rule "auditctl" "/etc/localtime" "wa" "audit_time_rules"
    #
    function fix_audit_watch_rule {

    # Load function arguments into local variables
    local tool="$1"
    local path="$2"
    local required_access_bits="$3"
    local key="$4"

    # Check sanity of the input
    if [ $# -ne "4" ]
    then
    	echo "Usage: fix_audit_watch_rule 'tool' 'path' 'bits' 'key'"
    	echo "Aborting."
    	exit 1
    fi

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

    # Check sanity of the specified audit tool
    if [ "$tool" != 'auditctl' ] && [ "$tool" != 'augenrules' ]
    then
    	echo "Unknown audit rules loading tool: $1. Aborting."
    	echo "Use either 'auditctl' or 'augenrules'!"
    	exit 1
    # If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
    # into the list of files to be inspected
    elif [ "$tool" == 'auditctl' ]
    then
    	files_to_inspect=("${files_to_inspect[@]}" '/etc/audit/audit.rules')
    # If the audit is 'augenrules', then check if rule is already defined
    # If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
    # If rule isn't defined, add '/etc/audit/rules.d/$key.rules' to list of files for inspection.
    elif [ "$tool" == 'augenrules' ]
    then
    	# Case when particular audit rule is already defined in some of /etc/audit/rules.d/*.rules file
    	# Get pair -- filepath : matching_row into @matches array
    	IFS=$'\n' matches=($(grep -P "[\s]*-w[\s]+$path" /etc/audit/rules.d/*.rules))
    	# Reset IFS back to default
    	unset IFS
    	# 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=("${files_to_inspect[@]}" "$rulesd_audit_file")
    	done
    	# Case when particular audit rule isn't defined yet
    	if [ ${#files_to_inspect[@]} -eq "0" ]
    	then
    		# Append '/etc/audit/rules.d/$key.rules' into list of files for inspection
    		files_to_inspect="/etc/audit/rules.d/$key.rules"
    		# If the $key.rules file doesn't exist yet, create it with correct permissions
    		if [ ! -e "$files_to_inspect" ]
    		then
    			touch "$files_to_inspect"
    			chmod 0640 "$files_to_inspect"
    		fi
    	fi
    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]+$path" "$audit_rules_file"
    	then
    		# Rule is found => verify yet if existing rule definition contains
    		# all of the required access type bits

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

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

    fix_audit_watch_rule "auditctl" "/etc/group" "wa" "audit_rules_usergroup_modification"
    fix_audit_watch_rule "augenrules" "/etc/group" "wa" "audit_rules_usergroup_modification"

Remediation Ansible snippet: (show)

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

    #
    # What architecture are we on?
    #
    - name: Set architecture for audit group tasks
      set_fact:
        audit_arch: "b{{ ansible_architecture | regex_replace('.*(\\d\\d$)','\\1') }}"

    #
    # Inserts/replaces the rule in /etc/audit/rules.d
    #
    - name: Search /etc/audit/rules.d for other user/group modification audit rules
      find:
        paths: "/etc/audit/rules.d"
        recurse: no
        contains: "-k audit_rules_usergroup_modification$"
        patterns: "*.rules"
      register: find_group

    - name: If existing user/group modification ruleset not found, use /etc/audit/rules.d/privileged.rules as the recipient for the rule
      set_fact:
        all_files:
          - /etc/audit/rules.d/privileged.rules
      when: find_group.matched == 0

    - name: Use matched file as the recipient for the rule
      set_fact:
        all_files:
          - "{{ find_group.files | map(attribute='path') | list | first }}"
      when: find_group.matched > 0

    - name: Inserts/replaces the group rule in rules.d when on x86
      lineinfile:
        path: "{{ all_files[0] }}"
        line: "-w /etc/group -p wa -k audit_rules_usergroup_modification"
        create: yes
      tags:
        - audit_rules_usergroup_modification_group
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80433-6
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030871

    #
    # Inserts/replaces the rule in /etc/audit/audit.rules
    #
    - name: Inserts/replaces the group rule in /etc/audit/audit.rules
      lineinfile:
        line: "{{ item }}"
        state: present
        dest: /etc/audit/audit.rules
      with_items:
        - "-w /etc/group -p wa -k audit_rules_usergroup_modification"
      tags:
        - audit_rules_usergroup_modification_group
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-80433-6
        - NIST-800-53-AC-2(4)
        - NIST-800-53-AC-17(7)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-IR-5
        - NIST-800-171-3.1.7
        - PCI-DSS-Req-10.2.5
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030871

#### Enable Auditing for Processes Which Start Prior to the Audit Daemon [ref]rule

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 in `/etc/default/grub`, in the manner below:

    GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=VolGroup/LogVol06 rd.lvm.lv=VolGroup/lv_swap rhgb quiet rd.shell=0 audit=1"

Rationale:

Each process on the system carries an "auditable" flag which indicates whether its activities can be audited. Although `auditd` takes care of enabling this for all processes which launch after it does, adding the kernel argument ensures it is set for every process during boot.

Severity: medium

Identifiers: CCE-27212-0

References: 4.1.3, 5.4.1.1, 3.3.1, CCI-001464, CCI-000130, 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), AC-17(1), AU-14(1), AU-1(b), AU-2(a), AU-2(c), AU-2(d), AU-10, IR-5, Req-10.3

Remediation Shell script: (show)

    # Correct the form of default kernel command line in /etc/default/grub
    grep -q ^GRUB_CMDLINE_LINUX=\".*audit=0.*\" /etc/default/grub && \
      sed -i "s/audit=[^[:space:]\+]/audit=1/g" /etc/default/grub
    if ! [ $? -eq 0 ]; then
      sed -i "s/\(GRUB_CMDLINE_LINUX=\)\"\(.*\)\"/\1\"\2 audit=1\"/" /etc/default/grub
    fi

    # Correct the form of kernel command line for each installed kernel
    # in the bootloader
    /sbin/grubby --update-kernel=ALL --args="audit=1"

Remediation Ansible snippet: (show)

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

    - name: "Enable Auditing for Processes Which Start Prior to the Audit Daemon"
      shell: /sbin/grubby --update-kernel=ALL --args="audit=1"
      tags:
        - bootloader_audit_argument
        - medium_severity
        - restrict_strategy
        - low_complexity
        - low_disruption
        - CCE-27212-0
        - NIST-800-53-AC-17(1)
        - NIST-800-53-AU-14(1)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-2(a)
        - NIST-800-53-AU-2(c)
        - NIST-800-53-AU-2(d)
        - NIST-800-53-AU-10
        - NIST-800-53-IR-5
        - NIST-800-171-3.3.1
        - PCI-DSS-Req-10.3
        - CJIS-5.4.1.1

#### Enable auditd Service [ref]rule

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: high

Identifiers: CCE-27407-6

References: RHEL-07-030000, SV-86703r2_rule, 4.1.2, 5.4.1.1, 3.3.1, 3.3.2, 3.3.6, CCI-000126, CCI-000131, 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), AU-3, AC-17(1), AU-1(b), AU-10, AU-12(a), AU-12(c), AU-14(1), IR-5, Req-10, SRG-OS-000038-GPOS-00016, SRG-OS-000039-GPOS-00017, SRG-OS-000042-GPOS-00021, SRG-OS-000254-GPOS-00095, SRG-OS-000255-GPOS-00096

Remediation Shell script: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    # Function to enable/disable and start/stop services on RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     service_command enable bluetooth
    #     service_command disable bluetooth.service
    #
    #     Using xinetd:
    #     service_command disable rsh.socket xinetd=rsh
    #
    function service_command {

    # Load function arguments into local variables
    local service_state=$1
    local service=$2
    local xinetd=$(echo $3 | cut -d'=' -f2)

    # Check sanity of the input
    if [ $# -lt "2" ]
    then
      echo "Usage: service_command 'enable/disable' 'service_name.service'"
      echo
      echo "To enable or disable xinetd services add \'xinetd=service_name\'"
      echo "as the last argument"
      echo "Aborting."
      exit 1
    fi

    # If systemctl is installed, use systemctl command; otherwise, use the service/chkconfig commands
    if [ -f "/usr/bin/systemctl" ] ; then
      service_util="/usr/bin/systemctl"
    else
      service_util="/sbin/service"
      chkconfig_util="/sbin/chkconfig"
    fi

    # If disable is not specified in arg1, set variables to enable services.
    # Otherwise, variables are to be set to disable services.
    if [ "$service_state" != 'disable' ] ; then
      service_state="enable"
      service_operation="start"
      chkconfig_state="on"
    else
      service_state="disable"
      service_operation="stop"
      chkconfig_state="off"
    fi

    # If chkconfig_util is not empty, use chkconfig/service commands.
    if [ "x$chkconfig_util" != x ] ; then
      $service_util $service $service_operation
      $chkconfig_util --level 0123456 $service $chkconfig_state
    else
      $service_util $service_operation $service
      $service_util $service_state $service
      # 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.
      $service_util reset-failed $service
    fi

    # Test if local variable xinetd is empty using non-bashism.
    # If empty, then xinetd is not being used.
    if [ "x$xinetd" != x ] ; then
      grep -qi disable /etc/xinetd.d/$xinetd && \

      if [ "$service_operation" = 'disable' ] ; then
        sed -i "s/disable.*/disable         = no/gI" /etc/xinetd.d/$xinetd
      else
        sed -i "s/disable.*/disable         = yes/gI" /etc/xinetd.d/$xinetd
      fi
    fi

    }

    service_command enable auditd

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | low
Strategy: | enable

    - name: Enable service auditd
      service:
        name="{{item}}"
        enabled="yes"
        state="started"
      with_items:
        - auditd
      tags:
        - service_auditd_enabled
        - high_severity
        - enable_strategy
        - low_complexity
        - low_disruption
        - CCE-27407-6
        - NIST-800-53-AU-3
        - NIST-800-53-AC-17(1)
        - NIST-800-53-AU-1(b)
        - NIST-800-53-AU-10
        - NIST-800-53-AU-12(a)
        - NIST-800-53-AU-12(c)
        - NIST-800-53-AU-14(1)
        - NIST-800-53-IR-5
        - NIST-800-171-3.3.1
        - NIST-800-171-3.3.2
        - NIST-800-171-3.3.6
        - PCI-DSS-Req-10
        - CJIS-5.4.1.1
        - DISA-STIG-RHEL-07-030000

### Installing and Maintaining Software [ref]group

The following sections contain information on security-relevant choices during the initial operating system installation process and the setup of software updates.

contains 10 rules

### GNOME Desktop Environment [ref]group

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

contains 2 rules

### GNOME Remote Access Settings [ref]group

GNOME remote access settings that apply to the graphical interface.

contains 2 rules

#### Require Encryption for Remote Access in GNOME3 [ref]rule

By default, `GNOME` requires encryption when using `Vino` for remote access. To prevent remote access encryption from being disabled, add or set `require-encryption` to `true` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/Vino]
    require-encryption=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/Vino/require-encryption

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

Open X displays allow an attacker to capture keystrokes and to execute commands remotely.

Severity: medium

Identifiers: CCE-80121-7

References: RHEL-07-TBD, 3.1.13, CCI-000366, 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), CM-2(1)(b), SRG-OS-000480-GPOS-00227

Remediation Shell script: (show)

    function include_dconf_settings {
    	:
    }

    # Function to configure DConf settings for RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     dconf_settings 'org/gnome/login-screen' 'banner-message-enable' 'true' 'local.d' '10-banner'
    #
    function dconf_settings {
    	local _path=$1 _key=$2 _value=$3 _db=$4 _settingFile=$5

    	# Check sanity of the input
    	if [ $# -ne "5" ]
    	then
    		echo "Usage: dconf_settings 'dconf_path' 'dconf_setting' 'dconf_db' 'dconf_settingsfile'"
    		echo "Aborting."
    		exit 1
    	fi

    	# Check for setting in any of the DConf db directories
    	SETTINGSFILES=($(grep -r "\[${_path}]" "/etc/dconf/db/" | grep -v "distro\|ibus" | cut -d":" -f1))
    	DCONFFILE="/etc/dconf/db/${_db}/${_settingFile}"
    	DBDIR="/etc/dconf/db/${_db}"

    	mkdir -p "${DBDIR}"

    	if [[ -z "${SETTINGSFILES[@]}" ]]
    	then
    		[ ! -z ${DCONFFILE} ] || $(echo "" >> ${DCONFFILE})
    		echo "[${_path}]" >> ${DCONFFILE}
    		echo "${_key}=${_value}" >> ${DCONFFILE}
    	else
    		if grep -q "${_key}" ${SETTINGSFILES[@]}
    		then
    			sed -i "s/${_key}\s*=\s*.*/${_key}=${_value}/g" ${SETTINGSFILES[@]}
    		else
    			sed -i "\|\[${_path}]|a\\${_key}=${_value}" ${SETTINGSFILES[@]}
    		fi
    	fi
    }

    # Function to configure DConf locks for RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     dconf_lock 'org/gnome/login-screen' 'banner-message-enable' 'local.d' 'banner'
    #
    function dconf_lock {
    	local _key=$1 _setting=$2 _db=$3 _lockFile=$4

    	# Check sanity of the input
    	if [ $# -ne "4" ]
    	then
    		echo "Usage: dconf_lock 'dconf_path' 'dconf_setting' 'dconf_db' 'dconf_lockfile'"
    		echo "Aborting."
    		exit 1
    	fi

    	# Check for setting in any of the DConf db directories
    	LOCKFILES=$(grep -r "^/${_key}/${_setting}$" "/etc/dconf/db/" | grep -v "distro\|ibus" | cut -d":" -f1)
    	LOCKSFOLDER="/etc/dconf/db/${_db}/locks"

    	mkdir -p "${LOCKSFOLDER}"

    	if [[ -z "${LOCKFILES}" ]]
    	then
    		echo "/${_key}/${_setting}" >> "/etc/dconf/db/${_db}/locks/${_lockFile}"
    	fi
    }

    include_dconf_settings

    dconf_settings 'org/gnome/Vino' 'require-encryption' 'true' 'local.d' '00-security-settings'
    dconf_lock 'org/gnome/Vino' 'require-encryption' 'local.d' '00-security-settings-lock'

#### Require Credential Prompting for Remote Access in GNOME3 [ref]rule

By default, `GNOME` does not require credentials when using `Vino` for remote access. To configure the system to require remote credentials, add or set `authentication-methods` to `['vnc']` in `/etc/dconf/db/local.d/00-security-settings`. For example:

    [org/gnome/Vino]
    authentication-methods=['vnc']

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/Vino/authentication-methods

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

Username and password prompting is required for remote access. Otherwise, non-authorized and nefarious users can access the system freely.

Severity: medium

Identifiers: CCE-80120-9

References: 3.1.12, 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)

Remediation Shell script: (show)

    function include_dconf_settings {
    	:
    }

    # Function to configure DConf settings for RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     dconf_settings 'org/gnome/login-screen' 'banner-message-enable' 'true' 'local.d' '10-banner'
    #
    function dconf_settings {
    	local _path=$1 _key=$2 _value=$3 _db=$4 _settingFile=$5

    	# Check sanity of the input
    	if [ $# -ne "5" ]
    	then
    		echo "Usage: dconf_settings 'dconf_path' 'dconf_setting' 'dconf_db' 'dconf_settingsfile'"
    		echo "Aborting."
    		exit 1
    	fi

    	# Check for setting in any of the DConf db directories
    	SETTINGSFILES=($(grep -r "\[${_path}]" "/etc/dconf/db/" | grep -v "distro\|ibus" | cut -d":" -f1))
    	DCONFFILE="/etc/dconf/db/${_db}/${_settingFile}"
    	DBDIR="/etc/dconf/db/${_db}"

    	mkdir -p "${DBDIR}"

    	if [[ -z "${SETTINGSFILES[@]}" ]]
    	then
    		[ ! -z ${DCONFFILE} ] || $(echo "" >> ${DCONFFILE})
    		echo "[${_path}]" >> ${DCONFFILE}
    		echo "${_key}=${_value}" >> ${DCONFFILE}
    	else
    		if grep -q "${_key}" ${SETTINGSFILES[@]}
    		then
    			sed -i "s/${_key}\s*=\s*.*/${_key}=${_value}/g" ${SETTINGSFILES[@]}
    		else
    			sed -i "\|\[${_path}]|a\\${_key}=${_value}" ${SETTINGSFILES[@]}
    		fi
    	fi
    }

    # Function to configure DConf locks for RHEL and Fedora systems.
    #
    # Example Call(s):
    #
    #     dconf_lock 'org/gnome/login-screen' 'banner-message-enable' 'local.d' 'banner'
    #
    function dconf_lock {
    	local _key=$1 _setting=$2 _db=$3 _lockFile=$4

    	# Check sanity of the input
    	if [ $# -ne "4" ]
    	then
    		echo "Usage: dconf_lock 'dconf_path' 'dconf_setting' 'dconf_db' 'dconf_lockfile'"
    		echo "Aborting."
    		exit 1
    	fi

    	# Check for setting in any of the DConf db directories
    	LOCKFILES=$(grep -r "^/${_key}/${_setting}$" "/etc/dconf/db/" | grep -v "distro\|ibus" | cut -d":" -f1)
    	LOCKSFOLDER="/etc/dconf/db/${_db}/locks"

    	mkdir -p "${LOCKSFOLDER}"

    	if [[ -z "${LOCKFILES}" ]]
    	then
    		echo "/${_key}/${_setting}" >> "/etc/dconf/db/${_db}/locks/${_lockFile}"
    	fi
    }

    include_dconf_settings

    dconf_settings 'org/gnome/Vino' 'authentication-methods' "['vnc']" 'local.d' '00-security-settings'
    dconf_lock 'org/gnome/Vino' 'authentication-methods' 'local.d' '00-security-settings-lock'

### System and Software Integrity [ref]group

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.

contains 2 rules

### Software Integrity Checking [ref]group

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.

contains 2 rules

### Verify Integrity with RPM [ref]group

The RPM package management system includes the ability to verify the integrity of installed packages by comparing the installed files with information about the files taken from the package metadata stored in the RPM database. Although an attacker could corrupt the RPM database (analogous to attacking the AIDE database as described above), this check can still reveal modification of important files. To list which files on the system differ from what is expected by the RPM database:

    $ rpm -qVa

See the man page for `rpm` to see a complete explanation of each column.

contains 2 rules

#### Verify and Correct File Permissions with RPM [ref]rule

The RPM package management system can check file access permissions of installed software packages, including many that are important to system security. Verify that the file permissions of system files and commands match vendor values. Check the file permissions with the following command:

    $ sudo rpm -Va | grep '^.M'

Output indicates files that do not match vendor defaults. After locating a file with incorrect permissions, run the following command to determine which package owns it:

    $ rpm -qf FILENAME

Next, run the following command to reset its permissions to the correct values:

    $ sudo rpm --setperms PACKAGENAME

Rationale:

Permissions on system binaries and configuration files that are too generous could allow an unauthorized user to gain privileges that they should not have. The permissions set by the vendor should be maintained. Any deviations from this baseline should be investigated.

Severity: high

Identifiers: CCE-27209-6

References: RHEL-07-010010, SV-86473r2_rule, 1.2.6, 6.1.3, 6.1.4, 6.1.5, 6.1.6, 6.1.7, 6.1.8, 6.1.9, 6.2.3, 5.10.4.1, 3.3.8, 3.4.1, CCI-001494, CCI-001496, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), AC-6, AU-9(1), AU-9(3), CM-6(d), CM-6(3), Req-11.5, SRG-OS-000257-GPOS-00098, SRG-OS-000278-GPOS-00108

Remediation Shell script: (show)

Complexity: | high
Disruption: | medium
Strategy: | restrict

    # Declare array to hold list of RPM packages we need to correct permissions for
    declare -a SETPERMS_RPM_LIST

    # Create a list of files on the system having permissions different from what
    # is expected by the RPM database
    FILES_WITH_INCORRECT_PERMS=($(rpm -Va --nofiledigest | grep '^.M' | cut -d ' ' -f4-))

    # For each file path from that list:
    # * Determine the RPM package the file path is shipped by,
    # * Include it into SETPERMS_RPM_LIST array

    for FILE_PATH in "${FILES_WITH_INCORRECT_PERMS[@]}"
    do
    	RPM_PACKAGE=$(rpm -qf "$FILE_PATH")
    	SETPERMS_RPM_LIST=("${SETPERMS_RPM_LIST[@]}" "$RPM_PACKAGE")
    done

    # Remove duplicate mention of same RPM in $SETPERMS_RPM_LIST (if any)
    SETPERMS_RPM_LIST=( $(echo "${SETPERMS_RPM_LIST[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ') )

    # For each of the RPM packages left in the list -- reset its permissions to the
    # correct values
    for RPM_PACKAGE in "${SETPERMS_RPM_LIST[@]}"
    do
    	rpm --setperms "${RPM_PACKAGE}"
    done

Remediation Ansible snippet: (show)

Complexity: | high
Disruption: | medium
Strategy: | restrict

    - name: "Read list of files with incorrect permissions"
      shell: "rpm -Va | grep '^.M' | cut -d ' ' -f5- | sed -r 's;^.*\\s+(.+);\\1;g'"
      register: files_with_incorrect_permissions
      failed_when: False
      changed_when: False
      check_mode: no
      tags:
        - rpm_verify_permissions
        - high_severity
        - restrict_strategy
        - high_complexity
        - medium_disruption
        - CCE-27209-6
        - NIST-800-53-AC-6
        - NIST-800-53-AU-9(1)
        - NIST-800-53-AU-9(3)
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010010

    - name: "Correct file permissions with RPM"
      shell: "rpm --setperms $(rpm -qf '{{item}}')"
      with_items: "{{ files_with_incorrect_permissions.stdout_lines }}"
      when: files_with_incorrect_permissions.stdout_lines | length > 0
      tags:
        - rpm_verify_permissions
        - high_severity
        - restrict_strategy
        - high_complexity
        - medium_disruption
        - CCE-27209-6
        - NIST-800-53-AC-6
        - NIST-800-53-AU-9(1)
        - NIST-800-53-AU-9(3)
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010010

#### Verify File Hashes with RPM [ref]rule

Without cryptographic integrity protections, system executables and files can be altered by unauthorized users without detection. The RPM package management system can check the hashes of installed software packages, including many that are important to system security. To verify that the cryptographic hash of system files and commands match vendor values, run the following command to list which files on the system have hashes that differ from what is expected by the RPM database:

    $ rpm -Va | grep '^..5'

A "c" in the second column indicates that a file is a configuration file, which may appropriately be expected to change. If the file was not expected to change, investigate the cause of the change using audit logs or other means. The package can then be reinstalled to restore the file. Run the following command to determine which package owns the file:

    $ rpm -qf FILENAME

The package can be reinstalled from a yum repository using the command:

    $ sudo yum reinstall PACKAGENAME

Alternatively, the package can be reinstalled from trusted media using the command:

    $ sudo rpm -Uvh PACKAGENAME

Rationale:

The hashes of important files like system executables should match the information given by the RPM database. Executables with erroneous hashes could be a sign of nefarious activity on the system.

Severity: high

Identifiers: CCE-27157-7

References: RHEL-07-010020, SV-86479r2_rule, 1.2.6, 5.10.4.1, 3.3.8, 3.4.1, CCI-000663, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-6(d), CM-6(3), SI-7(1), Req-11.5, SRG-OS-000480-GPOS-00227

Remediation Ansible snippet: (show)

Complexity: | high
Disruption: | medium

    - name: "Set fact: Package manager reinstall command (dnf)"
      set_fact:
        package_manager_reinstall_cmd: dnf reinstall -y
      when: ansible_distribution == "Fedora"
      tags:
        - rpm_verify_hashes
        - high_severity
        - unknown_strategy
        - high_complexity
        - medium_disruption
        - CCE-27157-7
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-53-SI-7(1)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010020

    - name: "Set fact: Package manager reinstall command (yum)"
      set_fact:
        package_manager_reinstall_cmd: yum reinstall -y
      when: ansible_distribution == "RedHat" or ansible_distribution == "OracleLinux"
      tags:
        - rpm_verify_hashes
        - high_severity
        - unknown_strategy
        - high_complexity
        - medium_disruption
        - CCE-27157-7
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-53-SI-7(1)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010020

    - name: "Read files with incorrect hash"
      shell: "rpm -Va | grep -E '^..5.* /(bin|sbin|lib|lib64|usr)/' | sed -r 's;^.*\\s+(.+);\\1;g'"
      register: files_with_incorrect_hash
      changed_when: False
      when: package_manager_reinstall_cmd is defined
      check_mode: no
      tags:
        - rpm_verify_hashes
        - high_severity
        - unknown_strategy
        - high_complexity
        - medium_disruption
        - CCE-27157-7
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-53-SI-7(1)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010020

    - name: "Reinstall packages of files with incorrect hash"
      shell: "{{package_manager_reinstall_cmd}} $(rpm -qf '{{item}}')"
      with_items: "{{ files_with_incorrect_hash.stdout_lines }}"
      when: package_manager_reinstall_cmd is defined and (files_with_incorrect_hash.stdout_lines | length > 0)
      tags:
        - rpm_verify_hashes
        - high_severity
        - unknown_strategy
        - high_complexity
        - medium_disruption
        - CCE-27157-7
        - NIST-800-53-CM-6(d)
        - NIST-800-53-CM-6(3)
        - NIST-800-53-SI-7(1)
        - NIST-800-171-3.3.8
        - NIST-800-171-3.4.1
        - PCI-DSS-Req-11.5
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-010020

### Updating Software [ref]group

The `yum` 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 systems contain an installed software catalog called the RPM database, which records metadata of installed packages. Consistently using `yum` or the graphical Software Update for all software installation allows for insight into the current inventory of installed software on the system.
Oracle Linux system contain an installed software catalog called the RPM database, which records metadata of installed packages. Consistently using `yum` or the graphical Software Update for all software installation allows for insight into the current inventory of installed software on the system.

contains 5 rules

#### Ensure gpgcheck Enabled For All Yum Package Repositories [ref]rule

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

Identifiers: CCE-26876-3

References: FAU_GEN.1.1.c, 5.10.4.1, 3.4.8, CCI-001749, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-5(3), SI-7, MA-1(b), Req-6.2, 366

Remediation Shell script: (show)

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

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium

    #
    - name: Find All Yum Repositories
      find:
        paths: "/etc/yum.repos.d/"
        patterns: "*.repo"
      register: yum_find

    - name: Ensure gpgcheck Enabled For All Yum Package Repositories
      with_items: "{{ yum_find.files }}"
      lineinfile:
        create: yes
        dest: "{{ item.path }}"
        regexp: '^gpgcheck'
        line: 'gpgcheck=1'
      tags:
        - ensure_gpgcheck_never_disabled
        - high_severity
        - unknown_strategy
        - low_complexity
        - medium_disruption
        - CCE-26876-3
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1

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

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

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

Identifiers: CCE-26957-1

References: FAU_GEN.1.1.c, 1.2.3, 5.10.4.1, 3.4.8, CCI-001749, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-5(3), SI-7, MA-1(b), Req-6.2, 366

Remediation Shell script: (show)

    # The two fingerprints below are retrieved from https://access.redhat.com/security/team/key
    readonly REDHAT_RELEASE_2_FINGERPRINT="567E 347A D004 4ADE 55BA 8A5F 199E 2F91 FD43 1D51"
    readonly REDHAT_AUXILIARY_FINGERPRINT="43A6 E49C 4A38 F4BE 9ABF 2A53 4568 9C88 2FA6 58E0"
    # 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).
      IFS=$'\n' GPG_OUT=($(gpg --with-fingerprint "${REDHAT_RELEASE_KEY}" | grep 'Key fingerprint ='))
      GPG_RESULT=$?
      # Reset IFS back to default
      unset IFS
      # No CRC error, safe to proceed
      if [ "${GPG_RESULT}" -eq "0" ]
      then
        tr -s ' ' <<< "${GPG_OUT}" | grep -vE "${REDHAT_RELEASE_2_FINGERPRINT}|${REDHAT_AUXILIARY_FINGERPRINT}" || {
          # If file doesn't contains any keys with unknown fingerprint, import it
          rpm --import "${REDHAT_RELEASE_KEY}"
        }
      fi
    fi

Remediation Ansible snippet: (show)

Complexity: | medium
Disruption: | medium
Strategy: | restrict

    - name: "Read permission of GPG key directory"
      stat:
        path: /etc/pki/rpm-gpg/
      register: gpg_key_directory_permission
      check_mode: no
      tags:
        - ensure_redhat_gpgkey_installed
        - high_severity
        - restrict_strategy
        - medium_complexity
        - medium_disruption
        - CCE-26957-1
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1

    # It should fail if it doesn't find any fingerprints in file - maybe file was not parsed well.

    - name: Read signatures in GPG key
      shell: gpg --with-fingerprint '/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release' | grep 'Key fingerprint =' | tr -s ' ' | sed 's;.*= ;;g'
      changed_when: False
      register: gpg_fingerprints
      check_mode: no
      tags:
        - ensure_redhat_gpgkey_installed
        - high_severity
        - restrict_strategy
        - medium_complexity
        - medium_disruption
        - CCE-26957-1
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1

    - name: Set Fact - Valid fingerprints
      set_fact:
         gpg_valid_fingerprints: ("567E 347A D004 4ADE 55BA 8A5F 199E 2F91 FD43 1D51" "43A6 E49C 4A38 F4BE 9ABF 2A53 4568 9C88 2FA6 58E0")
      tags:
        - ensure_redhat_gpgkey_installed
        - high_severity
        - restrict_strategy
        - medium_complexity
        - medium_disruption
        - CCE-26957-1
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1

    - name: Import RedHat GPG key
      rpm_key:
        state: present
        key: /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
      when:
        (gpg_key_directory_permission.stat.mode <= '0755')
        and (( gpg_fingerprints.stdout_lines | difference(gpg_valid_fingerprints)) | length == 0)
        and (gpg_fingerprints.stdout_lines | length > 0)
        and (ansible_distribution == "RedHat")
      tags:
        - ensure_redhat_gpgkey_installed
        - high_severity
        - restrict_strategy
        - medium_complexity
        - medium_disruption
        - CCE-26957-1
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1

#### Ensure gpgcheck Enabled for Repository Metadata [ref]rule

Verify the operating system prevents the installation of patches, service packs, device drivers, or operating system components of local packages without verification of the repository metadata.
Check that `yum` verifies the repository metadata prior to install with the following command. This should be configured by setting `repo_gpgcheck` to `1` in `/etc/yum.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.
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. The operating system should not have to verify the software again.
NOTE: For U.S. Military systems, this requirement does not mandate DoD certificates for this purpose; however, the certificate used to verify the software must be from an approved Certificate Authority.

Severity: high

Identifiers: CCE-80348-6

References: RHEL-07-020070, SV-86605r1_rule, CCI-001749, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-5(3), SRG-OS-000366-GPOS-00153

#### Ensure gpgcheck Enabled In Main Yum Configuration [ref]rule

The `gpgcheck` option controls whether RPM packages' signatures are always checked prior to installation. To configure yum to check package signatures before installing them, ensure the following line appears in `/etc/yum.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

Identifiers: CCE-26989-4

References: FAU_GEN.1.1.c, RHEL-07-020050, SV-86601r1_rule, 1.2.2, 5.10.4.1, 3.4.8, CCI-001749, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-5(3), SI-7, MA-1(b), Req-6.2, SRG-OS-000366-GPOS-00153

Remediation Shell script: (show)

    # Function to replace configuration setting in config file or add the configuration setting if
    # it does not exist.
    #
    # Expects arguments:
    #
    # config_file:		Configuration file that will be modified
    # key:			Configuration option to change
    # value:		Value of the configuration option to change
    # cce:			The CCE identifier or '@CCENUM@' if no CCE identifier exists
    # format:		The printf-like format string that will be given stripped key and value as arguments,
    #			so e.g. '%s=%s' will result in key=value subsitution (i.e. without spaces around =)
    #
    # Optional arugments:
    #
    # format:		Optional argument to specify the format of how key/value should be
    # 			modified/appended in the configuration file. The default is key = value.
    #
    # Example Call(s):
    #
    #     With default format of 'key = value':
    #     replace_or_append '/etc/sysctl.conf' '^kernel.randomize_va_space' '2' '@CCENUM@'
    #
    #     With custom key/value format:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' 'disabled' '@CCENUM@' '%s=%s'
    #
    #     With a variable:
    #     replace_or_append '/etc/sysconfig/selinux' '^SELINUX=' $var_selinux_state '@CCENUM@' '%s=%s'
    #
    function replace_or_append {
      local default_format='%s = %s' case_insensitive_mode=yes sed_case_insensitive_option='' grep_case_insensitive_option=''
      local config_file=$1
      local key=$2
      local value=$3
      local cce=$4
      local format=$5

      if [ "$case_insensitive_mode" = yes ]; then
        sed_case_insensitive_option="i"
        grep_case_insensitive_option="-i"
      fi
      [ -n "$format" ] || format="$default_format"
      # Check sanity of the input
      [ $# -ge "3" ] || { echo "Usage: replace_or_append <config_file_location> <key_to_search> <new_value> [<CCE number or literal '@CCENUM@' if unknown>] [printf-like format, default is '$default_format']" >&2; exit 1; }

      # Test if the config_file is a symbolic link. If so, use --follow-symlinks with sed.
      # Otherwise, regular sed command will do.
      sed_command=('sed' '-i')
      if test -L "$config_file"; then
        sed_command+=('--follow-symlinks')
      fi

      # Test that the cce arg is not empty or does not equal @CCENUM@.
      # If @CCENUM@ exists, it means that there is no CCE assigned.
      if [ -n "$cce" ] && [ "$cce" != '@CCENUM@' ]; then
        cce="CCE-${cce}"
      else
        cce="CCE"
      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' <<< "$key")

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

      # If the key exists, change it. Otherwise, add it to the config_file.
      # We search for the key string followed by a word boundary (matched by \>),
      # so if we search for 'setting', 'setting2' won't match.
      if grep -q $grep_case_insensitive_option "${key}\\>" "$config_file"; then
        "${sed_command[@]}" "s/${key}\\>.*/$formatted_output/g$sed_case_insensitive_option" "$config_file"
      else
        # \n is precaution for case where file ends without trailing newline
        printf '\n# Per %s: Set %s in %s\n' "$cce" "$formatted_output" "$config_file" >> "$config_file"
        printf '%s\n' "$formatted_output" >> "$config_file"
      fi
    }

    replace_or_append '/etc/yum.conf' '^gpgcheck' '1' 'CCE-26989-4'

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium

    - name: Check existence of yum on Fedora
      stat:
        path: /etc/yum.conf
      register: yum_config_file
      check_mode: no
      when: ansible_distribution == "Fedora"

    # Old versions of Fedora use yum

    - name: Ensure GPG check is globally activated (yum)
      ini_file:
        dest: "{{item}}"
        section: main
        option: gpgcheck
        value: 1
        create: False
      with_items: "/etc/yum.conf"
      when: ansible_distribution == "RedHat" or ansible_distribution == "CentOS" or yum_config_file.stat.exists
      tags:
        - ensure_gpgcheck_globally_activated
        - high_severity
        - unknown_strategy
        - low_complexity
        - medium_disruption
        - CCE-26989-4
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-020050

    - name: Ensure GPG check is globally activated (dnf)
      ini_file:
        dest: "{{item}}"
        section: main
        option: gpgcheck
        value: 1
        create: False
      with_items: "/etc/dnf/dnf.conf"
      when: ansible_distribution == "Fedora"
      tags:
        - ensure_gpgcheck_globally_activated
        - high_severity
        - unknown_strategy
        - low_complexity
        - medium_disruption
        - CCE-26989-4
        - NIST-800-53-CM-5(3)
        - NIST-800-53-SI-7
        - NIST-800-53-MA-1(b)
        - NIST-800-171-3.4.8
        - PCI-DSS-Req-6.2
        - CJIS-5.10.4.1
        - DISA-STIG-RHEL-07-020050

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

`Yum` should be configured to verify the signature(s) of local packages prior to installation. To configure `yum` to verify signatures of local packages, set the `localpkg_gpgcheck` to `1` in `/etc/yum.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

Identifiers: CCE-80347-8

References: FAU_GEN.1.1.c, RHEL-07-020060, SV-86603r1_rule, 3.4.8, CCI-001749, 164.308(a)(1)(ii)(D), 164.312(b), 164.312(c)(1), 164.312(c)(2), 164.312(e)(2)(i), CM-5(3), SRG-OS-000366-GPOS-00153

Remediation Shell script: (show)

    if grep --silent ^localpkg_gpgcheck /etc/yum.conf ; then
            sed -i "s/^localpkg_gpgcheck.*/localpkg_gpgcheck=1/g" /etc/yum.conf
    else
            echo -e "\n# Set localpkg_gpgcheck to 1 per security requirements" >> /etc/yum.conf
            echo "localpkg_gpgcheck=1" >> /etc/yum.conf
    fi

Remediation Ansible snippet: (show)

Complexity: | low
Disruption: | medium

    - name: Check existence of yum on Fedora
      stat:
        path: /etc/yum.conf
      register: yum_config_file
      check_mode: no
      when: ansible_distribution == "Fedora"

    # Old versions of Fedora use yum

    - name: Ensure GPG check Enabled for Local Packages (Yum)
      ini_file:
        dest: "{{item}}"
        section: main
        option: localpkg_gpgcheck
        value: 1
        create: True
      with_items: "/etc/yum.conf"
      when: ansible_distribution == "RedHat" or ansible_distribution == "CentOS" or yum_config_file.stat.exists
      tags:
        - ensure_gpgcheck_local_packages
        - high_severity
        - unknown_strategy
        - low_complexity
        - medium_disruption
        - CCE-80347-8
        - NIST-800-53-CM-5(3)
        - NIST-800-171-3.4.8
        - DISA-STIG-RHEL-07-020060

    - name: Ensure GPG check Enabled for Local Packages (DNF)
      ini_file:
        dest: "{{item}}"
        section: main
        option: localpkg_gpgcheck
        value: 1
        create: True
      with_items: "/etc/dnf/dnf.conf"
      when: ansible_distribution == "Fedora"
      tags:
        - ensure_gpgcheck_local_packages
        - high_severity
        - unknown_strategy
        - low_complexity
        - medium_disruption
        - CCE-80347-8
        - NIST-800-53-CM-5(3)
        - NIST-800-171-3.4.8
        - DISA-STIG-RHEL-07-020060

### Disk Partitioning [ref]group

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. See the LVM HOWTO at http://tldp.org/HOWTO/LVM-HOWTO/ for more detailed information on LVM.

contains 1 rule

#### Encrypt Partitions [ref]rule

Red Hat Enterprise Linux 7 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 Documentation web site:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/sec-Encryption.htmlRationale:

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

Identifiers: CCE-27128-8

References: 3.13.16, CCI-001199, CCI-002476, 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), A.8.2.3, SC-13, SC-28(1), SRG-OS-000405-GPOS-00184, SRG-OS-000185-GPOS-00079

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.