{{#
Pass strings that correspond to XCCDF value names as arguments to this macro::

    bash_instantiate_variables("varname1", "varname2")

Then, assume that variables of that names are defined and contain the correct value, e.g.::

        echo "Setting=$varname1" >> config_file

#}}
{{%- macro bash_instantiate_variables() -%}}
{{%- for name in varargs -%}}
{{{ name }}}='(bash-populate {{{ name }}})'
{{% endfor -%}}
{{%- endmacro -%}}


{{#
    Make sure that we have a line like this in pamFile (additional options are left as-is):
    type control module option=valueRegexArg

:param pamFile:         PAM config file
:type pamFile: str
:param type:            PAM module interface
:type type: str
:param control:         PAM control flags
:type control: str
:param module:          PAM module name
:type module: str
:param option:          PAM module option
:type option: str
:param valueRegexArg:   PAM module option argument regex pattern
:type valueRegexArg: str
:param defaultValueArg: PAM module option argument default value
:type defaultValueArg: str

#}}
{{%- macro bash_ensure_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix 'type' if it's wrong
    if grep -q -P "^\\s*(?"'!'"{{{ type }}}\\s)[[:alnum:]]+\\s+[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*)[[:alnum:]]+(\\s+[[:alnum:]]+\\s+{{{ module }}})/\\1{{{ type }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix 'control' if it's wrong
    if grep -q -P "^\\s*{{{ type }}}\\s+(?"'!'"{{{ control }}})[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+)[[:alnum:]]+(\\s+{{{ module }}})/\\1{{{ control }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{#
    Make sure that we have a line with given type, control and module has the given option in pamFile (additional options are left as-is):
    `type control module option=valueRegexArg`

:param pamFile: PAM config file
:type pamFile: str
:param type: PAM module interface
:type type: str
:param control: PAM control flags
:type control: str
:param module: PAM module name
:type module: str
:param option: PAM module option
:type option: str
:param valueRegexArg: PAM module option argument regex pattern
:type valueRegexArg: str
:param defaultValueArg: PAM module option argument default value
:type defaultValueArg: str

#}}
{{%- macro bash_provide_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{%- macro in_chrooted_environment() -%}}
test "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)"
{{%- endmacro -%}}

{{#
    Set a parameter

:param path: Path to file
:type path: str
:param parameter: Parameter to set
:type parameter: str
:param value: Value to set
:type value: str
:param no_quotes: If true the value is not quoted. Default is false.
:type no_quotes: bool

#}}
{{%- macro bash_shell_file_set(path, parameter, value, no_quotes=false, rule_id=None) -%}}
{{% if no_quotes -%}}
  {{% if "$" in value %}}
    {{% set value = '%s' % value.replace("$", "\\$") %}}
  {{% endif %}}
{{%- else -%}}
  {{% if "$" in value %}}
    {{% set value = '\\"%s\\"' % value.replace("$", "\\$") %}}
  {{% else %}}
    {{% set value = "'%s'" % value %}}
  {{% endif %}}
{{%- endif -%}}
{{{ set_config_file(
        path=path,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="^#\s*" ~ parameter,
        insensitive=false,
        separator="=",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*", rule_id=rule_id)
    }}}
{{%- endmacro -%}}


{{#
    Set set a parameter in /etc/sshd_config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_sshd_config_set(parameter, value, rule_id=None) -%}}
{{{ set_config_file(
        path="/etc/ssh/sshd_config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="BOF",
        insensitive=true,
        separator=" ",
        separator_regex="\s\+",
        prefix_regex="^\s*", rule_id=rule_id)
    }}}
{{%- endmacro -%}}


{{#
        Set set a parameter in /etc/sshd_config or /etc/ssh/sshd_config.d/

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str
:parameter config_is_distributed: If true, will ok look in /etc/ssh/sshd_config.d
:type config_is_distributed: str
:parameter config_basename: Filename of configuration file when using distributed configuration
:type config_basename: str

#}}
{{% macro bash_sshd_remediation(parameter, value, config_is_distributed="false", config_basename="00-complianceascode-hardening.conf", rule_id=None) -%}}
{{%- set sshd_config_path = "/etc/ssh/sshd_config" %}}
{{%- set sshd_config_dir = "/etc/ssh/sshd_config.d" -%}}

{{% if product in ["ol8", "ol9"] %}}
# Find the include keyword, extract from the line the glob expression representing included files.
# And if it is a relative path prepend '/etc/ssh/'
included_files=$(grep -oP "^\s*(?i)include.*" /etc/ssh/sshd_config | sed -e 's/\s*include\s*//I' | sed -e 's|^[^/]|/etc/ssh/&|')
for included_file in ${included_files} ; do
    {{{ lineinfile_absent("$included_file", "^\s*" ~ parameter, insensitive=true, rule_id=rule_id) | indent(4) }}}
done
{{% endif %}}
{{%- if config_is_distributed == "true" %}}
{{%- set prefix_regex = "^\s*" -%}}
{{%- set separator_regex = "\s\+" -%}}
{{%- set hardening_config_basename = config_basename %}}
{{%- set line_regex = prefix_regex ~ parameter ~ separator_regex %}}
mkdir -p {{{ sshd_config_dir }}}
touch {{{ sshd_config_dir }}}/{{{ hardening_config_basename }}}
chmod 0600 {{{ sshd_config_dir }}}/{{{ hardening_config_basename }}}
{{{ lineinfile_absent(sshd_config_path, line_regex, insensitive=true, rule_id=rule_id) }}}
{{{ lineinfile_absent_in_directory(sshd_config_dir, line_regex, insensitive=true, filename_glob="*.conf") }}}
{{{ set_config_file(
        path=sshd_config_dir ~ "/" ~ hardening_config_basename,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="BOF",
        insensitive=true,
        separator=" ",
        separator_regex=separator_regex,
        prefix_regex=prefix_regex, rule_id=rule_id)
    }}}
{{%- else %}}
{{{ bash_sshd_config_set(parameter=parameter, value=value, rule_id=rule_id) }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
    Macro that copies the audit rules into a file.
    The purpose is to create exactly the same content in the file specified by filename argument
    as in https://github.com/linux-audit/audit-userspace/blob/master/rules/30-ospp-v42.rules

:param filename:    Name of the file to print the information to; written do directory specified by the filename
:type filename: str

#}}
{{%- macro bash_create_audit_remediation_unsuccessful_file_modification_detailed(filename) -%}}
mkdir -p "$(dirname '{{{ filename }}}')"
cat <<EOF > "{{{ filename }}}"
{{{ audit_remediation_unsuccessful_file_modification_detailed_audit_file_content() }}}
EOF
{{%- endmacro -%}}


{{#
   Set parameter in /etc/audit/auditd.conf

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_auditd_config_set(parameter, value, rule_id=None) -%}}
{{{ set_config_file(
        path="/etc/audit/auditd.conf",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator=" = ",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*", rule_id=rule_id)
    }}}
{{%- endmacro -%}}

{{#
   Set parameter in /etc/selinux/config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_selinux_config_set(parameter, value, rule_id=None) -%}}
{{{ set_config_file(
        path="/etc/selinux/config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator="=",
        separator_regex="=",
        prefix_regex="^", rule_id=rule_id)
    }}}
{{%- endmacro -%}}


{{#
    Macro to fix audit file system object watch rule for given path:

    * if rule exists, also verifies the '-w' or '-F path' 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

    Example macro invocation::

          {{{ bash_fix_audit_watch_rule("auditctl", "/etc/localtime", "wa", "audit_time_rules") }}}

:param tool:                 tool used to load audit rules, either 'auditctl', or 'augenrules'
:type tool: str
:param path:                 value of '-w' or '-F path=' or '-F dir=' audit rule's argument
:type path: str
:param required_access_bits: value of '-p' or '-F perm=' audit rule's argument
:type required_access_bits: str
:param key:                  value of '-k' or '-F key=' audit rule's argument
:type key: str
:param style: Use "modern" or "legacy" style of audit watches
:type style: str
:param arch: Value of '-F arch=' audit rule's argument, generate audit watches for the "b32" or "b64" architecture. Only applicable if "style" is set to "modern".
:type arch: str
:param filter_type: The string after first `-F` before first `=`. can be either `path` or `dir`. Only applicable if "style" is set to "modern".
:type filter_type: str


#}}
{{%- macro bash_fix_audit_watch_rule(tool, path, required_access_bits, key, style="", arch="", filter_type="path") -%}}
# Create a list of audit *.rules files that should be inspected for presence and correctness
# of a particular audit rule. The scheme is as follows:
#
# -----------------------------------------------------------------------------------------
# Tool used to load audit rules	| Rule already defined	|  Audit rules file to inspect	  |
# -----------------------------------------------------------------------------------------
#	auditctl		|     Doesn't matter	|  /etc/audit/audit.rules	  |
# -----------------------------------------------------------------------------------------
# 	augenrules		|          Yes		|  /etc/audit/rules.d/*.rules	  |
# 	augenrules		|          No		|  /etc/audit/rules.d/$key.rules  |
# -----------------------------------------------------------------------------------------
files_to_inspect=()

{{% if tool == "auditctl" %}}
# If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# into the list of files to be inspected
files_to_inspect+=('/etc/audit/audit.rules')
{{%- elif tool == "augenrules" -%}}
# 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.
{{% if style == "modern" %}}
readarray -t matches < <(grep -HP "[\s]*-F[\s]+{{{ filter_type }}}={{{ path }}}" /etc/audit/rules.d/*.rules)
{{% else %}}
readarray -t matches < <(grep -HP "[\s]*-w[\s]+{{{ path }}}" /etc/audit/rules.d/*.rules)
{{% endif %}}

# For each of the matched entries
for match in "${matches[@]}"
do
    # Extract filepath from the match
    rulesd_audit_file=$(echo $match | cut -f1 -d ':')
    # Append that path into list of files for inspection
    files_to_inspect+=("$rulesd_audit_file")
done
# Case when particular audit rule isn't defined yet
if [ "${#files_to_inspect[@]}" -eq "0" ]
then
    # Append '/etc/audit/rules.d/{{{ key }}}.rules' into list of files for inspection
    key_rule_file="/etc/audit/rules.d/{{{ key }}}.rules"
    # If the {{{ key }}}.rules file doesn't exist yet, create it with correct permissions
    if [ ! -e "$key_rule_file" ]
    then
        touch "$key_rule_file"
        chmod 0600 "$key_rule_file"
    fi
    files_to_inspect+=("$key_rule_file")
fi
{{%- else -%}}
{{{ raise("Unknown tool used: " + tool) }}}
{{%- endif %}}

# 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 style == "modern" %}}
    if grep -q -P -- "^[\s]*-F[\s]+{{{ filter_type }}}={{{ path }}}" "$audit_rules_file"
{{% else %}}
    if grep -q -P -- "^[\s]*-w[\s]+{{{ path }}}" "$audit_rules_file"
{{% endif %}}
    then
        # Rule is found => verify yet if existing rule definition contains
        # all of the required access type bits

        # Define BRE whitespace class shortcut
        sp="[[:space:]]"
        # Extract current permission access types (e.g. -p [r|w|x|a] values) from audit rule
{{% if style == "modern" %}}
        current_access_bits=$(sed -ne "s#$sp*-a$sp\+always,exit$sp\+-F$sp\+arch={{{ arch }}}$sp\+-F$sp\+{{{ filter_type }}}={{{ path }}}$sp\+-F$sp\+perm=\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")
{{% else %}}
        current_access_bits=$(sed -ne "s#$sp*-w$sp\+{{{ path }}} $sp\+-p$sp\+\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")
{{% endif %}}
        # 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
{{% if style == "modern" %}}
        sed -i "s#\($sp*-a$sp\+always,exit$sp\+-F$sp\+arch={{{ arch }}}$sp\+-F$sp\+{{{ filter_type }}}={{{ path }}}$sp\+-F$sp\+perm=\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"
{{% else %}}
        sed -i "s#\($sp*-w$sp\+{{{ path }}}$sp\+-p$sp\+\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"
{{% endif %}}
    else
        # Rule isn't present yet. Append it at the end of $audit_rules_file file
        # with proper key

{{% if style == "modern" %}}
        echo "-a always,exit -F arch={{{ arch }}} -F {{{ filter_type }}}={{{ path }}} -F perm={{{ required_access_bits }}} -F key={{{ key }}}" >> "$audit_rules_file"
{{% else %}}
        echo "-w {{{ path }}} -p {{{ required_access_bits }}} -k {{{ key }}}" >> "$audit_rules_file"
{{% endif %}}
    fi
done
{{%- endmacro -%}}


{{#
    Install a package

    Uses the right command based on pkg_manager property defined in product.yml.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_install(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if ! rpm -q --quiet "{{{ package }}}" ; then
    {{{ pkg_manager }}} install -y "{{{ package }}}"
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=60 install -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper install -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Remove a package

    Uses the right command based on pkg_manager property defined in product.yml.
    When used in a test scenario, the macro will remove even protected packages.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_remove(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if rpm -q --quiet "{{{ package }}}" ; then
{{% if SSG_TEST_SUITE_ENV %}}
    rpm -e --nodeps "{{{ package }}}"
{{% else %}}
    {{%- if pkg_manager == "dnf" -%}}
        dnf remove -y --noautoremove "{{{ package }}}"
    {{%- else -%}}
        {{{ pkg_manager }}} remove -y "{{{ package }}}"
    {{%- endif -%}}

{{% endif %}}
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=60 remove -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper remove -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Macro to perform remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    system calls on RHEL, Fedora or OL systems.
    Remediation performed for both possible tools: 'auditctl' and 'augenrules'.

     Note: 'stime' system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
     therefore excluded from the list of time group system calls to be audited on this arch

    Example macro invocation::

      {{{ bash_perform_audit_adjtimex_settimeofday_stime_remediation() }}}

#}}
{{%- macro bash_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
    # Create expected audit group and audit rule form for particular system call & architecture
    if [ ${ARCH} = "b32" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
        # so append it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday stime"
        SYSCALL_GROUPING="adjtimex settimeofday stime"
    elif [ ${ARCH} = "b64" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
        # therefore don't add it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday"
        SYSCALL_GROUPING="adjtimex settimeofday"
    fi
    OTHER_FILTERS=""
    AUID_FILTERS=""
    KEY="audit_time_rules"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    {{{ bash_fix_audit_syscall_rule("augenrules", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
    {{{ bash_fix_audit_syscall_rule("auditctl", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
done
{{%- endmacro -%}}


{{#
    Disable prelinking in sysconfig

#}}
{{%- macro bash_disable_prelink() -%}}
# prelink not installed
if test -e /etc/sysconfig/prelink -o -e /usr/sbin/prelink; then
    if grep -q ^PRELINKING /etc/sysconfig/prelink
    then
        sed -i 's/^PRELINKING[:blank:]*=[:blank:]*[:alpha:]*/PRELINKING=no/' /etc/sysconfig/prelink
    else
        printf '\n' >> /etc/sysconfig/prelink
        printf '%s\n' '# Set PRELINKING=no per security requirements' 'PRELINKING=no' >> /etc/sysconfig/prelink
    fi

    # Undo previous prelink changes to binaries if prelink is available.
    if test -x /usr/sbin/prelink; then
        /usr/sbin/prelink -ua
    fi
fi
{{%- endmacro -%}}


{{#
    Macro to configure DConf settings for RHEL and Fedora systems.

    If files contain ibus or distro, ignore them.

#}}
{{%- macro bash_dconf_settings(path, key, value, db, setting_file, rule_id=None) -%}}
# Check for setting in any of the DConf db directories
# If files contain ibus or distro, ignore them.
# The assignment assumes that individual filenames don't contain :
readarray -t SETTINGSFILES < <(grep -r "\\[{{{ path }}}\\]" "/etc/dconf/db/" \
                                | grep -v 'distro\|ibus\|{{{ db }}}' | cut -d":" -f1)
DCONFFILE="/etc/dconf/db/{{{ db }}}/{{{ setting_file }}}"
DBDIR="/etc/dconf/db/{{{ db }}}"

mkdir -p "${DBDIR}"

# Comment out the configurations in databases different from the target one
if [ "${#SETTINGSFILES[@]}" -ne 0 ]
then
    if grep -q "^\\s*{{{ key }}}\\s*=" "${SETTINGSFILES[@]}"
    then
        {{% if '/' in key %}}
        {{{ raise("Key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
        {{% endif %}}
        sed -Ei "s/(^\s*){{{ key }}}(\s*=)/#\1{{{ key }}}\2/g" "${SETTINGSFILES[@]}"
    fi
fi

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

escaped_value="$(sed -e 's/\\/\\\\/g' <<< "{{{ value }}}")"
if grep -q "^\\s*{{{ key }}}\\s*=" "${DCONFFILE}"
then
        sed -i "s/\\s*{{{ key }}}\\s*=\\s*.*/{{{ key }}}=${escaped_value}/g" "${DCONFFILE}"
    else
        sed -i "\\|\\[{{{ path }}}\\]|a\\{{{ key }}}=${escaped_value}" "${DCONFFILE}"
fi

{{%- if 'ubuntu' in product %}}
# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/db
(umask 0022 && dconf update)
{{%- else %}}
dconf update
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Macro to configure DConf locks for RHEL and Fedora systems.

#}}
{{%- macro bash_dconf_lock(key, setting, db, lock_file) -%}}
# Check for setting in any of the DConf db directories
LOCKFILES=$(grep -r "^/{{{ key }}}/{{{ setting }}}$" "/etc/dconf/db/" \
            | grep -v 'distro\|ibus\|{{{ db }}}' | grep ":" | cut -d":" -f1)
LOCKSFOLDER="/etc/dconf/db/{{{ db }}}/locks"

mkdir -p "${LOCKSFOLDER}"

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

if ! grep -qr "^/{{{ key }}}/{{{ setting }}}$" /etc/dconf/db/{{{ db }}}/
then
    echo "/{{{ key }}}/{{{ setting }}}" >> "/etc/dconf/db/{{{ db }}}/locks/{{{ lock_file }}}"
fi

{{%- if 'ubuntu' in product %}}
# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/db
(umask 0022 && dconf update)
{{%- else %}}
dconf update
{{%- endif %}}
{{%- endmacro -%}}


{{#
Macro to enable or disable a particular service.

    Examples::

        bash_service_command("enable", "bluetooth")
        bash_service_command("disable", "bluetooth.service")
        bash_service_command("disable", "rsh.socket", xinetd="rsh")

:param service_state: Desired state of the service
:type service_state: str
:param service: The service to change
:type service: str
:param xinetd: Set the xinetd for the service. Defaults to empty string.
:type xinetd: str

#}}
{{%- macro bash_service_command(service_state, service, xinetd="") -%}}
{{#
# If systemctl is installed, use systemctl command; otherwise, use the
# service/chkconfig commands
#}}
{{%- if init_system == "systemd" -%}}
  {{%- if service_state == "disable" -%}}
if [[ $(/usr/bin/systemctl is-system-running) != "offline" ]]; then
/usr/bin/systemctl stop "{{{ service }}}"
fi
/usr/bin/systemctl disable "{{{ service }}}"
  {{%- else -%}}
/usr/bin/systemctl enable "{{{ service }}}"
if [[ $(/usr/bin/systemctl is-system-running) != "offline" ]]; then
/usr/bin/systemctl start "{{{ service }}}"
fi
  {{%- endif %}}
# 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.
if /usr/bin/systemctl --failed | grep -q "{{{ service }}}"; then
    /usr/bin/systemctl reset-failed "{{{ service }}}"
fi
{{%- endif -%}}

{{%- if xinetd != "" -%}}
grep -qi disable "/etc/xinetd.d/$xinetd" && \
    {{%- if service_state == "disable" -%}}
sed -i "s/disable.*/disable         = no/gI" "/etc/xinetd.d/$xinetd"
    {{%- else -%}}
sed -i "s/disable.*/disable         = yes/gI" "/etc/xinetd.d/$xinetd"
    {{%- endif -%}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Macro to ensure that the ntp/chrony config file contains valid server entries.

:param config_file: Path to the ntp/chrony config file
:type config_file: str
:param servers_list: Comma-separated list of servers
:type servers_list: str

#}}
{{%- macro bash_ensure_there_are_servers_in_ntp_compatible_config_file(config_file, servers_list) -%}}
if ! grep -q '#[[:space:]]*server' "{{{ config_file }}}" ; then
  for server in $(echo "{{{ servers_list }}}" | tr ',' '\n') ; do
    printf '\nserver %s' "$server" >> "{{{ config_file }}}"
  done
else
  sed -i 's/#[ \t]*server/server/g' "{{{ config_file }}}"
fi
{{{ bash_ensure_nl_at_eof(config_file) }}}
{{%- endmacro -%}}


{{#
    Macro used to apply changes on authselect profiles. The command automatically creates a backup
    of the current settings before applying the changes. It is possible to inform a custom backup
    name through the "backup_name" parameter. If the "backup_name" parameter is not defined, the
    authselect default name is used. The default name is formed by the current date and time
    suffixed by 6 random alphanumeric characters. The authselect backups are stored in sub-folders
    inside the "/var/lib/authselect/backups" folder, identified by their respective backup names.
    Note: An existing backup can be overwritten if the same backup name is informed. If this is
    not desired, avoid defining a backup name.

:param backup_name:        Changes the default backup name used by authselect.
:type backup_name: str

#}}
{{% macro bash_apply_authselect_changes(backup_name='') -%}}
{{%- if backup_name == '' %}}
authselect apply-changes -b
{{%- else %}}
authselect apply-changes -b --backup={{{ backup_name }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
    Disable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.
#}}
{{%- macro bash_disable_authselect_feature(feature) -%}}
{{{ bash_check_authselect_integrity() }}}
authselect disable-feature {{{ feature }}}
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Enable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.
#}}
{{%- macro bash_enable_authselect_feature(feature) -%}}
{{{ bash_check_authselect_integrity() }}}
authselect enable-feature {{{ feature }}}
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module using authselect.
    If an authselect profile is not selected or the selected profile is not intact, the operation is aborted.
    If the operation is aborted, an informative message is shown in the remediation report.

#}}
{{%- macro bash_enable_pam_faillock_with_authselect() -%}}
{{{ bash_enable_authselect_feature('with-faillock') }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module by directly editing PAM files.
    This option is only recommended when authselect tool is not available for the system.

#}}
{{%- macro bash_enable_pam_faillock_directly_in_pam_files() -%}}
{{% if 'debian' in product or product in ['sle15', 'sle16'] %}}
pam_file="/etc/pam.d/common-auth"
if ! grep -qE '^\s*auth\s+required\s+pam_faillock\.so\s+preauth.*$' "$pam_file" ; then
    {{% if  product in ['sle15', 'sle16'] %}}
    # insert before pam_unix.so
    sed -i --follow-symlinks '/^auth.*required.*pam_unix\.so.*/i auth        required      pam_faillock.so preauth' "$pam_file"
    {{% else %}}
    # insert at the top
    sed -i --follow-symlinks '/^# here are the per-package modules/i auth        required      pam_faillock.so preauth' "$pam_file"
    {{% endif %}}
fi
if ! grep -qE '^\s*auth\s+\[default=die\]\s+pam_faillock\.so\s+authfail.*$' "$pam_file" ; then

    num_lines=$(sed -n 's/^\s*auth.*success=\([1-9]\).*pam_unix\.so.*/\1/p' "$pam_file")
    if [ ! -z "$num_lines" ]; then

        # Add pam_faillock (authfail) module below pam_unix, skipping N-1 lines, where N is
        # the number of jumps in the pam_unix success=N statement. Ignore commented and empty lines.

        append_position=$(cat -n "${pam_file}" \
                          | grep -P "^\s+\d+\s+auth\s+.*$" \
                          | grep -w "pam_unix.so" -A $(( num_lines - 1 )) \
                          | tail -n 1 | cut -f 1 | tr -d ' '
                         )
        sed -i --follow-symlinks ''${append_position}'a auth        [default=die]      pam_faillock.so authfail' "$pam_file"
    else
        sed -i --follow-symlinks '/^auth.*pam_unix\.so.*/a auth        [default=die]      pam_faillock.so authfail' "$pam_file"
    fi
fi
if ! grep -qE '^\s*auth\s+sufficient\s+pam_faillock\.so\s+authsucc.*$' "$pam_file" ; then
    sed -i --follow-symlinks '/^auth.*pam_faillock\.so.*authfail.*/a auth        sufficient      pam_faillock.so authsucc' "$pam_file"
fi

pam_file="/etc/pam.d/common-account"
if ! grep -qE '^\s*account\s+required\s+pam_faillock\.so.*$' "$pam_file" ; then
    {{% if  product in ['sle15', 'sle16'] %}}
    # insert before pam_unix.so(so only consecutive authentication failures are lock)
    sed -i --follow-symlinks '/^account.*required.*pam_unix\.so.*/i account   required     pam_faillock.so' "$pam_file"
    {{% else %}}
    echo 'account   required     pam_faillock.so' >> "$pam_file"
    {{% endif %}}
fi
{{% elif 'ubuntu' in product %}}
conf_name=cac_faillock

if [ ! -f /usr/share/pam-configs/"$conf_name" ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"
Name: Enable pam_faillock to deny access
Default: yes
Conflicts: faillock
Priority: 0
Auth-Type: Primary
Auth:
    [default=die]                   pam_faillock.so authfail
EOF
fi

if [ ! -f /usr/share/pam-configs/"$conf_name"_notify ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"_notify
Name: Notify of failed login attempts and reset count upon success
Default: yes
Conflicts: faillock_notify
Priority: 1025
Auth-Type: Primary
Auth:
    requisite                       pam_faillock.so preauth
Account-Type: Primary
Account:
    required                        pam_faillock.so
EOF
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update

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


{{%- macro bash_pam_faillock_enable() -%}}
if [ -f /usr/bin/authselect ]; then
    {{{ bash_enable_pam_faillock_with_authselect() }}}
else
    {{{ bash_enable_pam_faillock_directly_in_pam_files() }}}
fi
{{%- endmacro -%}}


{{#
    Enable pam_pwquality.so PAM module by using pam-auth-update.
    This option is only recommended when pam-auth-update tool is available for the system.
#}}
{{%- macro bash_pam_pwquality_enable() -%}}
conf_name=cac_pwquality
if [ ! -f /usr/share/pam-configs/"$conf_name" ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"
Name: Pwquality password strength checking
Default: yes
Priority: 1025
Conflicts: cracklib, pwquality
Password-Type: Primary
Password:
    requisite                   pam_pwquality.so
EOF
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update
{{%- endmacro -%}}


{{#
    Enable pam_unix.so PAM module by using pam-auth-update.
    This option is only recommended when pam-auth-update tool is available for the system.
#}}
{{%- macro bash_pam_unix_enable() -%}}
conf_name=cac_unix
conf_path="/usr/share/pam-configs"

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

{{%- endmacro -%}}


{{#
    Validate an authselect custom profile integrity and ensures the correct file path is defined
    in the "PAM_FILE_PATH" variable. The macros which change PAM files are the same regardless of
    using authselect or not. The only change is the file path. However, this file path can change
    depending on the custom profile name used in the system. So, based on the informed PAM file,
    the macro will properly locate the correct profile and file to be edited in the authselect
    context. This sequence of commands is used in multiple PAM related macros.

:param pam_file:    PAM config file.
:type pam_file: str

#}}
{{%- macro bash_ensure_pam_variables_and_authselect_profile(pam_file) -%}}
{{{ bash_check_authselect_integrity() }}}
{{# the following macro ensures the CURRENT_PROFILE variable is properly set #}}
{{{ bash_ensure_authselect_custom_profile() }}}
PAM_FILE_NAME=$(basename "{{{ pam_file }}}")
PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Ensure pam_lastlog.so PAM module shows the failed logins according to the system capabilities.
    If authselect is present and the "with-silent-lastlog" feature is available, the feature will be disabled.
    If authselect is present but the "with-silent-lastlog" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

:param pam_file:    PAM config file.
:type pam_file: str
:param control:     PAM control flags.
:type control: str
:param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                    Note: For this macro, there is a special value used to include a line at
                    the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_pam_lastlog_enable_showfailed(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features sssd | grep -q with-silent-lastlog; then
        {{{ bash_disable_authselect_feature('with-silent-lastlog') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(8) }}}
        {{{ bash_remove_pam_module_option_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog.so', 'silent') | indent(8) }}}
    fi
else
    {{{ bash_ensure_pam_module_configuration(pam_file, 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(8) }}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'session', control, 'pam_lastlog.so', 'silent') | indent(8) }}}
fi
{{%- endmacro -%}}

{{#
    Ensure pam_lastlog2.so PAM module shows the failed logins according to the system capabilities.
    If authselect is present and the "with-silent-lastlog" feature is available, the feature will be disabled.
    If authselect is present but the "with-silent-lastlog" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

:param pam_file:    PAM config file.
:type pam_file: str
:param control:     PAM control flags.
:type control: str
:param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                    Note: For this macro, there is a special value used to include a line at
                    the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_pam_lastlog2_enable_showfailed(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features sssd | grep -q with-silent-lastlog; then
        {{{ bash_disable_authselect_feature('with-silent-lastlog') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog2.so', 'showfailed', '', after_match) | indent(8) }}}
        {{{ bash_remove_pam_module_option_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog2.so', 'silent') | indent(8) }}}
    fi
else
    {{{ bash_ensure_pam_module_configuration(pam_file, 'session', control, 'pam_lastlog2.so', 'showfailed', '', after_match) | indent(8) }}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'session', control, 'pam_lastlog2.so', 'silent') | indent(8) }}}
fi
{{%- endmacro -%}}

{{#
    Enable pam_pwhistory.so PAM module according to the system capabilities.
    If authselect is present and the "with-pwhistory" feature is available, the feature will be enabled.
    If authselect is present but the "with-pwhistory" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

:param pam_file:    PAM config file.
:type pam_file: str
:param control:     PAM control flags.
:type control: str
:param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                    Note: For this macro, there is a special value used to include a line at
                    the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_pam_pwhistory_enable(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features sssd | grep -q with-pwhistory; then
        {{{ bash_enable_authselect_feature('with-pwhistory') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", 'password', control, 'pam_pwhistory.so', after_match) | indent(8) }}}
    fi
else
{{% if 'ubuntu' in product or 'debian' in product %}}
conf_name={{{ pam_file }}}
conf_path="/usr/share/pam-configs"

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

DEBIAN_FRONTEND=noninteractive pam-auth-update
{{% else %}}
    {{{ bash_ensure_pam_module_line(pam_file, 'password', control, 'pam_pwhistory.so', after_match) | indent(4) }}}
{{% endif %}}
fi
{{%- endmacro -%}}


{{#
    Set pam_pwhistory.so PAM module options and values. In case the file
    /etc/security/pwhistory.conf is present in the system, the option is ensured there and removed
    from pam files to avoid conflicts or confusion.

:param pam_file:    PAM config file.
:type pam_file: str
:param option:      pwhistory option e.g.: remember, retry, debug
:type option: str
:param value:       value of option
:type value: str

#}}
{{%- macro bash_pam_pwhistory_parameter_value(pam_file, option, value='') -%}}
PWHISTORY_CONF="{{{ pwhistory_path }}}"
if [ -f $PWHISTORY_CONF ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $PWHISTORY_CONF; then
        echo $line >> $PWHISTORY_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $PWHISTORY_CONF
    fi
    {{%- endif %}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'password', '', 'pam_pwhistory.so', option ) | indent(4) }}}
else
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", 'password', 'requisite', 'pam_pwhistory.so', option, value, '') | indent(4) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
fi
{{%- endmacro -%}}


{{#
    Sets PAM faillock module options and values. In case the file
    "{{{ pam_faillock_conf_path }}}" is present in the system, the option is removed from pam files
    since it is not needed there in that case.
    It also adds pam_faillock.so as required module for account.

:param option: faillock option eg. deny, unlock_time, fail_interval
:type option: str
:param value: value of option
:type value: str
:param authfail: check the pam_faillock.so conf line with authfail
:type authfail: bool

#}}
{{%- macro bash_pam_faillock_parameter_value(option, value='', authfail=True) -%}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['sle15', 'sle16'] %}}
AUTH_FILES=("/etc/pam.d/common-auth")
SKIP_FAILLOCK_CHECK=true
{{% else %}}
AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
SKIP_FAILLOCK_CHECK=false
{{% endif %}}
FAILLOCK_CONF="{{{ pam_faillock_conf_path }}}"
if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $FAILLOCK_CONF; then
        echo $line >> $FAILLOCK_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $FAILLOCK_CONF
    fi
    {{%- endif %}}
    {{% if 'ubuntu' not in product %}}
    for pam_file in "${AUTH_FILES[@]}"
    do
        {{{ bash_remove_pam_module_option_configuration("$pam_file",'auth','','pam_faillock.so', option ) | indent(8) }}}
    done
    {{% endif %}}
else
    for pam_file in "${AUTH_FILES[@]}"
    do
        if ! grep -qE '^\s*auth.*pam_faillock\.so\s+(preauth|authfail).*{{{ option }}}' "$pam_file"; then
            {{%- if value == '' %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- endif %}}
            {{%- else %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- endif %}}
            {{%- endif %}}
        {{%- if value == '' %}}
        fi
        {{%- else %}}
        else
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"{{{ option }}}"'=\)\S\+\b\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"{{{ option }}}"'=\)\S\+\b\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- endif %}}
        fi
        {{%- endif %}}
    done
fi
{{%- endmacro -%}}


{{#
    Sets PAM pwquality module options and values. The module argument is not removed from pam files
    since it is not inserted there in Ubuntu case.
    It also assume pam_pwquality.so is added as required module for account.

:param option: pwquality option eg. retry, minlen, dcredit
:type option: str
:param value: value of option
:type value: str

#}}
{{%- macro bash_pam_pwquality_parameter_value(option, value='') -%}}
PWQUALITY_CONF="/etc/security/pwquality.conf"
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $PWQUALITY_CONF; then
        echo $line >> $PWQUALITY_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $PWQUALITY_CONF
    fi
    {{%- endif %}}
{{%- endmacro -%}}


{{#
    Print a message to stderr and exit the shell

:param message: The message to print.
:type message: str
:param rc: The error code (optional, default is 1)
:type rc: int
:param action: What to do (optional, default is 'exit', can be also 'return' or anything else)
:type action: str

#}}
{{% macro die(message, rc=1, action="exit") -%}}
printf '%s\n' "{{{ message | replace('"', '\\"') }}}" >&2
{{{ action }}} {{{ rc }}}
{{%- endmacro %}}


{{#
    Add an entry to a text configuration file

:param path: path of the configuration file
:type path: str
:param parameter: the parameter to be set in the configuration file
:type parameter: str
:param value: the value of the parameter to be set in the configuration file
:type value: str
:param create: whether create the file specified by path if the file does not exits
:type create: bool
:param insert_after: inserts the entry right after first line that matches regular expression specified by this argument, set to EOF to insert at the end of the file
:type insert_after: str
:param insert_before: inserts the entry right before first line that matches regular expression specified by this argument, set to BOF to insert at the beginning of the file
:type insert_before: str
:param insensitive: ignore case
:type insensitive: bool
:param separator: separates parameter from the value (literal)
:type separator: str
:param separator_regex: regular expression that describes the separator and surrounding whitespace
:type separator_regex: str
:param prefix_regex: regular expression describing allowed leading characters at each line
:type prefix_regex: str
:param sed_path_separator:
:type sed_path_separator: char

#}}
{{%- macro set_config_file(path, parameter, value, create, insert_after, insert_before, insensitive=true, separator=" ", separator_regex="\s\+", prefix_regex="^\s*", sed_path_separator="/", rule_id=None) -%}}
    {{%- set new_line = parameter+separator~value -%}}
    {{#- An escaped dollar in the parameter is escaped because of its significance for the shell, so when making a regex out of the parameter, we remove the shell escape, as the regex escape will do its thing. -#}}
    {{%- set line_regex = prefix_regex + ((parameter | replace("\\$", "$") | escape_regex) | replace("/", "\/")) + separator_regex -%}}
if [ -e "{{{ path }}}" ] ; then
    {{{ lineinfile_absent(path, line_regex, insensitive, sed_path_separator=sed_path_separator, rule_id=rule_id) | indent(4) }}}
else
    {{%- if create %}}
    touch "{{{ path }}}"
    {{%- else %}}
    {{{ die("Path '" + path + "' wasn't found on this system. Refusing to continue.", action="return") | indent(4) }}}
    {{%- endif %}}
fi
{{{ lineinfile_present(path, new_line, insert_after, insert_before, insensitive, sed_path_separator=sed_path_separator) }}}
{{%- endmacro -%}}


{{%- macro lineinfile_absent(path, regex, insensitive=true, sed_path_separator="/", rule_id=None) -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
    {{% if sed_path_separator in regex %}}
    {{{ raise("regex (" + regex + ") uses sed path separator (" + sed_path_separator + ") in " + rule_id) }}}
    {{% endif %}}
LC_ALL=C sed -i "{{{ sed_path_separator }}}{{{ regex }}}{{{ sed_path_separator }}}{{{ modifier }}}" "{{{ path }}}"
{{%- endmacro -%}}


{{%- macro lineinfile_absent_in_directory(dirname, regex, insensitive=true, filename_glob="*") -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
LC_ALL=C sed -i "/{{{ regex }}}/{{{ modifier }}}" "{{{ dirname }}}"/{{{ filename_glob }}}
{{%- endmacro -%}}


{{%- macro lineinfile_present(path, line, insert_after="", insert_before="", insensitive=true, sed_path_separator="/") -%}}
    {{%- if insensitive -%}}
        {{%- set grep_args="-q -m 1 -i" -%}}
    {{%- else -%}}
        {{%- set grep_args="-q -m 1" -%}}
    {{%- endif -%}}
# make sure file has newline at the end
sed -i -e '$a\' "{{{ path }}}"

cp "{{{ path }}}" "{{{ path }}}.bak"
    {{%- if not (insert_after or insert_before)  or insert_after == "EOF" %}}
# Insert at the end of the file
printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    {{%- elif insert_before == "BOF" %}}
# Insert at the beginning of the file
printf '%s\n' "{{{ line }}}" > "{{{ path }}}"
cat "{{{ path }}}.bak" >> "{{{ path }}}"
    {{%- elif insert_after %}}
# Insert after the line matching the regex '{{{ insert_after }}}'
line_number="$(LC_ALL=C grep -n "{{{ insert_after }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_after }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number + 1 ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- elif insert_before %}}
# Insert before the line matching the regex '{{{ insert_before }}}'.
line_number="$(LC_ALL=C grep -n "{{{ insert_before }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_before }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number - 1 ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- else %}}
{{{ die("This remediation has been generated incorrectly.") }}}
    {{%- endif %}}
# Clean up after ourselves.
rm "{{{ path }}}.bak"
{{%- endmacro -%}}


{{#
  Generates bash script code that puts 'contents' into a file at 'filepath'

:param filepath: Filepath of the file to check
:type filepath: str
:param contents:  Contents that should be in the file
:type contents: str

#}}
{{%- macro bash_file_contents(filepath='', contents='') %}}
cat << 'EOF' > {{{ filepath }}}
{{{ contents }}}
EOF
{{%- endmacro %}}


{{# Strips anchors regex around the banner text #}}
{{% macro bash_deregexify_banner_anchors(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^\^\(.*\)\$$/\1/g')
{{%- endmacro %}}


{{# Strips multibanner regex and keeps only the first banner #}}
{{% macro bash_deregexify_multiple_banners(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^(\(.*\.\)|.*)$/\1/g')
{{%- endmacro %}}


{{# Strips whitespace or newline regex #}}
{{% macro bash_deregexify_banner_space(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\[\\s\\n\]+/ /g')
{{%- endmacro %}}


{{# Strips newline or newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline(banner_var_name, newline) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(?:\[\\n\]+|(?:\\\\n)+)/{{{ newline }}}/g')
{{%- endmacro %}}


{{# Strips newline token for a newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline_token(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(n)\*/\\n/g')
{{%- endmacro %}}


{{# Strips backslash regex #}}
{{% macro bash_deregexify_banner_backslash(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\\//g')
{{%- endmacro %}}


{{% macro bash_ini_file_set(filename, section, key, value, rule_id=None) -%}}
{{% set config_dir = "/".join(filename.split("/")[:-1]) %}}
# Try find '[{{{ section }}}]' and '{{{ key }}}' in '{{{ filename }}}', if it exists, set
# to '{{{ value }}}', if it isn't here, add it, if '[{{{ section }}}]' doesn't exist, add it there
if grep -qzosP '[[:space:]]*\[{{{ section }}}]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}' '{{{ filename }}}'; then
    {{% if '/' in key %}}
    {{{ raise("key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
    {{% elif '/' in value %}}
    {{{ raise("value (" + value + ") uses sed path separator (/) in " + rule_id) }}}
    {{% endif %}}
    sed -i "s/{{{ key }}}[^(\n)]*/{{{ key }}}={{{ value }}}/" '{{{ filename }}}'
elif grep -qs '[[:space:]]*\[{{{ section }}}]' '{{{ filename }}}'; then
    sed -i "/[[:space:]]*\[{{{ section }}}]/a {{{ key }}}={{{ value }}}" '{{{ filename }}}'
else
    if test -d "{{{ config_dir }}}"; then
        printf '%s\n' '[{{{ section }}}]' "{{{ key }}}={{{ value }}}" >> '{{{ filename }}}'
    else
        echo "Config file directory '{{{ config_dir }}}' doesnt exist, not remediating, assuming non-applicability." >&2
    fi
fi
{{%- endmacro %}}


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

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

{{% macro bash_sssd_ldap_config(parameter, value, rule_id=None) -%}}
SSSD_CONF="/etc/sssd/sssd.conf"
LDAP_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*{{{ parameter }}}'
AD_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*id_provider[[:space:]]*=[[:space:]]*((?i)ad)[[:space:]]*$'
DOMAIN_REGEX="[[:space:]]*\[domain\/[^]]*]"

# Check if id_provider is not set to ad (Active Directory) which makes start_tls not applicable, note the -v option to invert the grep.
# Try to find [domain/..] and {{{ parameter }}} in sssd.conf, if it exists, set to '{{{ value }}}'
# if {{{ parameter }}} isn't here, add it
# if [domain/..] doesn't exist, add it here for default domain
if grep -qvzosP $AD_REGEX $SSSD_CONF; then
        if grep -qzosP $LDAP_REGEX $SSSD_CONF; then
                {{% if '#' in parameter %}}
                {{{ raise("parameter (" + parameter + ") uses sed path separator (#) in " + rule_id) }}}
                {{% endif %}}
                sed -i "s#{{{ parameter }}}[^(\n)]*#{{{ parameter }}} = {{{ value }}}#" $SSSD_CONF
        elif grep -qs $DOMAIN_REGEX $SSSD_CONF; then
                sed -i "/$DOMAIN_REGEX/a {{{ parameter }}} = {{{ value }}}" $SSSD_CONF
        else
                if test -f "$SSSD_CONF"; then
                        echo -e "[domain/default]\n{{{ parameter }}} = {{{ value }}}" >> $SSSD_CONF
                else
                        echo "Config file '$SSSD_CONF' doesnt exist, not remediating, assuming non-applicability." >&2
                fi
        fi
fi

readarray -t SSSD_CONF_D_FILES < <(find /etc/sssd/conf.d/ -name "*.conf")
for SSSD_CONF_D_FILE in "${SSSD_CONF_D_FILES[@]}"; do
    sed -i "s#{{{ parameter }}}[^(\n)]*#{{{ parameter }}} = {{{ value }}}#" "$SSSD_CONF_D_FILE"
done

{{%- endmacro %}}


{{#
    Check whether or not a package is installed.
#}}
{{%- macro bash_package_installed(pkgname) -%}}
{{%- if pkg_manager == "apt_get" -%}}
dpkg-query --show --showformat='${db:Status-Status}' "{{{ pkgname }}}" 2>/dev/null | grep -q '^installed$'
{{%- else -%}}
rpm --quiet -q "{{{ pkgname }}}"
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Set rule CCE value

    This macro gets the var cce_identifiers from the environment created by the build scripts.
    The cce_identifiers is a dictionary that contains either the 'cce':'CCENUM' record for the
    product this remediation is being built for, or it is empty.

#}}
{{%- macro set_cce_value(cce_identifiers=None) -%}}
{{% if cce_identifiers and 'cce' in cce_identifiers -%}}
cce="{{{ cce_identifiers['cce'] }}}"
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Ensure file ends with newline

    Do not modify file at all if there already is newline. Always follows
    symlinks.

:param file:     file to check
:type file: str

#}}
{{%- macro bash_ensure_nl_at_eof(file) -%}}
{{#- Plain sed '$a\' updates stat even if it dones not change the file. -#}}
if [[ -s "{{{ file }}}" ]] && [[ -n "$(tail -c 1 -- "{{{ file }}}" || true)" ]]; then
    LC_ALL=C sed -i --follow-symlinks '$a'\\ "{{{ file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro to replace configuration setting in config file or add the configuration setting if
    it does not exist.

    Example Calls:

      With default format of 'key = value'::

        {{{ bash_replace_or_append('/etc/sysctl.conf', '^kernel.randomize_va_space', '2', cce_identifiers=cce_identifiers) }}}

      With custom key/value format::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', 'disabled', '%s=%s', cce_identifiers=cce_identifiers) }}}

      With a variable::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', "$var_selinux_state", '%s=%s', cce_identifiers=cce_identifiers) }}}

:param config_file: Configuration file that will be modified
:type config_file: str
:param key: Configuration option to change
:type key: str
:param value: Value of the configuration option to change
:type value: str
:param format: Optional argument, 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 substitution (i.e. without spaces around =)
:type format: str

#}}

{{%- macro bash_comment_config_line(config_file, key) -%}}
# If the key exists, comment it. Otherwise do nothing
# We search for the key string followed by a blank space,
# so if we search for 'setting', 'setting2' won't match.
if LC_ALL=C grep -q -m 1 -i -e "{{{ key }}}[[:blank:]]" "{{{ config_file }}}"; then
    LC_ALL=C sed -i --follow-symlinks "s/{{{ key }}}[[:blank:]].*/#&/gi" "{{{ config_file }}}"
fi
{{%- endmacro -%}}



{{%- macro bash_replace_or_append(config_file, key, value, format='%s = %s', cce_identifiers=None) -%}}
# 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 LC_ALL=C grep -q -m 1 -i -e "{{{ key }}}\\>" "{{{ config_file }}}"; then
    escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
    LC_ALL=C sed -i --follow-symlinks "s/{{{ key }}}\\>.*/$escaped_formatted_output/gi" "{{{ config_file }}}"
else
    {{{ bash_ensure_nl_at_eof(config_file) | indent }}}
    {{%- if cce_identifiers and 'cce' in cce_identifiers %}}
    {{{ set_cce_value(cce_identifiers=cce_identifiers) }}}
    printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "{{{ config_file }}}" >> "{{{ config_file }}}"
    {{%- endif %}}
    printf '%s\n' "$formatted_output" >> "{{{ config_file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro to restrict permissions in home directories of interactive users.

#}}
{{%- macro bash_restrict_permissions_home_directories(recursive=false) -%}}
for home_dir in $(awk -F':' '{ if ($3 >= {{{ uid_min }}} && $3 != {{{ nobody_uid }}} && $6 != "/") print $6 }' /etc/passwd); do
    # Only update the permissions when necessary. This will avoid changing the inode timestamp when
    # the permission is already defined as expected, therefore not impacting in possible integrity
    # check systems that also check inodes timestamps.
    {{%- if recursive %}}
    find "$home_dir" -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    {{%- else %}}
    find "$home_dir" -maxdepth 0 -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    {{%- endif %}}
done
{{%- endmacro -%}}


{{#
    To see how args corresponds to an :code:`/etc/fstab` entry, see
    `bash_ensure_mount_option_for_vfstype <#template-bash_ensure_mount_option_in_fstab>`_
    documentation

:param vfstype:     type of filesystem
:type vfstype: str
:param mount_opt:   mount point option which we are checking
:type mount_opt: str
:param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
:type fs_spec: str
:param type:        mount type of new mount point (used when adding new entry in fstab)
:type type: str

#}}
{{% macro bash_ensure_mount_option_for_vfstype(vfstype, mount_opt, fs_spec, type) -%}}
vfstype_points=()
readarray -t vfstype_points < <(grep -E "[[:space:]]{{{ vfstype }}}[[:space:]]" /etc/fstab | awk '{print $2}')

for vfstype_point in "${vfstype_points[@]}"
do
    {{{ bash_ensure_mount_option_in_fstab("${vfstype_point//\\\\/\\\\\\\\}", mount_opt, fs_spec, type) | indent(4) }}}
done
{{%- endmacro %}}


{{#
Ensures that given mount point is in :code:`/etc/fstab`.

    If we look at an example invocation of this macro::

        {{{ bash_ensure_mount_option_in_fstab("/home", "auto_da_alloc", "LABEL=t-home2", "ext4") }}}}

    The resulting :code:`/etc/fstab` entry could look like this::

        LABEL=t-home2   /home      ext4    defaults,auto_da_alloc      0  2

:param mount_point: mount point
:type mount_point: str
:param mount_opt:   mount point option whose presence in /etc/fstab we are ensuring
:type mount_opt: str
:param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
:type fs_spec: str
:param type:        mount type of mount point (used when adding new entry in fstab)
:type type: str

#}}
{{% macro bash_ensure_mount_option_in_fstab(mount_point, mount_opt, fs_spec, type) -%}}
mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" {{{ mount_point }}})"

# If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
    # runtime opts without some automatic kernel/userspace-added defaults
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                | sed -E "s/(rw|defaults|seclabel|{{{ mount_opt }}})(,|$)//g;s/,$//")
    [ "$previous_mount_opts" ] && previous_mount_opts+=","
    # In iso9660 filesystems mtab could describe a "blocksize" value, this should be reflected in
    # fstab as "block".  The next variable is to satisfy shellcheck SC2050.
    fs_type="{{{ type }}}"
    if [  "$fs_type" == "iso9660" ] ; then
        previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
    fi
    echo "{{{ fs_spec }}} {{{ mount_point }}} {{{ type }}} defaults,${previous_mount_opts}{{{ mount_opt }}} 0 0" >> /etc/fstab
# If the mount_opt option is not already in the mount point's /etc/fstab entry, add it
elif ! grep "$mount_point_match_regexp" /etc/fstab | grep -q "{{{ mount_opt }}}"; then
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/fstab | awk '{print $4}')
    sed -i "s|\(${mount_point_match_regexp}.*${previous_mount_opts}\)|\1,{{{ mount_opt }}}|" /etc/fstab
fi
{{%- endmacro %}}


{{#
    Check whether mount_point is present in /etc/fstab; print err to stderr and return 1 if not

#}}
{{% macro bash_assert_mount_point_in_fstab(mount_point) -%}}
mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "{{{ mount_point }}}")"
{{#
    This macro gets expanded to code that will return 1 if MOUNTPOINT is not in /etc/fstab;
    This is consistent with the behavior prior to converting this function to a jinja macro
#}}
grep "$mount_point_match_regexp" -q /etc/fstab \
    || { echo "The mount point '{{{ mount_point }}}' is not even in /etc/fstab, so we can't set up mount options" >&2;
            echo "Not remediating, because there is no record of {{{ mount_point }}} in /etc/fstab" >&2; return 1; }
{{%- endmacro %}}


{{#
  Ensure that partition is mounted at mount_point with correct options, but only if the partition
  is already mounted.

#}}
{{% macro bash_ensure_partition_is_mounted(mount_point) -%}}
if mkdir -p "{{{ mount_point }}}"; then
    if mountpoint -q "{{{ mount_point }}}"; then
        mount -o remount --target "{{{ mount_point }}}"
    fi
fi
{{%- endmacro %}}


{{#
Based on example audit syscall rule definitions as outlined in
:code:`/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.

Notes:

* The 2-nd up to 4-th arguments are used to determine how many existing audit
  rules will be inspected for resemblance with the new audit rule the macro
  is going to add.
* The macro's similarity check uses the 5-th argument to optimize audit rules
  definitions (merge syscalls of the same group into one rule) to avoid the
  "single-syscall-per-audit-rule" performance penalty.
* The key argument (7-th argument) is not used when the syscall is grouped to
  an existing audit rule. The audit rule will retain the key it already had.

:param tool:  tool used to load audit rules, either 'auditctl', or 'augenrules
:type tool: str
:param action_arch_filters: The action and arch filters of the rule. For example, "-a always,exit -F arch=b64"
:type action_arch_filters: str
:param other_filters: Other filters that may characterize the rule. For example, "-F a2&03 -F path=/etc/passwd"
:type other_filters: str
:param auid_filters: The auid filters of the rule. For example, "-F auid>=" ~ uid_min ~ " -F auid!=unset"
:type auid_filters: str
:param syscall: The syscall to ensure presense among audit rules. For example, "chown"
:type syscall: str
:param syscall_groupings: Other syscalls that can be grouped with 'syscall' as a space separated list. For example, "fchown lchown fchownat"
:type syscall_groupings: str
:param key: The key to use when appending a new rule
:type key: str

#}}
{{% macro bash_fix_audit_syscall_rule(tool, action_arch_filters, other_filters, auid_filters, syscall, syscall_groupings, key) -%}}

unset syscall_a
unset syscall_grouping
unset syscall_string
unset syscall
unset file_to_edit
unset rule_to_edit
unset rule_syscalls_to_edit
unset other_string
unset auid_string
unset full_rule

# Load macro arguments into arrays
read -a syscall_a <<< {{{ syscall }}}
read -a syscall_grouping <<< {{{ syscall_groupings }}}

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

{{% if tool == "auditctl" %}}
# If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# file to the list of files to be inspected
default_file="/etc/audit/audit.rules"
files_to_inspect+=('/etc/audit/audit.rules' )
{{%- else -%}}
# If audit tool is 'augenrules', then check if the audit rule is defined
# If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
# If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
default_file="/etc/audit/rules.d/{{{ key }}}.rules"
# As other_filters may include paths, lets use a different delimiter for it
# The "F" script expression tells sed to print the filenames where the expressions matched
readarray -t files_to_inspect < <(sed -s -n -e "/^{{{ action_arch_filters }}}/!d" -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" -e "F" /etc/audit/rules.d/*.rules)
# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
if [ ${#files_to_inspect[@]} -eq "0" ]
then
    file_to_inspect="/etc/audit/rules.d/{{{ key }}}.rules"
    files_to_inspect=("$file_to_inspect")
    if [ ! -e "$file_to_inspect" ]
    then
        touch "$file_to_inspect"
        chmod 0600 "$file_to_inspect"
    fi
fi
{{%- endif %}}

# After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
skip=1

for audit_file in "${files_to_inspect[@]}"
do
    # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
    # i.e, collect rules that match:
    # * the action, list and arch, (2-nd argument)
    # * the other filters, (3-rd argument)
    # * the auid filters, (4-rd argument)
    readarray -t similar_rules < <(sed -e "/^{{{ action_arch_filters }}}/!d"  -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" "$audit_file")

    candidate_rules=()
    # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
    for s_rule in "${similar_rules[@]}"
    do
        # Strip all the options and fields we know of,
        # than check if there was any field left over
        extra_fields=$(sed -E -e "s/^{{{ action_arch_filters }}}//"  -e "s#{{{ other_filters }}}##" -e "s/{{{ auid_filters }}}//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
        grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
    done

    if [[ ${#syscall_a[@]} -ge 1 ]]
    then
        # Check if the syscall we want is present in any of the similar existing rules
        for rule in "${candidate_rules[@]}"
        do
            rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
            all_syscalls_found=0
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                   # A syscall was not found in the candidate rule
                   all_syscalls_found=1
                   }
            done
            if [[ $all_syscalls_found -eq 0 ]]
            then
                # We found a rule with all the syscall(s) we want; skip rest of macro
                skip=0
                break
            fi

            # Check if this rule can be grouped with our target syscall and keep track of it
            for syscall_g in "${syscall_grouping[@]}"
            do
                if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                then
                    file_to_edit=${audit_file}
                    rule_to_edit=${rule}
                    rule_syscalls_to_edit=${rule_syscalls}
                fi
            done
        done
    else
        # If there is any candidate rule, it is compliant; skip rest of macro
        if [ "${#candidate_rules[@]}" -gt 0 ]
        then
            skip=0
        fi
    fi

    if [ "$skip" -eq 0 ]; then
        break
    fi
done

if [ "$skip" -ne 0 ]; then
    # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
    # At this point we know if we need to either append the $full_rule or group
    # the syscall together with an exsiting rule

    # Append the full_rule if it cannot be grouped to any other rule
    if [ -z ${rule_to_edit+x} ]
    then
        # Build full_rule while avoid adding double spaces when other_filters is empty
        if [ "${#syscall_a[@]}" -gt 0 ]
        then
            syscall_string=""
            for syscall in "${syscall_a[@]}"
            do
                syscall_string+=" -S $syscall"
            done
        fi
        other_string=$([[ {{{ other_filters }}} ]] && echo " {{{ other_filters }}}") || /bin/true
        auid_string=$([[ {{{ auid_filters }}} ]] && echo " {{{ auid_filters }}}") || /bin/true
        full_rule="{{{ action_arch_filters }}}${syscall_string}${other_string}${auid_string} -F key={{{ key }}}" || /bin/true
        echo "$full_rule" >> "$default_file"
        chmod 0600 ${default_file}
    else
        # Check if the syscalls are declared as a comma separated list or
        # as multiple -S parameters
        if grep -q -- "," <<< "${rule_syscalls_to_edit}"
        then
            delimiter=","
        else
            delimiter=" -S "
        fi
        new_grouped_syscalls="${rule_syscalls_to_edit}"
        for syscall in "${syscall_a[@]}"
        do
            grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
               # A syscall was not found in the candidate rule
               new_grouped_syscalls+="${delimiter}${syscall}"
               }
        done

        # Group the syscall in the rule
        sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
    fi
fi
{{%- endmacro %}}


{{#
    Ensures that /etc/default/grub file contains the arg_name_value.

:param arg_name: name of the grub parameter, e.g.: "audit"
:type arg_name: str
:param arg_name_value: parameter together with the value to ensure, e.g.: "audit=1"
:type arg_name_value: str

#}}
{{%- macro update_etc_default_grub_manually(arg_name, arg_name_value) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q '^\s*GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"'  '/etc/default/grub' ; then
       # modify the GRUB command-line if an {{{ arg_name }}}= arg already exists
       sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\){{{ arg_name }}}=[^[:space:]]\+\(.*\"\)/\1{{{ arg_name_value }}}\2/"  '/etc/default/grub'
# Add to already existing GRUB_CMDLINE_LINUX parameters
elif grep -q '^\s*GRUB_CMDLINE_LINUX='  '/etc/default/grub' ; then
       # no {{{ arg_name }}}=arg is present, append it
       sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)\"/\1 {{{ arg_name_value }}}\"/"  '/etc/default/grub'
# Add GRUB_CMDLINE_LINUX parameters line
else
       echo "GRUB_CMDLINE_LINUX=\"{{{ arg_name_value }}}\"" >> '/etc/default/grub'
fi
{{%- endmacro %}}


{{#
Macro for Bash remediation for adding a kernel command line argument to the GRUB 2 bootloader.
Part of the grub2_bootloader_argument template.

:param arg_name: Kernel command line argument
:type arg_name: str
:param arg_name_value: Kernel command line argument concatenated with the value of this argument using an equal sign, eg. "noexec=off".
:type arg_name_value: str

#}}
{{% macro grub2_bootloader_argument_remediation(arg_name, arg_name_value) %}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15', 'sle16', 'slmicro5'] %}}
{{{ update_etc_default_grub_manually(arg_name, arg_name_value) }}}
{{% endif -%}}
{{{ grub_command("add", arg_name_value) }}}
{{% endmacro %}}


{{#
    Ensures that /etc/default/grub file does not contain the arg_name_value.

:param arg_name: name of the grub parameter, e.g.: "audit"
:type arg_name: str

#}}
{{%- macro update_etc_default_grub_manually_absent(arg_name) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q -E '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=?.*"'  '/etc/default/grub' ; then
       sed -i 's/\(^GRUB_CMDLINE_LINUX=".*\){{{ arg_name }}}=\?[^[:space:]]*\(.*"\)/\1 \2/' '/etc/default/grub'
fi
{{%- endmacro %}}


{{#
Macro for Bash remediation for removing a kernel command line argument from the GRUB 2 bootloader.
Part of the grub2_bootloader_argument_absent template.

:param arg_name: Name of the kernel command line argument that will be removed from GRUB 2 configuration.
:type arg_name: str

#}}
{{% macro grub2_bootloader_argument_absent_remediation(arg_name) %}}
{{% if 'ubuntu' in product or product in ['ol7', 'sle12', 'sle15', 'sle16', 'slmicro5'] %}}
{{{ update_etc_default_grub_manually_absent(arg_name) }}}
{{% endif -%}}
{{{ grub_command("remove", arg_name) }}}
{{% endmacro %}}


{{#
This macro creates a bash conditional which is used to determine if a
remediation is applicable. The macro takes package as an argument and chooses
appropriate package manager. If the package is installed and satisfies the
optional version restricion, the Bash remediation will be applied. The macro
respects `platform_package_overrides` variable.

:param package: package name
:type package: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_pkg_conditional(package, op=None, ver=None) -%}}
{{%- if package in platform_package_overrides -%}}
  {{%- set package = platform_package_overrides[package] -%}}
{{%- endif -%}}
  {{% if pkg_system is defined %}}
    {{%- if pkg_system == "rpm" -%}}
        {{{ bash_pkg_conditional_rpm(package, op, ver) }}}
    {{%- elif pkg_system == "dpkg" -%}}
        {{{ bash_pkg_conditional_dpkg(package, op, ver) }}}
    {{%- else -%}}
JINJA MACRO ERROR - Unknown package system '{{{ pkg_system }}}'.
    {{%- endif -%}}
{{% endif %}}
{{%- endmacro -%}}


{{#
This macro generates code that gets version of an installed RPM package.

:param package: package name
:type package: str

#}}
{{%- macro bash_get_rpm_package_version(package) -%}}
$(epoch=$(rpm -q --queryformat '%{EPOCH}' {{{ package }}}); version=$(rpm -q --queryformat '%{VERSION}' {{{ package }}}); [ "$epoch" = "(none)" ] && echo "0:$version" || echo "$epoch:$version")
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional that compares version of the package
with a given version.

Description of the algorithm:

#. Get the actual version of the given package and store it in `real`.
#. Store the expected version in `ver`.
#. Perform the comparison and return the result.
   Comparison method is different based on the comparison operator. The method
   code is chosen at the build time during Jinja expansion. Therefore, the
   algorithm doesn't use the operator at all.
   Based on the operator, these operations are performed:

   #. "<": real != ver && is_sorted([real, ver])
   #. "<=": is_sorted([real, ver])
   #. "==": real == ver
   #. "!=": real != ver
   #. ">=" real != ver && is_sorted([ver, real])
   #. ">" is_sorted([ver, real])

   where is_sorted returns true if the given list parameter is a sorted list of version numbers.

The implementation uses the GNU `sort` version ordering, which is described at:
https://www.gnu.org/software/coreutils/manual/coreutils.html#Version-sort-ordering

:param real: real package version
:type real: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param expected: expected package version
:type expected: str

#}}
{{%- macro bash_pkg_conditional_compare(real, op, expected) -%}}
{ real="{{{ real }}}"; expected="{{{ expected }}}"; {{{ bash_compare_version("$real", op, "$expected") }}}; }
{{%- endmacro -%}}


{{#
This macro generates comparison code based on the operator.

Assumptions:

* Version arguments are either literal, or they expand to versions (e.g. the argument is a deferenced variable)
* Either all versions have epoch, or none of them has.

  * Violation of this results in undefined behavior.
  * If one has epoch e.g. 0, and the other one has no epoch, they will not be treated as equal.

:param real: real package version
:type real: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param expected: expected package version
:type expected: str

#}}
{{%- macro bash_compare_version(real, op, expected) -%}}
{{%- if op == "<" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]] && printf "%s\n%s" "{{{ real }}}" "{{{ expected }}}" | sort -VC
{{%- elif op == "<=" -%}}
printf "%s\n%s" "{{{ real }}}" "{{{ expected }}}" | sort -VC
{{%- elif op == "==" -%}}
[[ "{{{ real }}}" == "{{{ expected }}}" ]]
{{%- elif op == "!=" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]]
{{%- elif op == ">" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]] && printf "%s\n%s" "{{{ expected }}}" "{{{ real }}}" | sort -VC
{{%- elif op == ">=" -%}}
printf "%s\n%s" "{{{ expected }}}" "{{{ real }}}" | sort -VC
{{%- endif -%}}
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which uses rpm to check if a package passed as a parameter is installed.

:param package: package name
:type package: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
    The version always needs to contain epoch. If the package has no epoch, please prepend "0:".
:type ver: str

#}}
{{%- macro bash_pkg_conditional_rpm(package, op=None, ver=None) -%}}
{{%- if ver -%}}
rpm --quiet -q {{{ package }}} && {{{ bash_pkg_conditional_compare(bash_get_rpm_package_version(package), op, ver) }}}
{{%- else -%}}
rpm --quiet -q {{{ package }}}
{{%- endif -%}}
{{%- endmacro %}}


{{#
This macro generates code that gets version of an installed DEB package.

:param package: package name
:type package: str

#}}
{{%- macro bash_get_dpkg_package_version(package) -%}}
{{# We don't take the "release" part into account. #}}
dpkg-query -f='${Version}\n' --show {{{ package }}} | cut -f1 -d-
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional that compares version of the DEB package
with a given version.

:param package: package name
:type package: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_compare_version_dpkg(package, op, ver) -%}}
{{%- set op_codes = ({"<":"lt", "<=":"le", "==":"eq", "!=":"ne", ">":"gt", ">=":"ge"}) -%}}
{ real="$({{{ bash_get_dpkg_package_version(package) }}})"; ver="{{{ ver }}}"; dpkg --compare-versions "$real" "{{{ op_codes[op] }}}" "$ver"; }
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which uses dpkg to check if a package passed as a parameter is installed.

:param package: package name
:type package: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_pkg_conditional_dpkg(package, op=None, ver=None) -%}}
{{%- if ver -%}}
dpkg-query --show --showformat='${db:Status-Status}' '{{{ package }}}' 2>/dev/null | grep -q '^installed$' && {{{ bash_compare_version_dpkg(package, op, ver) }}}
{{%- else -%}}
dpkg-query --show --showformat='${db:Status-Status}' '{{{ package }}}' 2>/dev/null | grep -q '^installed$'
{{%- endif -%}}
{{%- endmacro -%}}

{{#
    Macro that lets you define the body of a loop that iterates over the output of the find command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "mydir -name *.conf") %}} ...

#}}
{{% macro iterate_over_find_output(varname, find_args="") -%}}
while IFS= read -r -d '' {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <(find {{{ find_args }}} -print0)
{{%- endmacro %}}


{{#
    Macro that lets you define the body of a loop that iterates over the output of any command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "awk ... myfile") %}} ...

#}}
{{% macro iterate_over_command_output(varname, command_and_its_args) -%}}
while IFS= read -r {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <({{{ command_and_its_args }}})
{{%- endmacro %}}


{{#
    Ensure key is set to correct value under a correct section in an .ini style config file

Example macro invocation(s)::

    {{{ bash_ensure_ini_config("/etc/sssd/sssd.conf", "pam", "offline_credentials_expiration", "1") }}}
    {{{ bash_ensure_ini_config("/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf", "sssd", "user", "sssd") }}}

:param files:   list of space-separated files to add key = value to (may contain wildcards)
                if none contain section, create and append to FIRST file
:type files: str
:param section: section to add key = value under
:type section: str
:param key:     key
:type key: str
:param value:   value
:type value: str

#}}
{{% macro bash_ensure_ini_config(files, section, key, value, no_quotes=true) -%}}
found=false

# set value in all files if they contain section or key
for f in $(echo -n "{{{ files }}}"); do
    if [ ! -e "$f" ]; then
        continue
    fi

    # find key in section and change value
    if grep -qzosP "(?m)^[[:space:]]*\[{{{ section }}}\]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}" "$f"; then
        if ! grep -qzosP "(?m)^[[:space:]]*{{{ key }}}[[:space:]]*=[[:space:]]*{{{ value }}}" "$f"; then
{{% if no_quotes %}}
            sed -i "/^[[:space:]]*{{{ key }}}/s/\([[:blank:]]*=[[:blank:]]*\).*/\1{{{ value | replace("/", "\/") }}}/" "$f"
{{% else %}}
            sed -i '/^[[:space:]]*{{{ key }}}/s/\([[:blank:]]*=[[:blank:]]*\).*/\1"{{{ value | replace("/", "\/") }}}"/' "$f"
{{% endif %}}
        fi

        found=true

    # find section and add key = value to it
    elif grep -qs "^[[:space:]]*\[{{{ section }}}\]" "$f"; then
{{% if no_quotes %}}
            sed -i "/^[[:space:]]*\[{{{ section }}}\]/a {{{ key }}}={{{ value | replace("/", "\/") }}}" "$f"
{{% else %}}
            sed -i '/^[[:space:]]*\[{{{ section }}}\]/a {{{ key }}}="{{{ value | replace ("/", "\/") }}}"' "$f"
{{% endif %}}
            found=true
    fi
done

# if section not in any file, append section with key = value to FIRST file in files parameter
if ! $found ; then
    file=$(echo "{{{ files }}}" | cut -f1 -d ' ')
    mkdir -p "$(dirname "$file")"
{{% if no_quotes %}}
    echo -e "[{{{ section }}}]\n{{{ key }}}={{{ value }}}" >> "$file"
{{% else %}}
    echo -e '[{{{ section }}}]\n{{{ key }}}="{{{ value }}}"' >> "$file"
{{% endif %}}
fi
{{%- endmacro %}}


{{#
    Ensure pam_unix.so module is enabled in specified PAM files and sections.
    Iterates through the provided PAM files and sections, ensuring that
    the pam_unix.so module is properly configured with the appropriate control flag.
    For auth and password sections, it uses "sufficient" control, while for other
    sections (account, session) it uses "required" control.

:param pam_files: List of PAM configuration file names (without /etc/pam.d/ prefix)
:type pam_files: list
:param pam_sections: List of PAM management groups to configure (auth, account, password, session)
:type pam_sections: list

#}}
{{%- macro bash_ensure_pam_module_line_unix_enable(pam_files, pam_sections) -%}}
{{% for pam_file in pam_files %}}
    {{% for pam_section in pam_sections %}}
        {{% if pam_section in ["auth", "password"] %}}
            {{{ bash_ensure_pam_module_line("/etc/pam.d/" + pam_file, pam_section, "sufficient", "pam_unix.so") }}}
        {{% else %}}
            {{{ bash_ensure_pam_module_line("/etc/pam.d/" + pam_file, pam_section, "required", "pam_unix.so") }}}
        {{% endif %}}
    {{% endfor %}}
{{% endfor %}}
{{%- endmacro -%}}

{{#
    Make sure that a line with a specific PAM module is present with the correct control.
    If the line is not present, it will be included after the regex informed in the "after_match"
    parameter. If the "after_match" parameter is empty, the line will be included at the end of
    the file informed in the "pam_file" parameter.

    If the line was already present, but with a different control, the control will be updated.
    Note: If there are multiple lines matching the "group" + "module", no lines will be updated.
    Instead, a new line will be included after the regex informed in "after_match" or at the
    end of file if "after_match" parameter is empty or there is no match.

    This is a conservative safeguard for improper use of this macro in rare cases of modules
    configured by multiple lines, like pam_sss.so, pam_faillock.so and pam_lastlog.so. In some
    situations, these special modules may have similar lines sharing the same "group" and "module".
    For these specific cases, this macro is not recommened without careful tests to make sure the
    PAM module is working as expected. Otherwise, a custom remediation should be considered.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param after_match:     Regex used as reference to append a line, if necessary. Optional parameter.
                        Note: For this macro, there is a special value used to include a line at the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_line(pam_file, group, control, module, after_match='') -%}}
{{% set control_regex = control | escape_regex %}}
if ! grep -qP "^\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s*.*" "{{{ pam_file }}}"; then
    # Line matching group + control + module was not found. Check group + module.
    if [ "$(grep -cP '^\s*{{{ group }}}\s+.*\s+{{{ module }}}\s*' "{{{ pam_file }}}")" -eq 1 ]; then
        # The control is updated only if one single line matches.
        sed -i -E --follow-symlinks "s/^(\s*{{{ group }}}\s+).*(\b{{{ module }}}.*)/\1{{{ control }}} \2/" "{{{ pam_file }}}"
    else
        {{%- if after_match == '' %}}
        echo "{{{ group }}}    {{{ control }}}    {{{ module }}}" >> "{{{ pam_file }}}"
        {{%- elif after_match == 'BOF'  %}}
        sed -i --follow-symlinks "1i {{{ group }}}     {{{ control }}}    {{{ module }}}" "{{{ pam_file }}}"
        {{%- else %}}
        LAST_MATCH_LINE=$(grep -nP "{{{ after_match }}}" "{{{ pam_file }}}" | tail -n 1 | cut -d: -f 1)
        if [ ! -z $LAST_MATCH_LINE ]; then
            sed -i --follow-symlinks $LAST_MATCH_LINE" a {{{ group }}}     {{{ control }}}    {{{ module }}}" "{{{ pam_file }}}"
        else
            echo "{{{ group }}}    {{{ control }}}    {{{ module }}}" >> "{{{ pam_file }}}"
        fi
        {{%- endif %}}
    fi
fi
{{%- endmacro -%}}


{{#
    Make sure that an existing PAM module line is properly configured with an option.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str
:param value:           PAM module option argument, if is case. Optional parameter.
:type value: str
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_option(pam_file, group, control, module, option, value='', after_match='') -%}}
{{% set control_regex = control | escape_regex %}}
{{{ bash_ensure_pam_module_line(pam_file, group, control, module, after_match) }}}
# Check the option
if ! grep -qP "^\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s*.*\s{{{ option }}}\b" "{{{ pam_file }}}"; then
    {{%- if value == '' %}}
    sed -i -E --follow-symlinks "/\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}.*/ s/$/ {{{ option }}}/" "{{{ pam_file }}}"
    {{%- else %}}
    sed -i -E --follow-symlinks "/\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}.*/ s/$/ {{{ option }}}={{{ value }}}/" "{{{ pam_file }}}"
    {{%- endif %}}
{{%- if value == '' %}}
fi
{{%- else %}}
else
    sed -i -E --follow-symlinks "s/(\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s+.*)({{{ option }}}=)[[:alnum:]]*\s*(.*)/\1\2{{{ value }}} \3/" "{{{ pam_file }}}"
fi
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Remove a PAM module option if present in a PAM module line.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str

#}}
{{%- macro bash_remove_pam_module_option(pam_file, group, control, module, option) -%}}
{{%- if control == '' %}}
if grep -qP "^\s*{{{ group }}}\s.*\b{{{ module }}}\s.*\b{{{ option }}}\b" "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks "s/(.*{{{ group }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[[:alnum:]]*(.*)/\1\2/g" "{{{ pam_file }}}"
{{%- else %}}
if grep -qP "^\s*{{{ group }}}\s+{{{ control }}}\s+{{{ module }}}\s.*\b{{{ option }}}\b" "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks "s/(.*{{{ group }}}.*{{{ control }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[[:alnum:]]*(.*)/\1\2/g" "{{{ pam_file }}}"
{{%- endif %}}
fi
{{%- endmacro -%}}


{{#
    Macro used to check if authselect files are intact. When used, it will exit the respective
    script if any authselect file was modified without proper use of authselect tool and
    respective profiles.

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


{{#
    Macro used to force re-select the current authselect profile, overwriting any manual modifications.
    This can fix integrity check failures caused by manual PAM file edits.
    The --force flag will overwrite modified files without prompting.

#}}
{{% macro bash_authselect_force_reselect() -%}}
authselect select "$(authselect current --raw)" --force
{{%- endmacro %}}


{{#
    Macro used to ensure a custom authselect profile is in use before changing any PAM file.
    This macro is useful in cases where an authselect profile doesn't provide a feature to enable
    the desired PAM module or option. In these cases, a custom authselect profile is necessary.
    If the system already uses a custom authselect profile, no action is necessary. Otherwise, a
    new custom profile will be created based on the current profile and preserving the already
    enabled features. Custom profiles are only recommeded if an authselect feature for the same
    purpose is not available. In any case, this macro will also set the "CURRENT_PROFILE" variable
    which is also used in the "bash_ensure_pam_variables_and_authselect_profile" macro.

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


{{#
    Make sure that an existing PAM module line is properly configured, in aligment to the current
    system configuration. This macro is compatible with custom authselect profiles if the system
    relies on authselect. Otherwise, the PAM files will be directly edited.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option. Optional parameter.
:type option: str
:param value:           PAM module option argument, if is case. Optional parameter.
:type value: str
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_configuration(pam_file, group, control, module, option='', value='', after_match='') -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{%- if option == '' %}}
    {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", group, control, module, after_match) }}}
    {{%- else %}}
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", group, control, module, option, value, after_match) | indent(8) }}}
    {{%- endif %}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}


{{#
    Remove a PAM module option from an existing PAM module line. This macro is compatible with
    custom authselect profiles if the system relies on authselect. Otherwise, the PAM files will
    be directly edited.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str

#}}
{{%- macro bash_remove_pam_module_option_configuration(pam_file, group, control, module, option) -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_remove_pam_module_option("$PAM_FILE_PATH", group, control, module, option) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}


{{%- macro bash_mount_conditional(path) -%}}
'findmnt --kernel "{{{ path }}}" > /dev/null || findmnt --fstab "{{{ path }}}" > /dev/null'
{{%- endmacro -%}}


{{#
    Macro to insert script to find a Python interpreter on the target system.

#}}
{{% macro find_python() -%}}

declare __REMEDIATE_PYTHON
if [ -x /usr/bin/python ]; then
    __REMEDIATE_PYTHON=/usr/bin/python
elif [ -x /usr/bin/python3 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python3
elif [ -x /usr/bin/python2 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python2
else
    echo "Python required and no python interpreter found."
    exit 1
fi
{{%- endmacro %}}


{{#
    Macro to insert script to find Mozilla Firefox location on the target system.

#}}
{{% macro find_firefox() -%}}

declare __FIREFOX_DISTRIBUTION
if find /usr -iname firefox\* -type f -print | grep -qe "firefox.sh$\|firefox-bin$"; then
   __FIREFOX_DISTRIBUTION=$(dirname "$(find /usr -iname firefox\* -type f -print | grep -e "firefox.sh$\|firefox-bin$" | head -n1)")/distribution
fi
{{%- endmacro %}}


{{#
This macro creates a Bash conditional which is used to determine if a
remediation is applicable. The condition compares the actual version of the
operating system with the expected version using the given operator. The macro
takes the operating system name ID as an argument. If the operating system
conforms and satisfies the optional version restricion, the Bash remediation
will be applied.

:param os_id: OS name, value of the ID variable in /etc/os-release
:type os_id: str
:param expected_ver: expected OS version, value of the VERSION_ID variable in /etc/os-release
            (optional argument, use together with "op")
:type expected_ver: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_os_linux_conditional(os_id, expected_ver=None, op=None, os_release_path="/etc/os-release") -%}}
{{%- if expected_ver -%}}
grep -qP "^ID=[\"']?{{{ os_id }}}[\"']?$" "{{{ os_release_path }}}" && {{{ bash_compare_version_os_linux(expected_ver, op, os_release_path) }}}
{{%- else -%}}
grep -qP "^ID=[\"']?{{{ os_id }}}[\"']?$" "{{{ os_release_path }}}"
{{%- endif -%}}
{{%- endmacro %}}


{{#
This macro generates bash condition that compares the actual version of the
operating system with the expected version using the given operator.

:param expected: expected OS version, value of the VERSION_ID variable in /etc/os-release
:type expected: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_compare_version_os_linux(expected, op, os_release_path="/etc/os-release") -%}}
{ real="$({{{ bash_get_version_os_linux(os_release_path) }}})"; expected="{{{ expected }}}"; {{{ bash_compare_version("$real", op, "$expected") }}}; }
{{%- endmacro -%}}


{{#
This macro generates code that retrieves the operating system version
from /etc/os-release from VERSION_ID variable.

:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_get_version_os_linux(os_release_path="/etc/os-release") -%}}
grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" {{{ os_release_path }}} | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/"
{{%- endmacro -%}}


{{#
Remove all interactive users (UID >= uid_min) from /etc/passwd
#}}
{{%- macro bash_remove_interactive_users_from_passwd_by_uid() -%}}
# remove all interactive users (UID >= {{{ uid_min }}}) from /etc/passwd
del=""
while read -r user; do
    del+="/^${user}:/d;"
done < <(awk -F: '($3 >= {{{ uid_min }}}) { print $1 }' /etc/passwd)
sed -i "${del}" /etc/passwd
{{%- endmacro -%}}

{{#
Macro for enabling dconf user profile in /etc/dconf/profile/<PROFILE>

The macro adds the following lines to the profile:
---
user-db:user
system-db:<DATABASE>
---
If the profile exists but does not contain the above lines, the
lines will be inserted at the beginning of the profile.

:param profile: name of dconf profile (e.g. user, gdm)
:type profile: str
:param database: name of dconf database (e.g. local, gdm)
:type database: str
#}}
{{% macro bash_enable_dconf_user_profile(profile, database) -%}}

mkdir -p /etc/dconf/profile
dconf_profile_path=/etc/dconf/profile/{{{ profile }}}

[[ -s "${dconf_profile_path}" ]] || echo > "${dconf_profile_path}"

if ! grep -Pzq "(?s)^\s*user-db:user.*\n\s*system-db:{{{ database }}}" "${dconf_profile_path}"; then
    sed -i --follow-symlinks "1s/^/user-db:user\nsystem-db:{{{ database }}}\n/" "${dconf_profile_path}"
fi

# Make sure the corresponding directories exist
mkdir -p /etc/dconf/db/{{{ database }}}.d

# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/profile
(umask 0022 && dconf update)
{{%- endmacro -%}}

{{#
This macro defines a conditional expression that is evaluated as true
if the remediation is performed during a build of a bootable container image.
#}}
{{%- macro bash_bootc_build() -%}}
{{%- if pkg_system == "rpm" -%}}
{ rpm --quiet -q kernel rpm-ostree bootc && ! rpm --quiet -q openshift-kubelet && { [ -f "/run/.containerenv" ] || [ -f "/.containerenv" ]; }; }
{{%- else -%}}
/bin/false
{{%- endif -%}}
{{%- endmacro -%}}

{{#
This macro defines a conditional expression that is evaluated as true
if the remediation is not performed during a build of a bootable container image.
#}}
{{%- macro bash_not_bootc_build() -%}}
! {{{ bash_bootc_build() }}}
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which checks the system architecture in /proc/sys/kernel/{osrelease,arch}

  :param arch: system architecture (x86_64, aarch64, s90x, ppc64le, ...)
  :type arch: str
#}}
{{%- macro bash_arch_conditional(arch) -%}}
( grep -sqE "^.*\.{{{ arch }}}$" /proc/sys/kernel/osrelease || grep -sqE "^{{{ arch }}}$" /proc/sys/kernel/arch; )
{{%- endmacro -%}}
