---
# ssh-hardening / windows / t0 "Quick start"
#
# OpenSSH Server on Windows, keys only, with the configuration tested before
# the service restarts.
#
# Needs the Windows collection on the machine running Ansible:
#   ansible-galaxy collection install ansible.windows:==3.3.0
#
# Ansible reaches the servers over WinRM, so a bad SSH configuration cannot
# lock Ansible out. It can still lock people out, which is what the key check
# below is for.
#
# Put each administrator's public key in the file named under settings on
# every server first. Then run:
#   ansible-playbook -i inventory.ini playbook.yml
#
# Verify, from another machine:
#   ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password admin@server
#   It should be refused without asking for a password.

- name: Lock SSH down to keys only
  hosts: all
  gather_facts: false

  vars:
    # Administrators' keys go here, never in their own profile. The stock
    # configuration ignores a profile key for any member of Administrators.
    admin_keys_file: C:\ProgramData\ssh\administrators_authorized_keys
    require_admin_key: true # change me to false only if you have another way in

  tasks:
    - name: Install OpenSSH Server
      ansible.windows.win_powershell:
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param()
          $cap = Get-WindowsCapability -Online -Name 'OpenSSH.Server*'
          if ($cap.State -eq 'Installed') { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess($cap.Name, 'install')) {
            Add-WindowsCapability -Online -Name $cap.Name | Out-Null
          }

    # The first start writes the host keys and the stock configuration. The
    # test further down needs both to exist.
    - name: Start sshd once so it creates its host keys
      ansible.windows.win_service:
        name: sshd
        start_mode: auto
        state: started

    - name: Look for the administrators' key file
      ansible.windows.win_stat:
        path: "{{ admin_keys_file }}"
      register: admin_keys

    - name: Stop if there is no key to log in with
      ansible.builtin.assert:
        that:
          - admin_keys.stat.exists
          - admin_keys.stat.size > 0
        fail_msg: >-
          {{ inventory_hostname }} has no keys in {{ admin_keys_file }}. Add at least one
          administrator's public key first, or set require_admin_key to false if you have
          another way in, such as a console or RDP.
      when: require_admin_key | bool

    # sshd ignores this file, silently, unless only Administrators and SYSTEM
    # can reach it. A key in a file with the wrong permissions does not work,
    # and with passwords off that is a lockout.
    - name: Restrict the key file to Administrators and SYSTEM
      ansible.windows.win_powershell:
        parameters:
          Path: "{{ admin_keys_file }}"
        script: |
          [CmdletBinding(SupportsShouldProcess)]
          param([string]$Path)
          if (-not (Test-Path $Path)) { $Ansible.Changed = $false; return }
          $acl = Get-Acl $Path
          $who = $acl.Access | ForEach-Object { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } | Sort-Object -Unique
          if ($acl.AreAccessRulesProtected -and (($who -join ',') -eq 'S-1-5-18,S-1-5-32-544')) { $Ansible.Changed = $false; return }
          if ($PSCmdlet.ShouldProcess($Path, 'restrict to Administrators and SYSTEM')) {
            icacls.exe $Path /inheritance:r /grant:r '*S-1-5-32-544:F' /grant:r '*S-1-5-18:F' | Out-Null
            if ($LASTEXITCODE -ne 0) { throw "icacls could not set permissions on $Path" }
            # /grant:r replaces those two entries. Anyone else granted access
            # directly keeps it unless removed by name.
            foreach ($sid in $who) {
              if ('S-1-5-18', 'S-1-5-32-544' -notcontains $sid) { icacls.exe $Path /remove "*$sid" | Out-Null }
            }
          }

    # The whole file, so the result does not depend on which OpenSSH version
    # the Windows build shipped or what an earlier edit left behind.
    - name: Write the new configuration next to the live one
      ansible.windows.win_copy:
        dest: C:\ProgramData\ssh\sshd_config.new
        content: |
          # Managed by Ansible. Local edits are overwritten on the next run.
          PasswordAuthentication no
          PermitEmptyPasswords no
          PubkeyAuthentication yes
          AuthorizedKeysFile .ssh/authorized_keys
          MaxAuthTries 4
          LoginGraceTime 30
          AllowAgentForwarding no
          ClientAliveInterval 300
          ClientAliveCountMax 2
          Subsystem sftp sftp-server.exe

          Match Group administrators
                 AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

    - name: Test the new configuration before it goes live
      ansible.windows.win_command: C:\Windows\System32\OpenSSH\sshd.exe -t -f C:\ProgramData\ssh\sshd_config.new
      changed_when: false

    - name: Put it live
      ansible.windows.win_copy:
        src: C:\ProgramData\ssh\sshd_config.new
        dest: C:\ProgramData\ssh\sshd_config
        remote_src: true
      notify: Restart sshd
      # In a preview the new file was never written, so there is nothing to copy.
      when: not ansible_check_mode

    - name: Flush handlers so the check below reads the running configuration
      ansible.builtin.meta: flush_handlers

    - name: Read back the settings sshd will actually use
      ansible.windows.win_command: C:\Windows\System32\OpenSSH\sshd.exe -T
      changed_when: false
      register: effective

    - name: Confirm password logins are off
      ansible.builtin.assert:
        that:
          - "'passwordauthentication no' in effective.stdout | lower"
        fail_msg: sshd still accepts passwords on {{ inventory_hostname }}.
        success_msg: Key-only logins confirmed.
      when: not ansible_check_mode

  handlers:
    - name: Restart sshd
      ansible.windows.win_service:
        name: sshd
        state: restarted
