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

- name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Set fact for sysctl paths
  ansible.builtin.set_fact:

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



- name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Find all files that contain net.ipv4.conf.all.route_localnet
  ansible.builtin.shell:
    cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep -HP '^\s*net.ipv4.conf.all.route_localnet\s*=\s*.*$'
  register: find_all_values
  check_mode: false
  changed_when: false
  failed_when: false

- name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Find all files that set net.ipv4.conf.all.route_localnet to correct value
  ansible.builtin.shell:
    cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep -HP '^\s*net.ipv4.conf.all.route_localnet\s*=\s*0$'
  register: find_correct_value
  check_mode: false
  changed_when: false
  failed_when: false

- name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Comment out any occurrences of net.ipv4.conf.all.route_localnet from config files
  ansible.builtin.replace:
    path: '{{ item | split(":") | first }}'
    regexp: '^[\s]*net.ipv4.conf.all.route_localnet'
    replace: '#net.ipv4.conf.all.route_localnet'
  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: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Comment out any occurrences of net.ipv4.conf.all.route_localnet from /etc/ufw/sysctl.conf
  ansible.builtin.replace:
    path: "/etc/ufw/sysctl.conf"
    regexp: '(^[\s]*net.ipv4.conf.all.route_localnet.*$)'
    replace: '# \1'



- name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces - Ensure sysctl net.ipv4.conf.all.route_localnet is set to 0
  ansible.posix.sysctl:
    name: "net.ipv4.conf.all.route_localnet"
    value: "0"

    sysctl_file: "/etc/sysctl.conf"

    state: present
    reload: yes
