From 177ba579e9fd4d321a1708181d8999849610a625 Mon Sep 17 00:00:00 2001 From: Jan Beilicke Date: Mon, 11 Dec 2023 18:36:27 +0100 Subject: [PATCH] Disables SSH access for root on demand --- defaults/main.yml | 6 +++++- handlers/main.yml | 7 ++++++- tasks/users.yml | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/defaults/main.yml b/defaults/main.yml index d8197fa..9f87a85 100644 --- a/defaults/main.yml +++ b/defaults/main.yml @@ -18,6 +18,10 @@ ensure_ansible_version: 2.10.3 enable_sudo: yes # Allow passwordless sudo (applied to group wheel) enable_passwordless_sudo: yes +# Allow root to connect through SSH +enable_ssh_for_root: yes +# Allow root to connect only using public key authentication, no password +enable_ssh_for_root_prohibit_password: no # Skip provisioning of the firewall skip_firewall: no -authorized_keys_are_exclusive: false # Be careful, this will delete non-Ansible-managed authorized keys from the target! +authorized_keys_are_exclusive: false # Be careful, this will delete non-Ansible-managed authorized keys from the target! \ No newline at end of file diff --git a/handlers/main.yml b/handlers/main.yml index c6a8f0c..d4fec81 100644 --- a/handlers/main.yml +++ b/handlers/main.yml @@ -1,2 +1,7 @@ --- -# handlers file for common \ No newline at end of file +# handlers file for common +- name: Restart SSH + ansible.builtin.service: + name: ssh + state: restarted + become: true \ No newline at end of file diff --git a/tasks/users.yml b/tasks/users.yml index 8dfd11a..854c96c 100644 --- a/tasks/users.yml +++ b/tasks/users.yml @@ -72,6 +72,38 @@ files: - /etc/sudoers - /usr/local/etc/sudoers # e.g. FreeBSD + + - name: 'Disable SSH for root' + lineinfile: + dest: "/etc/ssh/sshd_config" + state: present + regexp: '^#?\s*PermitRootLogin' + line: 'PermitRootLogin No' + notify: Restart SSH + when: + - enable_ssh_for_root | bool == false + + - name: 'Enable SSH for root through password or key' + lineinfile: + dest: "/etc/ssh/sshd_config" + state: present + regexp: '^#?\s*PermitRootLogin' + line: 'PermitRootLogin Yes' + notify: Restart SSH + when: + - enable_ssh_for_root | bool == true + - enable_ssh_for_root_prohibit_password | bool == false + + - name: 'Enable SSH for root through key only' + lineinfile: + dest: "/etc/ssh/sshd_config" + state: present + regexp: '^#?\s*PermitRootLogin' + line: 'PermitRootLogin prohibit-password' + notify: Restart SSH + when: + - enable_ssh_for_root | bool == true + - enable_ssh_for_root_prohibit_password | bool == true when: - enable_sudo - enable_passwordless_sudo @@ -83,4 +115,4 @@ mode: 0644 owner: "{{ item }}" group: "{{ item }}" - with_items: "{{ users }}" \ No newline at end of file + with_items: "{{ users }}"