---
- name: Remove unused packages
  apt:
    name: "{{ unused_packages }}"
    state: absent
  tags:
    - apt
    - hardening

# After installing securedrop-grsec, remove
# old generic kernels to avoid accidental
# boots into a less secure environment.
# We must used command due to the use of wildcards
- name: Remove generic kernel packages.
  command: apt-get remove -y {{ item }}
  with_items: "{{ securedrop_kernel_packages_to_remove }}"
  register: apt_removed_kernels
  changed_when: "'The following packages will be REMOVED' in apt_removed_kernels.stdout"
  tags:
    - apt

- name: Get list of all installed kernels.
  shell: dpkg-query -f '${Package} ${Status}\n' -W 'linux-image*' | awk '$NF == "installed"{print $1}'
  register: apt_installed_kernels
  changed_when: false
  tags:
    - apt

- name: Validate that all installed kernels are grsecurity-hardened.
  assert:
    that:
      - item is search('-grsec')
    msg: "Not all non-grsec kernels have been removed, run dpkg-query -W 'linux-image*' for more details."
  with_items: "{{ apt_installed_kernels.stdout_lines }}"
  tags:
    - apt
    - grsecurity

- name: Remove dependencies that are no longer required
  apt:
    autoremove: yes
  tags:
    - apt
    - hardening

---
- name: Remove unused packages
  apt:
    name: "{{ unused_packages }}"
    state: absent
    purge: yes
  tags:
    - apt
    - hardening

# After installing securedrop-grsec, remove
# old generic kernels to avoid accidental
# boots into a less secure environment.
# We must used command due to the use of wildcards
- name: Remove generic kernel packages.
  command: apt-get remove -y {{ item }}
  with_items: "{{ securedrop_kernel_packages_to_remove }}"
  register: apt_removed_kernels
  changed_when: "'The following packages will be REMOVED' in apt_removed_kernels.stdout"
  tags:
    - apt

- name: Get list of all installed kernels.
  shell: dpkg-query -f '${Package} ${Status}\n' -W 'linux-image*' | awk '$NF == "installed"{print $1}'
  register: apt_installed_kernels
  changed_when: false
  tags:
    - apt

- name: Validate that all installed kernels are grsecurity-hardened.
  assert:
    that:
      - item is search('-grsec')
    msg: "Not all non-grsec kernels have been removed, run dpkg-query -W 'linux-image*' for more details."
  with_items: "{{ apt_installed_kernels.stdout_lines }}"
  tags:
    - apt
    - grsecurity

- name: Remove dependencies that are no longer required
  apt:
    autoremove: yes
  tags:
    - apt
    - hardening

Make sure to purge unwanted packages
Make sure to purge unwanted packages

If we don't purge them, config files can linger, causing problems with
other services. Discovered during removal of snapd, which will leave
apparmor profiles (as well as the old snaps themselves) on disk if only
removed, but not purged.
