---
# host-audit-rules / linux / t0 "Quick start"
#
# auditd rules for what an investigation asks first on a Linux host: who
# changed accounts, sudo rights, or SSH keys, what was set to start on its
# own, which kernel modules loaded, and which commands people ran as root.
#
# Run:
#   ansible-playbook -i inventory.ini playbook.yml
#
# Verify:
#   ansible all -i inventory.ini -b -a "touch /etc/sudoers.d/iac-test"
#   ansible all -i inventory.ini -b -a "ausearch -k privilege -ts recent"
#   The touch shows up, with the account that did it. Then remove the file:
#   ansible all -i inventory.ini -b -a "rm /etc/sudoers.d/iac-test"

- name: Record what investigations ask for first
  hosts: all
  become: true
  gather_facts: true

  tasks:
    - name: Install auditd
      ansible.builtin.package:
        name: "{{ 'audit' if ansible_facts['os_family'] == 'RedHat' else 'auditd' }}"
        state: present

    # Rules in /etc/audit/rules.d/ are merged into audit.rules by augenrules
    # at boot and when the handler below runs.
    - name: Write the rules
      ansible.builtin.copy:
        dest: /etc/audit/rules.d/50-iac.rules
        owner: root
        group: root
        mode: "0640"
        content: |
          ## Managed by Ansible. Local edits are overwritten on the next run.
          ## Each line ends in -k <key>; search by key with ausearch -k <key>.

          ## Accounts and groups
          -w /etc/passwd -p wa -k identity
          -w /etc/group -p wa -k identity
          -w /etc/shadow -p wa -k identity
          -w /etc/gshadow -p wa -k identity

          ## Who may become root
          -w /etc/sudoers -p wa -k privilege
          -w /etc/sudoers.d -p wa -k privilege

          ## SSH: server settings, and keys that let someone back in
          -w /etc/ssh/sshd_config -p wa -k sshd
          -w /etc/ssh/sshd_config.d -p wa -k sshd
          -w /root/.ssh -p wa -k ssh_keys

          ## Places programs are set to start on their own
          -w /etc/crontab -p wa -k persistence
          -w /etc/cron.d -p wa -k persistence
          -w /var/spool/cron -p wa -k persistence
          -w /etc/systemd/system -p wa -k persistence
          -w /etc/ld.so.preload -p wa -k persistence

          ## Kernel modules loaded or removed
          -a always,exit -F arch=b64 -S init_module,finit_module,delete_module -k modules

          ## Commands people ran as root. auid is the account that signed in,
          ## so this is what someone did after sudo, not what services did.
          ## 64-bit programs only here; Standard adds 32-bit ones on x86_64.
          -a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=unset -k root_commands
      notify: Load the rules

  handlers:
    # auditd refuses a plain systemctl restart. augenrules --load rebuilds
    # the rule set and loads it without restarting the daemon.
    - name: Load the rules
      ansible.builtin.command: augenrules --load
      changed_when: true
