# platform = multi_platform_all
# reboot = true
# strategy = disable
# complexity = low
# disruption = medium

- name: Restrict usage of ptrace to descendant processes - Set fact for sysctl paths
  ansible.builtin.set_fact:

    sysctl_paths:
      - "/etc/sysctl.d/"
      - "/run/sysctl.d/"
      - "/usr/local/lib/sysctl.d/"



- name: Restrict usage of ptrace to descendant processes - Find all files that contain kernel.yama.ptrace_scope
  ansible.builtin.shell:
    cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep -HP '^\s*kernel.yama.ptrace_scope\s*=\s*.*$'
  register: find_all_values
  check_mode: false
  changed_when: false
  failed_when: false

- name: Restrict usage of ptrace to descendant processes - Find all files that set kernel.yama.ptrace_scope to correct value
  ansible.builtin.shell:
    cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep -HP '^\s*kernel.yama.ptrace_scope\s*=\s*1$'
  register: find_correct_value
  check_mode: false
  changed_when: false
  failed_when: false

- name: Restrict usage of ptrace to descendant processes - Comment out any occurrences of kernel.yama.ptrace_scope from config files
  ansible.builtin.replace:
    path: '{{ item | split(":") | first }}'
    regexp: '^[\s]*kernel.yama.ptrace_scope'
    replace: '#kernel.yama.ptrace_scope'
  loop: '{{ find_all_values.stdout_lines }}'
  when: find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines | length > find_correct_value.stdout_lines | length


- name: Restrict usage of ptrace to descendant processes - Comment out any occurrences of kernel.yama.ptrace_scope from /etc/ufw/sysctl.conf
  ansible.builtin.replace:
    path: "/etc/ufw/sysctl.conf"
    regexp: '(^[\s]*kernel.yama.ptrace_scope.*$)'
    replace: '# \1'



- name: Restrict usage of ptrace to descendant processes - Ensure sysctl kernel.yama.ptrace_scope is set to 1
  ansible.posix.sysctl:
    name: "kernel.yama.ptrace_scope"
    value: "1"

    sysctl_file: "/etc/sysctl.conf"

    state: present
    reload: yes
