aboutsummaryrefslogtreecommitdiff
path: root/roles/ssh-port-fwd-user/tasks/main.yaml
blob: 8975cdbca2e5b90f07a92481199b0af4ed072068 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
- name: fail if required vars are missing
  assert:
    that:
      - port_fwd_user is defined

- name: set default shell if not defined
  set_fact:
    port_fwd_shell: "/bin/false"
  when: port_fwd_shell is not defined

- name: create restricted user
  user:
    name: "{{ port_fwd_user }}"
    shell: "{{ port_fwd_shell }}"
    create_home: yes
    password: '*'
    state: present

- name: ensure {{ ssh_key_dir }} exists
  ansible.builtin.file:
    path: "{{ ssh_key_dir }}"
    state: directory
    owner: "{{ port_fwd_user }}"
    group: "{{ port_fwd_user }}"
    mode: '0700'

- name: set ssh_key_dir
  set_fact:
    ssh_key_dir: "{{ ssh_key_dir }}"

- name: create ssh key pair on remote host
  community.crypto.openssh_keypair:
    path: "{{ ssh_key_dir }}/id_ed25519"
    type: ed25519
    owner: "{{ port_fwd_user }}"
    group: "{{ port_fwd_user }}"
    mode: '0600'
    comment: ""
    force: true

- name: set authorized_keys for restricted user
  copy:
    src: "{{ ssh_key_dir }}/id_ed25519.pub"
    dest: "{{ ssh_key_dir }}/authorized_keys"
    remote_src: yes
    owner: "{{ port_fwd_user }}"
    group: "{{ port_fwd_user }}"
    mode: '0600'

- name: create sshd_config.d drop-in
  copy:
    dest: "/etc/ssh/sshd_config.d/{{ port_fwd_user }}.conf"
    content: |
      Match User {{ port_fwd_user }}
        PasswordAuthentication no
        PubkeyAuthentication yes
        AllowTcpForwarding yes
        PermitOpen any
        GatewayPorts no
        X11Forwarding no
        PermitTunnel no
        AllowAgentForwarding no
        ForceCommand echo "port forwarding only"
    owner: root
    group: root
    mode: '0644'
  notify: restart ssh

- name: ensure /etc/ssh/sshd_config includes .d directory
  lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^Include /etc/ssh/sshd_config\.d/\*\.conf'
    line: 'Include /etc/ssh/sshd_config.d/*.conf'
    insertafter: EOF
  notify: restart ssh

- name: fetch private key to control node
  fetch:
    src: "{{ ssh_key_dir }}/id_ed25519"
    dest: "./{{ inventory_hostname }}_{{ port_fwd_user }}_id_ed25519"
    flat: true
    fail_on_missing: yes
    mode: '0600'