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

    ansible_instantiate_variables("varname1", "varname2")

Then, assume that the task that follows can work with the variable by referencing it, e.g.
value: :code:`Setting={{ varname1 }}`

#}}
{{%- macro ansible_instantiate_variables() -%}}
{{%- for name in varargs -%}}
- (xccdf-var {{{ name }}})
{{% endfor -%}}
{{%- endmacro -%}}


{{#
  A wrapper over the Ansible lineinfile module. This handles the most common
  options for us. regex is optional and when blank, it won't be included in
  the Ansible script; this allows arbitrary additions to files. new_line will
  only be passed when state is present. with_items will be specified only if
  non-empty, allowing for iterating through a variable of content (with the
  appropriate macro-based path). register will be specified only if non-empty,
  allowing for saving the output of this lineinfile module. check_mode allows
  an idempotent way to gather output, or run a task without changes. Useful when
  calling the ansible_only_lineinfile macro to handle deduplication of values.

  Note that all string-like parameters are single quoted in the YAML.

#}}
{{%- macro ansible_lineinfile(msg='', path='', mode='', regex='', insensitive='false', new_line='', create='no', state='present', with_items='', register='', when='', validate='', insert_after='', insert_before='', check_mode=False) -%}}
- name: "{{{ msg or rule_title }}}"
  lineinfile:
    path: '{{{ path }}}'
    create: {{{ create }}}
    {{%- if regex and insensitive %}}
    regexp: '(?i){{{ regex }}}'
    {{%- else %}}
    regexp: '{{{ regex }}}'
    {{%- endif %}}
    {{%- if mode %}}
    mode: '{{{ mode }}}'
    {{%- endif %}}
    {{%- if state == 'present' %}}
    line: '{{{ new_line }}}'
    state: present
    {{%- if insert_after %}}
    insertafter: '{{{ insert_after }}}'
    {{%- elif insert_before %}}
    insertbefore: '{{{ insert_before }}}'
    {{%- endif %}}
    {{%- else %}}
    state: '{{{ state }}}'
    {{%- endif %}}
    {{%- if validate %}}
    validate: '{{{ validate }}}'
    {{%- endif %}}
  {{%- if with_items %}}
  with_items: '{{{ with_items }}}'
  {{%- endif %}}
  {{%- if check_mode %}}
  check_mode: yes
  changed_when: no
  {{%- endif %}}
  {{%- if register %}}
  register: '{{{ register }}}'
  {{%- endif %}}
  {{%- if when %}}
  when: '{{{ when }}}'
  {{%- endif %}}
{{%- endmacro %}}


{{#
  Check the file system status of an object. Not a full implementation.

:parameter msg: Optional task title
:type msg: str
:parameter path: Path to file
:type path: str
:parameter register: variable to register
:type register: str

#}}
{{%- macro ansible_stat(msg='', path='', register='') %}}
- name: '{{{ msg or rule_title }}}'
  stat:
    path: '{{{ path }}}'
  {{%- if register %}}
  register: '{{{ register }}}'
  {{%- endif %}}
{{%- endmacro %}}


{{#
  Find files matching a particular value. Not a full implementation.

#}}
{{%- macro ansible_find(msg='', paths='', recurse='yes', follow='no', contains='', register='', when='') %}}
- name: '{{{ msg or rule_title }}}'
  find:
    paths: '{{{ paths }}}'
    recurse: '{{{ recurse }}}'
    follow: '{{{ follow }}}'
    {{%- if contains %}}
    contains: '{{{ contains }}}'
    {{%- endif %}}
  {{%- if register %}}
  register: '{{{ register }}}'
  {{%- endif %}}
  {{%- if when %}}
  when: '{{{ when }}}'
  {{%- endif %}}
{{%- endmacro %}}


{{#
  A wrapper for adding one, unique line to a file. A regex must be specified
  to tell if the line is unique. This is helpful in configuration files where
  a single configuration parameter might have multiple values, but only one
  value is approved. All lines matching the regex are first removed and then
  the new line is appended to the file.

#}}
{{%- macro ansible_only_lineinfile(msg, path, line_regex, new_line, insensitive='false', create='no', block=False, validate='', insert_after='', insert_before='', mode='') -%}}
{{%- if block %}}
- name: "{{{ msg or rule_title }}}"
  block:
    {{{ ansible_lineinfile("Check for duplicate values", path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', register='dupes', check_mode=True)|indent }}}
    {{{ ansible_lineinfile("Deduplicate values from " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', when='dupes.found is defined and dupes.found > 1')|indent }}}
    {{{ ansible_lineinfile("Insert correct line to " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before)|indent }}}
{{%- else %}}
{{{ ansible_lineinfile("Check for duplicate values", path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', register='dupes', check_mode=True) }}}
{{{ ansible_lineinfile("Deduplicate values from " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', when='dupes.found is defined and dupes.found > 1') }}}
{{{ ansible_lineinfile("Insert correct line into " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before) }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
  Ensure the configuration is set in a file. Note this handles generic
  key-seperator-value files with no sense of structure. In particular,
  ini configuration files are best served with the ini Ansible module
  instead of lineinfile-based solutions.

#}}
{{%- macro ansible_set_config_file(msg, file, parameter, separator=' ', separator_regex='\s+', value='', prefix_regex='^\s*', insensitive='false', create='no', validate='', insert_after='', insert_before='', mode='') %}}
{{{ ansible_only_lineinfile(msg, file, prefix_regex + parameter + separator_regex, parameter + separator + value, insensitive=insensitive, create=create, block=True, validate=validate, insert_after=insert_after, insert_before=insert_before, mode=mode) }}}
{{%- endmacro %}}


{{#
  Ensure the configuration is set in a file and not conflicted by a
  configuration in a directory. Note this handles generic key-separator-value
  files with no sense of structure. In particular, ini configuration files are
  best served with the ini Ansible module instead of lineinfile-based
  solutions.

#}}
{{%- macro ansible_set_config_file_dir(msg, config_file, config_dir, set_file, parameter, separator=' ', separator_regex='\s+', value='', prefix_regex='^\s*', insensitive='false', create='no', validate='', insert_after='', insert_before='') %}}
{{%- set var_dir = config_dir | replace("/", "_") | replace("-", "_") | replace(".", "_") -%}}
{{%- set dir_exists = var_dir + "_exists" -%}}
{{%- set dir_parameter = var_dir + "_has_parameter" -%}}
{{%- set line_regex = prefix_regex + "{{ \"" + parameter + "\"| regex_escape }}" + separator_regex -%}}
{{%- set find_when = dir_exists + ".stat.isdir is defined and " + dir_exists + ".stat.isdir" -%}}
{{%- set lineinfile_items = "{{ " + dir_parameter + ".files }}" -%}}
{{%- set lineinfile_when = dir_parameter + ".matched" -%}}
{{%- set new_line = parameter + separator + value -%}}
- name: '{{{ msg or rule_title }}}'
  block:
    {{{ ansible_lineinfile("Deduplicate values from " + config_file, config_file, regex=line_regex, insensitive=insensitive, create='no', state='absent')|indent }}}
    {{{ ansible_stat("Check if " + config_dir + " exists", path=config_dir, register=dir_exists)|indent }}}
    {{{ ansible_find("Check if the parameter " + parameter + " is present in " + config_dir, paths=config_dir, contains=line_regex, register=dir_parameter, when=find_when)|indent }}}
    {{{ ansible_lineinfile("Remove parameter from files in " + config_dir, path="{{ item.path }}", regex=line_regex, insensitive=insensitive, state="absent", with_items=lineinfile_items, when=lineinfile_when)|indent }}}
    {{{ ansible_lineinfile("Insert correct line to " + set_file, set_file, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before)|indent }}}
{{%- endmacro %}}


{{#
  High level macro to set a value in the ssh daemon configuration file.
  We specify a case insensitive comparison in the prefix since this is
  used to deduplicate since sshd_config has case-insensitive parameters
  (but case-sensitive values). We also specify the validation program here;
  -t specifies test and -f allows Ansible to pass a file at a different path.

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

:parameter msg: Message to be set as Task Title, if not set the rule's title will be used instead
:type msg: str
: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 ansible_sshd_set(msg='', parameter='', value='', config_is_distributed="false", config_basename="00-complianceascode-hardening.conf") %}}
{{%- if config_is_distributed == "true" %}}
{{% set config_dir = "/etc/ssh/sshd_config.d" %}}
{{% set config_file = "/etc/ssh/sshd_config.d" ~ "/" ~ config_basename %}}
{{{ ansible_set_config_file_dir(msg, config_file="/etc/ssh/sshd_config", config_dir=config_dir, set_file=config_file, parameter=parameter, separator_regex="\s+", value=value, prefix_regex="(?i)^\s*", create='yes', validate='/usr/sbin/sshd -t -f %s', insert_after='', insert_before="BOF") }}}
- name: {{{ rule_title }}} - set file mode for {{{ config_file }}}
  ansible.builtin.file:
    path: {{{ config_file }}}
    mode: '0600'
{{%- else %}}
{{% if product in ["ol8", "ol9"] %}}
- name: "Find sshd_config included files"
  shell: |-
    included_files=$(grep -oP "^\s*(?i)include.*" /etc/ssh/sshd_config | sed -e 's/\s*Include\s*//i' | sed -e 's|^[^/]|/etc/ssh/&|')
    [[ -n $included_files ]] && ls $included_files || true
  register: sshd_config_included_files

- name: "Comment conf from included files"
  replace:
    path: '{{ item }}'
    regexp: '^(\s*{{{ parameter }}}.*)$'
    replace: '# \1'
  loop: "{{ sshd_config_included_files.stdout_lines }}"

{{% endif %}}
{{{ ansible_set_config_file(msg, "/etc/ssh/sshd_config", parameter, value=value, create="yes", prefix_regex='(?i)^\s*', validate="/usr/sbin/sshd -t -f %s", insert_before="BOF") }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
  High level macro to set a value in a shell-related file that contains var assignments.

  We also specify the validation program here; see

    bash -c "help set" | grep -e -n

:param msg: The name for the Ansible task
:type msg: str
:param path: to the file
:type path: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: value of the parameter
:type value: str

#}}
{{%- macro ansible_shell_set(msg, path, parameter, value='', no_quotes=false) %}}
{{% if no_quotes -%}}
{{%- else -%}}
{{# Use the double quotes in all cases, as the underlying macro single-quotes the assignment line. #}}
{{% set value = '"%s"' % value %}}
{{%- endif -%}}
{{{ ansible_set_config_file(msg, path, parameter, separator="=", separator_regex="=", value=value, create="yes", prefix_regex='^\s*', validate="/usr/bin/bash -n %s", insert_before="^# " ~ parameter) }}}
{{%- endmacro %}}


{{#
  High level macro to set a command in tmux configuration file /etc/tmux.conf.
  Automatically adds "set -g " before the parameter.
:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str

#}}
{{%- macro ansible_tmux_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/tmux.conf", "set -g " + parameter, value=value, create="yes", mode="0644") }}}
{{%- endmacro %}}


{{#
  High level macro to set a command in auditd configuration file /etc/audit/auditd.conf.

:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str

#}}
{{%- macro ansible_auditd_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/audit/auditd.conf", parameter=parameter, value=value, create="yes", prefix_regex='(?i)^\s*', separator=" = ", separator_regex="\s*=\s*") }}}
{{%- endmacro %}}


{{#
  High level macro to set a parameter in /etc/systemd/coredump.conf.
  For SLE platforms put remediation in drop-in configuration file /etc/systemd/coredump.conf.d/oscap-autoremedy.conf.

:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str

#}}
{{%- macro ansible_coredump_config_set(msg='', parameter='', value='') %}}
{{% if 'sle' in product %}}
{{% set file = '/etc/systemd/coredump.conf.d/oscap-autoremedy.conf' %}}
{{% else %}}
{{% set file = '/etc/systemd/coredump.conf' %}}
{{% endif %}}
{{{ ansible_ini_file_set(file, "Coredump", parameter, value) }}}
{{%- endmacro %}}


{{#
  High level macro to set a parameter in /etc/selinux/config.

:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str

#}}
{{%- macro ansible_selinux_config_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/selinux/config", parameter=parameter, value=value, create="yes", separator="=", separator_regex="=", prefix_regex='^') }}}
{{%- endmacro %}}


{{#
  Generates an Ansible task 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 ansible_file_contents(filepath='', contents='') %}}
- name: "Put contents into {{{ filepath }}} according to policy"
  copy:
    dest: "{{{ filepath }}}"
    content: |+
        {{{ contents|indent(8) }}}
    force: yes
{{%- endmacro %}}


{{#
  Formats a banner regex for use in :code:`/etc/issue`, :code:`/etc/issue.net` or :code:`/etc/motd`

:param banner_var_name: name of ansible variable with the banner regex
:type banner_var_name: str

#}}
{{% macro ansible_deregexify_banner_etc_issue(banner_var_name) -%}}
{{ {{{ banner_var_name }}} |
{{{ ansible_deregexify_banner_anchors() }}} |
{{{ ansible_deregexify_multiple_banners() }}} |
{{{ ansible_deregexify_banner_space() }}} |
{{{ ansible_deregexify_banner_newline("\\n") }}} |
{{{ ansible_deregexify_banner_backslash() }}} |
wordwrap() }}
{{%- endmacro %}}


{{#
  Formats a banner regex for use in dconf

:param banner_var_name: name of ansible variable with the banner regex
:type banner_var_name: str

#}}
{{% macro ansible_deregexify_banner_dconf_gnome(banner_var_name) -%}}
''{{ {{{ banner_var_name }}} |
{{{ ansible_deregexify_banner_anchors() }}} |
{{{ ansible_deregexify_multiple_banners() }}} |
{{{ ansible_deregexify_banner_space() }}} |
{{{ ansible_deregexify_banner_newline("(n)*") }}} |
{{{ ansible_deregexify_banner_backslash() }}} |
{{{ ansible_deregexify_banner_newline_token()}}} }}''
{{%- endmacro %}}


{{# Strips anchors around the banner #}}
{{% macro ansible_deregexify_banner_anchors() -%}}
regex_replace("^\^(.*)\$$", "\1")
{{%- endmacro %}}


{{# Strips multibanner regex and keeps only the first banner #}}
{{% macro ansible_deregexify_multiple_banners() -%}}
regex_replace("^\((.*\.)\|.*\)$", "\1")
{{%- endmacro %}}


{{# Strips whitespace or newline regex #}}
{{% macro ansible_deregexify_banner_space() -%}}
regex_replace("\[\\s\\n\]\+"," ")
{{%- endmacro %}}


{{# Strips newline or newline escape sequence regex #}}
{{% macro ansible_deregexify_banner_newline(newline) -%}}
regex_replace("\(\?:\[\\n\]\+\|\(\?:\\\\n\)\+\)", "{{{ newline }}}")
{{%- endmacro %}}


{{# Strips newline token for a newline escape sequence regex #}}
{{% macro ansible_deregexify_banner_newline_token() -%}}
regex_replace("\(n\)\*", "\\n")
{{%- endmacro %}}


{{# Strips backslash regex #}}
{{% macro ansible_deregexify_banner_backslash() -%}}
regex_replace("\\", "")
{{%- endmacro %}}


{{#
The following macro remediates one audit watch rule in :code:`/etc/audit/rules.d` directory.

:param path: path to watch
:type path: str
:param permissions: permissions changes to watch for
:type permissions: str
:param key: key to use as identifier. Note that if there exists any other rule with the same find_mac_key in some file within :code:`/etc/audit/rules.d/`, the new rule will be appended to this file.
:type key: str

#}}
{{% macro ansible_audit_augenrules_add_watch_rule(path='', permissions='', key='') -%}}
- name: Check if watch rule for {{{ path }}} already exists in /etc/audit/rules.d/
  find:
    paths: "/etc/audit/rules.d"
    contains: '^\s*-w\s+{{{ path }}}\s+-p\s+{{{ permissions }}}(\s|$)+'
    patterns: "*.rules"
  register: find_existing_watch_rules_d

- name: Search /etc/audit/rules.d for other rules with specified key {{{ key }}}
  find:
    paths: "/etc/audit/rules.d"
    contains: '^.*(?:-F key=|-k\s+){{{ key }}}$'
    patterns: "*.rules"
  register: find_watch_key
  when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Use /etc/audit/rules.d/{{{ key }}}.rules as the recipient for the rule
  set_fact:
    all_files:
      - /etc/audit/rules.d/{{{ key }}}.rules
  when: find_watch_key.matched is defined and find_watch_key.matched == 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Use matched file as the recipient for the rule
  set_fact:
    all_files:
      - "{{ find_watch_key.files | map(attribute='path') | list | first }}"
  when: find_watch_key.matched is defined and find_watch_key.matched > 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0

- name: Add watch rule for {{{ path }}} in /etc/audit/rules.d/
  lineinfile:
    path: "{{ all_files[0] }}"
    line: "-w {{{ path }}} -p {{{ permissions }}} -k {{{ key }}}"
    create: yes
    mode: '0600'
  when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
{{%- endmacro %}}


{{#
The following macro remediates one audit watch rule in :code:`/etc/audit/audit.rules`.

:param path: Path to watch
:type path: str
:param permissions: Permissions changes to watch for
:type permissions: str
:param key: Key to use as identifier
:type key: str

#}}
{{% macro ansible_audit_auditctl_add_watch_rule(path='', permissions='', key='') -%}}
- name: Check if watch rule for {{{ path }}} already exists in /etc/audit/audit.rules
  find:
    paths: "/etc/audit/"
    contains: '^\s*-w\s+{{{ path }}}\s+-p\s+{{{ permissions }}}(\s|$)+'
    patterns: "audit.rules"
  register: find_existing_watch_audit_rules

- name: Add watch rule for {{{ path }}} in /etc/audit/audit.rules
  lineinfile:
    line: "-w {{{ path }}} -p {{{ permissions }}} -k {{{ key }}}"
    state: present
    dest: /etc/audit/audit.rules
    create: yes
    mode: '0600'
  when: find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched == 0
{{%- endmacro %}}


{{#
The following macro remediates Audit syscall rule in :code:`/etc/audit/rules.d` directory.
The macro requires following parameters:

: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 syscalls: List of syscalls to ensure presense among audit rules. For example, "['fchown', 'lchown', 'fchownat']"
:type syscalls: list[str]
:param syscall_grouping: List of other syscalls that can be grouped with 'syscalls'. For example, "['fchown', 'lchown', 'fchownat']"
:type syscall_grouping: list[str]
:param key: The key to use when appending a new rule
:type key: str

#}}
{{% macro ansible_audit_augenrules_add_syscall_rule(action_arch_filters="", other_filters="", auid_filters="", syscalls=[], key="", syscall_grouping=[]) -%}}
{{% if other_filters != "" %}}
    {{% set other_filters = " " ~ other_filters %}}
{{% endif %}}
{{% if auid_filters != "" %}}
    {{% set auid_filters = " " ~ auid_filters %}}
{{% endif %}}
{{% if syscalls == [] %}}
    {{% set syscall_flag = "" %}}
{{% else %}}
    {{% set syscall_flag = " -S " %}}
{{% endif %}}
- name: Declare list of syscalls
  set_fact:
    syscalls: {{{ syscalls }}}
    syscall_grouping: {{{ syscall_grouping }}}

- name: Check existence of {{{ syscalls | join(", ") }}} in /etc/audit/rules.d/
  find:
    paths: /etc/audit/rules.d
    contains: '{{{ action_arch_filters }}}(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)*{{{ other_filters }}}{{{ auid_filters }}} (-k\s+|-F\s+key=)\S+\s*$'
    patterns: '*.rules'
  register: find_command
  loop: '{{ (syscall_grouping + syscalls) | unique }}'

- name: Reset syscalls found per file
  set_fact:
    syscalls_per_file: {}
    found_paths_dict: {}

- name: Declare syscalls found per file
  set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
  loop: "{{ find_command.results | selectattr('matched') | list }}"

- name: Declare files where syscalls were found
  set_fact: found_paths="{{ find_command.results | map(attribute='files') | flatten | map(attribute='path') | list }}"

- name: Count occurrences of syscalls in paths
  set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item, 0) }) }}"
  loop: "{{ find_command.results | map(attribute='files') | flatten | map(attribute='path') | list }}"

- name: Get path with most syscalls
  set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value') | last).key }}"
  when: found_paths | length >= 1

- name: No file with syscall found, set path to /etc/audit/rules.d/{{{ key }}}.rules
  set_fact: audit_file="/etc/audit/rules.d/{{{ key }}}.rules"
  when: found_paths | length == 0

- name: Declare found syscalls
  set_fact: syscalls_found="{{ find_command.results | selectattr('matched') | map(attribute='item') | list }}"

- name: Declare missing syscalls
  set_fact:
    missing_syscalls="{{ syscalls | difference(syscalls_found) }}"

- name: Replace the audit rule in {{ audit_file }}
  lineinfile:
    path: '{{ audit_file }}'
    regexp: '({{{ action_arch_filters }}})(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file] | join("|") }}))\b)((?:( -S |,)\w+)+)({{{ other_filters }}}{{{ auid_filters }}} (?:-k |-F key=)\w+)'
    line: '\1\2\3{{ missing_syscalls | join("\3") }}\4'
    backrefs: yes
    state: present
    mode: g-rwx,o-rwx
  when: syscalls_found | length > 0 and missing_syscalls | length > 0

- name: Add the audit rule to {{ audit_file }}
  lineinfile:
    path: '{{ audit_file }}'
    line: "{{{ action_arch_filters }}}{{{ syscall_flag }}}{{ syscalls | join(',') }}{{{ other_filters }}}{{{ auid_filters}}} -F key={{{ key }}}"
    create: true
    mode: g-rwx,o-rwx
    state: present
  when: syscalls_found | length == 0
{{%- endmacro %}}


{{#
The following macro remediates Audit syscall rule in :code:`/etc/audit/audit.rules` file.

: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 syscalls: List of syscalls to ensure presense among audit rules.
    For example, "['fchown', 'lchown', 'fchownat']"
:type syscalls: list[str]
:param key: The key to use when appending a new rule
:type key: str
:param syscall_grouping: List of other syscalls that can be grouped with
    'syscalls'. For example, "['fchown', 'lchown', 'fchownat']"
:type syscall_grouping: list[str]

#}}
{{% macro ansible_audit_auditctl_add_syscall_rule(action_arch_filters="", other_filters="", auid_filters="", syscalls=[], key="", syscall_grouping=[]) -%}}
{{% if other_filters!= "" %}}
    {{% set other_filters = " " ~ other_filters %}}
{{% endif %}}
{{% if auid_filters!= "" %}}
    {{% set auid_filters = " " ~ auid_filters %}}
{{% endif %}}
{{% if syscalls == [] %}}
    {{% set syscall_flag = "" %}}
{{% else %}}
    {{% set syscall_flag = " -S " %}}
{{% endif %}}
- name: Declare list of syscalls
  set_fact:
    syscalls: {{{ syscalls }}}
    syscall_grouping: {{{ syscall_grouping }}}

- name: Check existence of {{{ syscalls | join(", ") }}} in /etc/audit/audit.rules
  find:
    paths: /etc/audit
    contains: '{{{ action_arch_filters }}}(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)*{{{ other_filters }}}{{{ auid_filters }}} (-k\s+|-F\s+key=)\S+\s*$'
    patterns: 'audit.rules'
  register: find_command
  loop: '{{ (syscall_grouping + syscalls) | unique }}'

- name: Set path to /etc/audit/audit.rules
  set_fact: audit_file="/etc/audit/audit.rules"

- name: Declare found syscalls
  set_fact: syscalls_found="{{ find_command.results | selectattr('matched') | map(attribute='item') | list }}"

- name: Declare missing syscalls
  set_fact:
    missing_syscalls="{{ syscalls | difference(syscalls_found) }}"

- name: Replace the audit rule in {{ audit_file }}
  lineinfile:
    path: '{{ audit_file }}'
    regexp: '({{{ action_arch_filters }}})(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:( -S |,)\w+)+)({{{ other_filters }}}{{{ auid_filters }}} (?:-k |-F key=)\w+)'
    line: '\1\2\3{{ missing_syscalls | join("\3") }}\4'
    backrefs: yes
    state: present
    mode: g-rwx,o-rwx
  when: syscalls_found | length > 0 and missing_syscalls | length > 0

- name: Add the audit rule to {{ audit_file }}
  lineinfile:
    path: '{{ audit_file }}'
    line: "{{{ action_arch_filters }}}{{{ syscall_flag }}}{{ syscalls | join(',') }}{{{ other_filters }}}{{{ auid_filters}}} -F key={{{ key }}}"
    create: true
    mode: g-rwx,o-rwx
    state: present
  when: syscalls_found | length == 0
{{%- endmacro %}}


{{% macro ansible_sssd_ldap_config(parameter, value) -%}}
- name: "Test for id_provider different than Active Directory (ad)"
  command: grep -qzosP '[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*id_provider[[:space:]]*=[[:space:]]*((?i)ad)[[:space:]]*$' /etc/sssd/sssd.conf
  register: test_id_provider
  failed_when: false
  changed_when: false
  check_mode: no

- name: "Test for domain group"
  command: grep '\s*\[domain\/[^]]*]' /etc/sssd/sssd.conf
  register: test_grep_domain
  failed_when: false
  changed_when: false
  check_mode: no

- name: "Add default domain group and set {{{ parameter }}} in sssd configuration (if no domain there)"
  ini_file:
    path: /etc/sssd/sssd.conf
    section: "{{ item.section }}"
    option: "{{ item.option }}"
    value: "{{ item.value }}"
    mode: 0600
  with_items:
    - { section: sssd, option: domains, value: default}
    - { section: domain/default, option: {{{ parameter }}}, value: "{{{ value }}}"}
  when:
    - test_grep_domain.stdout is defined
    - test_grep_domain.stdout | length < 1
    - test_id_provider.stdout is defined
    - test_id_provider.stdout | length < 1

- name: "Set {{{ parameter }}} in sssd configuration"
  ini_file:
    path: /etc/sssd/sssd.conf
    section: "{{ test_grep_domain.stdout | regex_replace('\\[(.*)\\]','\\1') }}"
    option: {{{ parameter }}}
    value: "{{{ value }}}"
    mode: 0600
  when:
    - test_grep_domain.stdout is defined
    - test_grep_domain.stdout | length > 0
    - test_id_provider.stdout is defined
    - test_id_provider.stdout | length < 1

- name: Find all the conf files inside /etc/sssd/conf.d/
  find:
    paths: "/etc/sssd/conf.d/"
    patterns: "*.conf"
  register: sssd_conf_d_files

- name: Set {{{ parameter }}} to {{{ value }}} in /etc/sssd/conf.d/ if exists
  ansible.builtin.replace:
    path: "{{ item.path }}"
    regexp: '[^#]*{{{ parameter }}}.*'
    replace: '{{{ parameter }}} = {{{ value }}}'
  with_items: "{{ sssd_conf_d_files.files }}"

{{%- endmacro %}}


{{% macro ansible_ini_file_set(filename, section, key, value, description="", no_extra_spaces=False) -%}}
- name: "{{{ description if description else ("Set '" + key + "' to '" + value + "' in the [" + section + "] section of '" + filename + "'") }}}"
  ini_file:
    path: "{{{ filename }}}"
    section: "{{{ section }}}"
    option: "{{{ key }}}"
    value: "{{{ value }}}"
    create: yes
    mode: 0644
    {{% if no_extra_spaces %}}
    no_extra_spaces: true
    {{% endif %}}

{{%- endmacro %}}

{{#
    This macro comments out a given line of the sudoers and then validates it before saving.

:param parameter: The parameter to remove
:type parameter: str
:param pattern: The pattern to remove
:type pattern: str

#}}
{{%- macro ansible_sudo_remove_config(parameter, pattern) -%}}

- name: Find /etc/sudoers.d/ files
  ansible.builtin.find:
    paths:
      - /etc/sudoers.d/
  register: sudoers

- name: "Remove lines containing {{{ parameter }}} from sudoers files"
  ansible.builtin.replace:
    regexp: '(^(?!#).*[\s]+{{{ pattern }}}.*$)'
    replace: '# \g<1>'
    path: "{{ item.path }}"
    validate: /usr/sbin/visudo -cf %s
  with_items:
    - { path: /etc/sudoers }
    - "{{ sudoers.files }}"
{{%- endmacro -%}}


{{#
  This macro creates an Ansible snipped which is used in `when` clause to
  determine applicability of a task. If the package passed as a parameter is
  installed, the task is applicable. The macro respects
  `platform_package_overrides` variable.

: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 ansible_pkg_conditional(package, op=None, ver=None) -%}}
{{%- if package in platform_package_overrides -%}}
  {{%- set package = platform_package_overrides[package] -%}}
{{%- endif -%}}
{{%- if ver -%}}
{{# For RPM packages, Ansible splits the package version into "epoch", "version" and "release" keys. For DEB packages, Ansible provides only "version" key. We don't take the "release" part into account. #}}
{{%- if pkg_system == "rpm" -%}}
"{{{ package }}}" in ansible_facts.packages and (((((ansible_facts.packages["{{{ package }}}"] | last)["epoch"]) != None) | ternary((ansible_facts.packages["{{{ package }}}"] | last)["epoch"] ~ ":", "0:")) + ((ansible_facts.packages["{{{ package }}}"] | last)["version"] | split("-") | first)) is version("{{{ ver }}}", "{{{ op }}}")
{{%- else -%}}
"{{{ package }}}" in ansible_facts.packages and ((ansible_facts.packages["{{{ package }}}"] | last)["version"] | split("-") | first) is version("{{{ ver }}}", "{{{ op }}}")
{{%- endif -%}}
{{%- else -%}}
"{{{ package }}}" in ansible_facts.packages
{{%- endif -%}}
{{%- 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 ansible_check_authselect_integrity() -%}}
- name: '{{{ rule_title }}} - Check integrity of authselect current profile'
  ansible.builtin.command:
    cmd: authselect check
  register: result_authselect_check_cmd
  changed_when: false
  failed_when: false

- name: '{{{ rule_title }}} - Informative message based on the authselect integrity check result'
  ansible.builtin.assert:
    that:
      - result_authselect_check_cmd.rc == 0
    fail_msg:
      - authselect integrity check failed. Remediation aborted!
      - This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
      - It is not recommended to manually edit the PAM files when authselect tool is available.
      - In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended.
    success_msg:
      - authselect integrity check passed
{{%- 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 ansible_apply_authselect_changes(backup_name='') -%}}
- name: '{{{ rule_title }}} - Ensure authselect changes are applied'
  ansible.builtin.command:
    {{%- if backup_name == '' %}}
    cmd: authselect apply-changes -b
    {{%- else %}}
    cmd: authselect apply-changes -b --backup={{{ backup_name }}}
    {{%- endif %}}
{{%- endmacro %}}

{{#
    Macro used to apply changes on pam-auth-update profiles. If the "profile_name" parameter is not defined, the
    pam-auth-update will apply all profile changes by default.

:param profile_name:        Changes the default profile used by pam-auth-update.
:type profile_name: str

#}}
{{% macro ansible_apply_pam_auth_update_changes(profile_name='') -%}}
- name: '{{{ rule_title }}} - Ensure pam-auth-update profile changes are applied'
  ansible.builtin.command:
    {{%- if profile_name == '' %}}
    cmd: pam-auth-update
    {{%- else %}}
    cmd: pam-auth-update --enable {{{ profile_name }}}
    {{%- endif %}}
{{%- endmacro %}}

{{#
    Disable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.

#}}
{{%- macro ansible_disable_authselect_feature(feature) -%}}
{{{ ansible_check_authselect_integrity() }}}

- name: '{{{ rule_title }}} - Get authselect Features Currently Enabled'
  ansible.builtin.shell:
    cmd: authselect current | tail -n+3 | awk '{ print $2 }'
  register: result_authselect_features
  changed_when: false
  when:
    - result_authselect_check_cmd is success

- name: '{{{ rule_title }}} - Ensure "{{{ feature }}}" Feature is Disabled Using authselect Tool'
  ansible.builtin.command:
    cmd: authselect disable-feature {{{ feature }}}
  register: result_authselect_disable_feature_cmd
  when:
    - result_authselect_check_cmd is success
    - result_authselect_features.stdout is search("{{{ feature }}}")

{{{ ansible_apply_authselect_changes() }}}
  when:
    - result_authselect_disable_feature_cmd is not skipped
    - result_authselect_disable_feature_cmd is success
{{%- endmacro -%}}


{{#
    Enable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.

#}}
{{%- macro ansible_enable_authselect_feature(feature) -%}}
{{{ ansible_check_authselect_integrity() }}}

- name: '{{{ rule_title }}} - Get authselect current features'
  ansible.builtin.shell:
    cmd: authselect current | tail -n+3 | awk '{ print $2 }'
  register: result_authselect_features
  changed_when: false
  when:
    - result_authselect_check_cmd is success

- name: '{{{ rule_title }}} - Ensure "{{{ feature }}}" feature is enabled using authselect tool'
  ansible.builtin.command:
    cmd: authselect enable-feature {{{ feature }}}
  register: result_authselect_enable_feature_cmd
  when:
    - result_authselect_check_cmd is success
    - result_authselect_features.stdout is not search("{{{ feature }}}")

{{{ ansible_apply_authselect_changes() }}}
  when:
    - result_authselect_enable_feature_cmd is not skipped
    - result_authselect_enable_feature_cmd is success
{{%- endmacro -%}}


{{#
    Used to identify if authselect is present or not in the system.
    Some macros can change the remediation behavior based on the presence of authselect.

#}}
{{%- macro ansible_check_authselect_presence() -%}}
- name: '{{{ rule_title }}} - Check if system relies on authselect tool'
  ansible.builtin.stat:
    path: /usr/bin/authselect
  register: result_authselect_present
{{%- endmacro -%}}

{{#
    Used to identify if pam-auth-update is present or not in the system.
    Some macros can change the remediation behavior based on the presence of authselect.

#}}
{{%- macro ansible_check_pam_auth_update_presence() -%}}
- name: '{{{ rule_title }}} - Check if system relies on pam-auth-update tool'
  ansible.builtin.stat:
    path: /usr/sbin/pam-auth-update
  register: result_pam_auth_update_present
{{%- 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 ansible_pam_lastlog_enable_showfailed(pam_file, control, after_match='') -%}}
{{{ ansible_check_authselect_presence() }}}

- name: '{{{ rule_title }}} - Collect the Available authselect Features'
  ansible.builtin.command:
    cmd: authselect list-features sssd
  register: result_authselect_available_features
  changed_when: false
  when:
    - result_authselect_present.stat.exists

- name: '{{{ rule_title }}} - Configure pam_lastlog.so Using authselect Feature'
  block:
    {{{ ansible_disable_authselect_feature('with-silent-lastlog') | indent(4) }}}
  when:
    - result_authselect_present.stat.exists
    - result_authselect_available_features.stdout is search("with-silent-lastlog")

- name: '{{{ rule_title }}} - Configure pam_lastlog.so in appropriate PAM files'
  block:
    {{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
    {{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(4) }}}
    {{{ ansible_remove_pam_module_option('{{ pam_file_path }}', 'session', control, 'pam_lastlog.so', 'silent') | indent(4) }}}
{{%- 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 ansible_pam_pwhistory_enable(pam_file, control, after_match='') -%}}
{{{ ansible_check_authselect_presence() }}}

- name: '{{{ rule_title }}} - Collect the available authselect features'
  ansible.builtin.command:
    cmd: authselect list-features sssd
  register: result_authselect_available_features
  changed_when: false
  when:
    - result_authselect_present.stat.exists

- name: '{{{ rule_title }}} - Enable pam_pwhistory.so using authselect feature'
  block:
    {{{ ansible_enable_authselect_feature('with-pwhistory') | indent(4) }}}
  when:
    - result_authselect_present.stat.exists
    - result_authselect_available_features.stdout is search("with-pwhistory")

- name: '{{{ rule_title }}} - Enable pam_pwhistory.so in appropriate PAM files'
  block:
    {{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
    {{{ ansible_ensure_pam_module_line('{{ pam_file_path }}', 'password', control, 'pam_pwhistory.so', after_match) | indent(4) }}}
  when: >
    (result_authselect_available_features.stdout is defined and result_authselect_available_features.stdout is not search("with-pwhistory"))
    or result_authselect_available_features is not defined
{{%- 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 parameter:           pwhistory parameter/option e.g.: remember, retry, debug
:type parameter: str
:param pwhistory_var_name:  Literal variable name.
:type pwhistory_var_name: str

#}}
{{%- macro ansible_pam_pwhistory_parameter_value(pam_file, parameter, pwhistory_var_name='') -%}}
- name: '{{{ rule_title }}} - Check the presence of /etc/security/pwhistory.conf file'
  ansible.builtin.stat:
    path: /etc/security/pwhistory.conf
  register: result_pwhistory_conf_check

- name: '{{{ rule_title }}} - pam_pwhistory.so parameters are configured in /etc/security/pwhistory.conf file'
  block:
    - name: '{{{ rule_title }}} - Ensure the pam_pwhistory.so {{{ parameter }}} parameter in /etc/security/pwhistory.conf'
      ansible.builtin.lineinfile:
        path: /etc/security/pwhistory.conf
        {{%- if pwhistory_var_name == '' %}}
        regexp: ^\s*{{{ parameter }}}
        line: {{{ parameter }}}
        {{%- else %}}
        regexp: ^\s*{{{ parameter }}}\s*=
        line: {{{ parameter }}} = {{{ pwhistory_var_name }}}
        {{%- endif %}}
        state: present

    - name: '{{{ rule_title }}} - Ensure the pam_pwhistory.so {{{ parameter }}} parameter is removed from PAM files'
      block:
        {{{ ansible_remove_pam_module_option_configuration(pam_file, 'password', '', 'pam_pwhistory.so', parameter) | indent(8) }}}
  when:
    - result_pwhistory_conf_check.stat.exists

- name: '{{{ rule_title }}} - pam_pwhistory.so parameters are configured in PAM files'
  block:
    {{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
    {{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', 'password', 'requisite', 'pam_pwhistory.so', parameter, pwhistory_var_name, '') | indent(4) }}}
    {{{ ansible_apply_authselect_changes() | indent(4) }}}
      when:
        - result_authselect_present.stat.exists
        - (result_pam_{{{ parameter }}}_add is defined and result_pam_{{{ parameter }}}_add.changed) or (result_pam_{{{ parameter }}}_edit is defined and result_pam_{{{ parameter }}}_edit.changed)
  when:
    - not result_pwhistory_conf_check.stat.exists
{{%- endmacro -%}}


{{#
  This macro ensures the pam_faillock.so PAM module is enabled.
  It is enabled using the authselect tool or editing the PAM files, only if authselect tool is not available.

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

{{{ ansible_check_authselect_presence() }}}

- name: {{{ rule_title }}} - Remediation where authselect tool is present
  block:
    {{{ ansible_enable_authselect_feature('with-faillock') | indent(4) }}}
  when:
    - result_authselect_present.stat.exists

- name: {{{ rule_title }}} - Remediation where authselect tool is not present
  block:
    - name: {{{ rule_title }}} - Check if pam_faillock.so is already enabled
      ansible.builtin.lineinfile:
        path: /etc/pam.d/system-auth
        regexp: .*auth.*pam_faillock\.so (preauth|authfail)
        state: absent
      check_mode: yes
      changed_when: false
      register: result_pam_faillock_is_enabled

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

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

    - name: {{{ rule_title }}} - Enable pam_faillock.so account section editing PAM files
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        line: account     required      pam_faillock.so
        insertbefore: ^account.*required.*pam_unix\.so.*
        state: present
      loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
      when:
        - result_pam_faillock_is_enabled.found == 0
  when:
    - not result_authselect_present.stat.exists
{{%- endmacro -%}}


{{#
  This macro make sure the informed parameter from pam_faillock.so PAM module is properly set. In
  case the file /etc/security/faillock.conf is present in the system, the option is removed from
  PAM files since it is not needed there in that case.

:param parameter: The pam_faillock.so parameter name.
:type parameter: str
:param faillock_var_name: If the parameter expects a value from a variable, the variable name is informed here.
:type faillock_var_name: str
:param authfail: check the pam_faillock.so conf line with authfail
:type authfail: bool

#}}
{{%- macro ansible_pam_faillock_parameter_value(parameter, faillock_var_name='', authfail=True) -%}}

{{%- if faillock_var_name != '' %}}
{{{ ansible_instantiate_variables( faillock_var_name ) }}}
{{%- endif %}}

- name: {{{ rule_title }}} - Check the presence of /etc/security/faillock.conf file
  ansible.builtin.stat:
    path: /etc/security/faillock.conf
  register: result_faillock_conf_check

- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter in /etc/security/faillock.conf
  ansible.builtin.lineinfile:
    path: /etc/security/faillock.conf
    {{%- if faillock_var_name == '' %}}
    regexp: ^\s*{{{ parameter }}}
    line: {{{ parameter }}}
    {{%- else %}}
    regexp: ^\s*{{{ parameter }}}\s*=
    line: {{{ parameter }}} = {{ {{{ faillock_var_name }}} }}
    {{%- endif %}}
    state: present
  when:
    - result_faillock_conf_check.stat.exists

- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter not in PAM files
  block:
    {{{ ansible_remove_pam_module_option_configuration('/etc/pam.d/system-auth','auth','','pam_faillock.so',parameter) | indent(4) }}}
    {{{ ansible_remove_pam_module_option_configuration('/etc/pam.d/password-auth','auth','','pam_faillock.so',parameter) | indent(4) }}}
  when:
    - result_faillock_conf_check.stat.exists

- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter in PAM files
  block:
    - name: {{{ rule_title }}} - Check if pam_faillock.so {{{ parameter }}} parameter is already enabled in pam files
      ansible.builtin.lineinfile:
        path: /etc/pam.d/system-auth
        regexp: .*auth.*pam_faillock\.so (preauth|authfail).*{{{ parameter }}}
        state: absent
      check_mode: yes
      changed_when: false
      register: result_pam_faillock_{{{ parameter }}}_parameter_is_present

    - name: {{{ rule_title }}} - Ensure the inclusion of pam_faillock.so preauth {{{ parameter }}} parameter in auth section
      ansible.builtin.lineinfile:
        path: "{{ item }}"
        backrefs: true
        regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
        {{%- if faillock_var_name == '' %}}
        line: \1required\3 {{{ parameter }}}
        {{%- else %}}
        line: \1required\3 {{{ parameter }}}={{ {{{ faillock_var_name }}} }}
        {{%- endif %}}
        state: present
      loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
      when:
        - result_pam_faillock_{{{ parameter }}}_parameter_is_present.found == 0

    {{%- if authfail %}}
    - name: {{{ rule_title }}} - Ensure the inclusion of pam_faillock.so authfail {{{ parameter }}} parameter in auth section
      ansible.builtin.lineinfile:
        path: "{{ item }}"
        backrefs: true
        regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
        {{%- if faillock_var_name == '' %}}
        line: \1required\3 {{{ parameter }}}
        {{%- else %}}
        line: \1required\3 {{{ parameter }}}={{ {{{ faillock_var_name }}} }}
        {{%- endif %}}
        state: present
      loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
      when:
        - result_pam_faillock_{{{ parameter }}}_parameter_is_present.found == 0
    {{%- endif %}}

    {{%- if faillock_var_name != '' %}}
    - name: {{{ rule_title }}} - Ensure the desired value for pam_faillock.so preauth {{{ parameter }}} parameter in auth section
      ansible.builtin.lineinfile:
        path: "{{ item }}"
        backrefs: true
        regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)({{{ parameter }}})=[0-9]+(.*)
        line: \1required\3\4={{ {{{ faillock_var_name }}} }}\5
        state: present
      loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
      when:
        - result_pam_faillock_{{{ parameter }}}_parameter_is_present.found > 0

    {{%- if authfail %}}
    - name: {{{ rule_title }}} - Ensure the desired value for pam_faillock.so authfail {{{ parameter }}} parameter in auth section
      ansible.builtin.lineinfile:
        path: "{{ item }}"
        backrefs: true
        regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)({{{ parameter }}})=[0-9]+(.*)
        line: \1required\3\4={{ {{{ faillock_var_name }}} }}\5
        state: present
      loop:
        - /etc/pam.d/system-auth
        - /etc/pam.d/password-auth
      when:
        - result_pam_faillock_{{{ parameter }}}_parameter_is_present.found > 0
    {{%- endif %}}
    {{%- endif %}}
  when:
    - not result_faillock_conf_check.stat.exists
{{%- endmacro -%}}

{{#
  This macro ensures the pam_pwquality.so PAM module is enabled.
  It is enabled using the pam-auth-update tool.

:param path: The path of pam-auth-update configuration for pam_pwquality.so.
:type parameter: str

#}}
{{%- macro ansible_pam_pwquality_enable(path) -%}}

{{{ ansible_check_pam_auth_update_presence() }}}

- name: {{{ rule_title }}} - Remediation where pam-auth-update tool is present
  block:
    - name: Check if {{{ path }}} exists
      stat:
        path: {{{ path }}}
      register: pwquality_file_stat

    - name: Put the content into {{{ path }}} if it does not exist
      copy:
        dest: {{{ path }}}
        content: |+
          Name: Pwquality password strength checking
          Default: yes
          Priority: 1024
          Conflicts: cracklib
          Password-Type: Primary
          Password:
            requisite           pam_pwquality.so retry=3
        force: yes
      when: not pwquality_file_stat.stat.exists

    {{{ ansible_apply_pam_auth_update_changes('cac_pwquality') | indent(4) }}}

  when:
    - result_pam_auth_update_present.stat.exists

{{%- endmacro -%}}


{{#
Macro for Ansible 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 ansible_grub2_bootloader_argument(arg_name, arg_name_value) -%}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15', 'slmicro5'] %}}
- name: Check {{{ arg_name }}} argument exists
  command: grep '^\s*GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=' /etc/default/grub
  failed_when: False
  register: argcheck

- name: Check {{{ arg_name }}} argument exists
  command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
  failed_when: False
  register: linecheck

- name: Add {{{ arg_name }}} argument
  ansible.builtin.lineinfile:
    line: 'GRUB_CMDLINE_LINUX="{{{ arg_name_value }}} "'
    state: present
    dest: /etc/default/grub
    create: yes
    mode: '0644'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc != 0

- name: Replace existing {{{ arg_name }}} argument
  replace:
      path: /etc/default/grub
      regexp: '{{{ arg_name }}}=[a-zA-Z0-9,]+'
      replace: '{{{ arg_name_value }}}'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and linecheck.rc == 0

- name: Add {{{ arg_name }}} argument
  replace:
      path: /etc/default/grub
      regexp: '(^\s*GRUB_CMDLINE_LINUX=.*)"'
      replace: '\1 {{{ arg_name_value }}}"'
  when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc == 0

{{% endif -%}}

{{% if product in ['sle12', 'sle15'] %}}
- name: Update grub defaults and the bootloader menu
  command: /usr/sbin/grub2-mkconfig -o {{{ grub2_boot_path }}}/grub.cfg
{{% elif 'debian' in product %}}
- name: Update grub defaults and the bootloader menu
  command: /usr/sbin/update-grub
{{% else %}}
- name: Update grub defaults and the bootloader menu
  command: /sbin/grubby --update-kernel=ALL --args="{{{ arg_name_value }}}"
{{% endif -%}}
{{%- endmacro -%}}


{{#
Macro for Ansible 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 ansible_grub2_bootloader_argument_absent(arg_name) -%}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15'] %}}
- name: Check {{{ arg_name }}} argument exists
  command: grep '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"' /etc/default/grub
  failed_when: False
  register: argcheck

- name: Replace existing {{{ arg_name }}} argument
  replace:
      path: /etc/default/grub
      regexp: '\(^GRUB_CMDLINE_LINUX=".*\){{{ arg_name }}}=?[^[:space:]]*\(.*"\)'
      replace: '\1 \2'
  when: argcheck is not skipped and argcheck.rc == 0

{{% endif -%}}

{{% if product in ['sle12', 'sle15'] %}}
- name: Update grub defaults and the bootloader menu
  command: /usr/sbin/grub2-mkconfig -o {{{ grub2_boot_path }}}/grub.cfg
{{% elif 'debian' in product %}}
- name: Update grub defaults and the bootloader menu
  command: /usr/sbin/update-grub
{{% else %}}
- name: Update grub defaults and the bootloader menu
  command: /sbin/grubby --update-kernel=ALL --remove-args="{{{ arg_name }}}"
{{% endif -%}}
{{%- endmacro -%}}


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

#}}
{{%- macro ansible_restrict_permissions_home_directories(recursive=false) -%}}
- name: Get all local users from /etc/passwd
  ansible.builtin.getent:
    database: passwd
    split: ':'

- name: Create local_users variable from the getent output
  ansible.builtin.set_fact:
    local_users: '{{ ansible_facts.getent_passwd|dict2items }}'

- name: Test for existence home directories to avoid creating them.
  ansible.builtin.stat:
    path: '{{ item.value[4] }}'
  register: path_exists
  loop: '{{ local_users }}'
  when:
    - item.value[1]|int >= {{{ uid_min }}}
    - item.value[1]|int != {{{ nobody_uid }}}
    - item.value[4] != "/"

- name: Ensure interactive local users have proper permissions on their respective home directories
  ansible.builtin.file:
    path: '{{ item.0.value[4] }}'
    mode: 'u-s,g-w-s,o=-'
    follow: no
    {{%- if recursive %}}
    recurse: yes
    {{%- else %}}
    recurse: no
    {{%- endif %}}
  loop: '{{ local_users|zip(path_exists.results)|list }}'
  when:
    - item.1.stat is defined and item.1.stat.exists
{{%- 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 include the line below, if necessary. Optional parameter.
:type after_match: str

#}}
{{%- macro ansible_ensure_pam_module_line(pam_file, group, control, module, after_match='') -%}}
- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
  ansible.builtin.set_fact:
    pam_module_control: '{{{ control }}}'

- name: '{{{ rule_title }}} - Check if expected PAM module line is present in {{{ pam_file }}}'
  ansible.builtin.lineinfile:
    path: "{{{ pam_file }}}"
    regexp: ^\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s*.*
    state: absent
  check_mode: yes
  changed_when: false
  register: result_pam_line_present

- name: '{{{ rule_title }}} - Include or update the PAM module line in {{{ pam_file }}}'
  block:
    - name: '{{{ rule_title }}} - Check if required PAM module line is present in {{{ pam_file }}} with different control'
      ansible.builtin.lineinfile:
        path: "{{{ pam_file }}}"
        regexp: ^\s*{{{ group }}}\s+.*\s+{{{ module }}}\s*
        state: absent
      check_mode: yes
      changed_when: false
      register: result_pam_line_other_control_present

    - name: '{{{ rule_title }}} - Ensure the correct control for the required PAM module line in {{{ pam_file }}}'
      ansible.builtin.replace:
        dest: "{{{ pam_file }}}"
        regexp: '^(\s*{{{ group }}}\s+).*(\b{{{ module }}}.*)'
        replace: '\1{{ pam_module_control }} \2'
      register: result_pam_module_edit
      when:
        - result_pam_line_other_control_present.found == 1

    - name: '{{{ rule_title }}} - Ensure the required PAM module line is included in {{{ pam_file }}}'
      ansible.builtin.lineinfile:
        dest: "{{{ pam_file }}}"
        {{%- if after_match != '' %}}
        insertafter: {{{ after_match }}}
        {{%- endif %}}
        line: "{{{ group }}}    {{ pam_module_control }}    {{{ module }}}"
      register: result_pam_module_add
      when:
        - result_pam_line_other_control_present.found == 0 or result_pam_line_other_control_present.found > 1

    {{{ ansible_apply_authselect_changes() | indent(4) }}}
      when:
        - result_authselect_present is defined
        - result_authselect_present.stat.exists
        - >-
          (result_pam_module_add is defined and result_pam_module_add.changed)
           or (result_pam_module_edit is defined and result_pam_module_edit.changed)
  when:
    - result_pam_line_present.found is defined
    - result_pam_line_present.found == 0
{{%- 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 ansible_ensure_pam_module_option(pam_file, group, control, module, option, value='', after_match='') -%}}
{{{ ansible_ensure_pam_module_line(pam_file, group, control, module, after_match) }}}

- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
  ansible.builtin.set_fact:
    pam_module_control: '{{{ control }}}'

- name: '{{{ rule_title }}} - Check if the required PAM module option is present in {{{ pam_file }}}'
  ansible.builtin.lineinfile:
    path: "{{{ pam_file }}}"
    regexp: ^\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s*.*\s{{{ option }}}\b
    state: absent
  check_mode: true
  changed_when: false
  register: result_pam_module_{{{ rule_id }}}_option_present

- name: '{{{ rule_title }}} - Ensure the "{{{ option }}}" PAM option for "{{{ module }}}" is included in {{{ pam_file }}}'
  ansible.builtin.lineinfile:
    path: "{{{ pam_file }}}"
    backrefs: true
    regexp: ^(\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}.*)
    {{%- if value == '' %}}
    line: \1 {{{ option }}}
    {{%- else %}}
    line: \1 {{{ option }}}={{{ value }}}
    {{%- endif %}}
    state: present
  register: result_pam_{{{ rule_id }}}_add
  when:
    - result_pam_module_{{{ rule_id }}}_option_present.found == 0

{{%- if value != '' %}}
- name: '{{{ rule_title }}} - Ensure the required value for "{{{ option }}}" PAM option from "{{{ module }}}" in {{{ pam_file }}}'
  ansible.builtin.lineinfile:
    path: "{{{ pam_file }}}"
    backrefs: true
    regexp: ^(\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s+.*)({{{ option }}})=[0-9a-zA-Z]+\s*(.*)
    line: \1\2={{{ value }}} \3
  register: result_pam_{{{ rule_id }}}_edit
  when:
    - result_pam_module_{{{ rule_id }}}_option_present.found > 0
{{%- 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 ansible_remove_pam_module_option(pam_file, group, control, module, option) -%}}
- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
  ansible.builtin.set_fact:
    pam_module_control: '{{{ control }}}'

- name: '{{{ rule_title }}} - Ensure the "{{{ option }}}" option from "{{{ module }}}" is not present in {{{ pam_file }}}'
  ansible.builtin.replace:
    dest: "{{{ pam_file }}}"
    {{%- if control == '' %}}
    regexp: (.*{{{ group }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[0-9a-zA-Z]*(.*)
    {{%- else %}}
    regexp: (.*{{{ group }}}.*{{ pam_module_control | regex_escape() }}.*{{{ module }}}.*)\b{{{ option }}}\b=?[0-9a-zA-Z]*(.*)
    {{%- endif %}}
    replace: '\1\2'
  register: result_pam_option_removal
{{%- 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 taken. 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.

#}}
{{% macro ansible_ensure_authselect_custom_profile() -%}}
- name: '{{{ rule_title }}} - Get authselect current profile'
  ansible.builtin.shell:
    cmd: authselect current -r | awk '{ print $1 }'
  register: result_authselect_profile
  changed_when: false
  when:
    - result_authselect_check_cmd is success

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

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

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

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

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

- name: '{{{ rule_title }}} - Create an authselect custom profile based on sssd profile'
  ansible.builtin.command:
    cmd: authselect create-profile hardening -b sssd
  when:
    - result_authselect_check_cmd is success
    - authselect_current_profile is match("local")
    - not result_authselect_custom_profile_present.stat.exists

{{{ ansible_apply_authselect_changes('before-hardening-custom-profile') }}}
  when:
    - result_authselect_check_cmd is success
    - result_authselect_profile is not skipped
    - authselect_current_profile is not match("custom/")
    - authselect_custom_profile is not match(authselect_current_profile)

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

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

{{{ ansible_apply_authselect_changes('after-hardening-custom-profile') }}}
  when:
    - result_authselect_check_cmd is success
    - result_authselect_profile is not skipped
    - result_pam_authselect_restore_features is not skipped
{{%- endmacro %}}


{{#
    Check if the system is using authselect. If so, check the profile integrity and make sure
    a custom profile is ready to be updated. Otherwise, ensures the ansible fact referring
    to the PAM file to be edited is correctly set.

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

#}}
{{%- macro ansible_ensure_pam_facts_and_authselect_profile(pam_file) -%}}
- name: '{{{ rule_title }}} - Define the PAM file to be edited as a local fact'
  ansible.builtin.set_fact:
    pam_file_path: {{{ pam_file }}}

{{{ ansible_check_authselect_presence() }}}

- name: '{{{ rule_title }}} - Ensure authselect custom profile is used if authselect is present'
  block:
    {{{ ansible_check_authselect_integrity() | indent(4) }}}

    {{{ ansible_ensure_authselect_custom_profile() | indent(4) }}}

    - name: '{{{ rule_title }}} - Change the PAM file to be edited according to the custom authselect profile'
      ansible.builtin.set_fact:
        pam_file_path: "/etc/authselect/{{ authselect_custom_profile }}/{{ pam_file_path | basename }}"
  when:
    - result_authselect_present.stat.exists
{{%- 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 ansible_ensure_pam_module_configuration(pam_file, group, control, module, option, value='', after_match='') -%}}
- name: '{{{ rule_title }}} - Check if {{{ pam_file }}} file is present'
  ansible.builtin.stat:
    path: {{{ pam_file }}}
  register: result_pam_file_present

- name: '{{{ rule_title }}} - Check the proper remediation for the system'
  block:
    {{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}

    {{%- if option == '' %}}
    {{{ ansible_ensure_pam_module_line('{{ pam_file_path }}', group, control, module, after_match) | indent(4) }}}
    {{%- else %}}
    {{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', group, control, module, option, value, after_match) | indent(4) }}}
    {{%- endif %}}

    {{{ ansible_apply_authselect_changes() | indent(4) }}}
      when:
        - result_authselect_present.stat.exists
        - >-
          (result_pam_{{{ rule_id }}}_add is defined and result_pam_{{{ rule_id }}}_add.changed)
           or (result_pam_{{{ rule_id }}}_edit is defined and result_pam_{{{ rule_id }}}_edit.changed)
  when:
    - result_pam_file_present.stat.exists
{{%- 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 ansible_remove_pam_module_option_configuration(pam_file, group, control, module, option) -%}}
- name: '{{{ rule_title }}} - Check if {{{ pam_file }}} file is present'
  ansible.builtin.stat:
    path: {{{ pam_file }}}
  register: result_pam_file_present

- name: '{{{ rule_title }}} - Check the proper remediation for the system'
  block:
    {{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}

    {{{ ansible_remove_pam_module_option('{{ pam_file_path }}', group, control, module, option) | indent(4) }}}

    {{{ ansible_apply_authselect_changes() | indent(4) }}}
      when:
        - result_authselect_present.stat.exists
        - result_pam_option_removal is changed
  when:
    - result_pam_file_present.stat.exists
{{%- endmacro -%}}


{{%- macro ansible_mount_conditional(path) -%}}
'"{{{ path }}}" in ansible_mounts | map(attribute="mount") | list'
{{%- endmacro -%}}

{{#
    Create a list of paths composed by root directories and mount points representing local file systems.
    This list excludes all local directories and mount points using known remote file systems.
    It also excludes local directories and mount points with pseudo file systems. The list of paths
    created by this macro can be used to efficiently locate local files or directories in a system.

:param list_name:       Prefered list name to be used in subsequent tasks.
:type pam_file: str

#}}
{{%- macro ansible_create_list_of_local_paths(list_name="search_paths") -%}}
- name: "{{{ rule_title }}} - Define Excluded (Non-Local) File Systems and Paths"
  ansible.builtin.set_fact:
    excluded_fstypes:
      - afs
      - ceph
      - cifs
      - smb3
      - smbfs
      - sshfs
      - ncpfs
      - ncp
      - nfs
      - nfs4
      - gfs
      - gfs2
      - glusterfs
      - gpfs
      - pvfs2
      - ocfs2
      - lustre
      - davfs
      - fuse.sshfs
    excluded_paths:
      - dev
      - proc
      - run
      - sys
    {{{ list_name }}}: []

- name: "{{{ rule_title }}} - Find Relevant Root Directories Ignoring Pre-Defined Excluded Paths"
  ansible.builtin.find:
    paths: /
    file_type: directory
    excludes: "{{ excluded_paths }}"
    hidden: true
    recurse: false
  register: result_relevant_root_dirs

- name: "{{{ rule_title }}} - Include Relevant Root Directories in a List of Paths to be Searched"
  ansible.builtin.set_fact:
    {{{ list_name }}}: "{{ {{{ list_name }}} | union([item.path]) }}"
  loop: "{{ result_relevant_root_dirs.files }}"

- name: "{{{ rule_title }}} - Increment Search Paths List with Local Partitions Mount Points"
  ansible.builtin.set_fact:
    {{{ list_name }}}: "{{ {{{ list_name }}} | union([item.mount]) }}"
  loop: '{{ ansible_mounts }}'
  when:
    - item.fstype not in excluded_fstypes
    - item.mount != '/'

- name: "{{{ rule_title }}} - Increment Search Paths List with Local NFS File System Targets"
  ansible.builtin.set_fact:
    {{{ list_name }}}: "{{ {{{ list_name }}} | union([item.device.split(':')[1]]) }}"
  loop: '{{ ansible_mounts }}'
  when:
    - item.device is search("localhost:")
{{%- endmacro -%}}
