From dcdc9133f6313688d0d9c0c652549f77b004c72c Mon Sep 17 00:00:00 2001 From: Dragonish Date: Sat, 14 Nov 2026 14:26:19 +0000 Subject: [PATCH 1/2] feat(system_baseline): optional tmux session on SSH login Adds tmux to the ubuntu_lxc and ubuntu_vm profiles and an opt-in /etc/profile.d snippet that attaches an interactive SSH login to a tmux session, created with configurable windows when it does not exist. - system_baseline_tmux_autostart (default false), _session (default main) and _windows ([{name, command}]); only ubuntu_lxc and ubuntu_vm install the snippet, pve never does, and false removes it. - profile.d is read only by an interactive login shell, so scp, sftp, ssh host command and automation are unaffected. ~/.no-tmux opts a user out. ForceCommand is not used: it would affect every session type. - Names and commands are validated and shell-quoted; the script is root-owned. Commands run as the logging-in user and are world-readable, so they must hold no secret. - Molecule converge enables it, verify checks ownership, mode, the attach line, the quoting and sh -n. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Q72rsMEKREGMfB9DH3T9mR --- changelogs/fragments/system-baseline-tmux.yml | 6 +++ roles/system_baseline/README.md | 23 +++++++++- roles/system_baseline/defaults/main.yml | 9 ++++ roles/system_baseline/meta/argument_specs.yml | 35 +++++++++++++++- .../molecule/default/converge.yml | 7 ++++ .../molecule/default/verify.yml | 24 +++++++++++ roles/system_baseline/tasks/main.yml | 4 ++ roles/system_baseline/tasks/tmux.yml | 42 +++++++++++++++++++ .../templates/tmux-autostart.sh.j2 | 14 +++++++ 9 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 changelogs/fragments/system-baseline-tmux.yml create mode 100644 roles/system_baseline/tasks/tmux.yml create mode 100644 roles/system_baseline/templates/tmux-autostart.sh.j2 diff --git a/changelogs/fragments/system-baseline-tmux.yml b/changelogs/fragments/system-baseline-tmux.yml new file mode 100644 index 0000000..3cbd640 --- /dev/null +++ b/changelogs/fragments/system-baseline-tmux.yml @@ -0,0 +1,6 @@ +--- +minor_changes: + - >- + system_baseline - add an optional tmux session on SSH login for the ``ubuntu_lxc`` and ``ubuntu_vm`` profiles + (``system_baseline_tmux_autostart``, ``system_baseline_tmux_session``, ``system_baseline_tmux_windows``). + It is off by default. The two profiles now install ``tmux``. diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index 3370d07..d012d1e 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -1,6 +1,6 @@ # system_baseline -Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, package install and removal, unattended-upgrades, locale, timezone, a journal size cap, sysctl hardening, tmpfs mounts and an optional reboot. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. +Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, package install and removal, unattended-upgrades, locale, timezone, a journal size cap, sysctl hardening, tmpfs mounts, an optional tmux session on SSH login and an optional reboot. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. ## Supported platforms @@ -36,6 +36,9 @@ templating error instead of the role's own message. | `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs | | `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` | | `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). | +| `system_baseline_tmux_autostart` | `false` | no | Attach interactive SSH logins to a tmux session (`ubuntu_lxc` and `ubuntu_vm` only) | +| `system_baseline_tmux_session` | `main` | no | Session name, `A-Za-z0-9_-`, up to 32 characters | +| `system_baseline_tmux_windows` | `[]` | no | `{name, command}` windows made when the session is created | | `system_baseline_timezone` | `Etc/UTC` | no | Timezone | | `system_baseline_locale` | `en_US.UTF-8` | no | Locale | | `system_baseline_reboot_if_required` | `true` | no | Reboot when `/var/run/reboot-required` exists | @@ -78,7 +81,7 @@ Besides `main`, two task files are a supported interface, for a caller that driv ## Tags -`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `sysctl`, `secure_tmp`. +`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `sysctl`, `secure_tmp`, `tmux`. ## Example play @@ -92,6 +95,22 @@ Besides `main`, two task files are a supported interface, for a caller that driv - role: mortis.kamino.system_baseline ``` +## tmux on SSH login + +With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; `pve` never gets the snippet. + +```yaml +system_baseline_tmux_autostart: true +system_baseline_tmux_session: ops +system_baseline_tmux_windows: + - { name: logs, command: "journalctl -f" } +``` + +- It is `/etc/profile.d/tmux-autostart.sh`, read only by an interactive login shell, so `scp`, `sftp`, `ssh host command` and Ansible never trigger it. sshd's `ForceCommand` is not used: it applies to every session type and a broken tmux would lock all of them out. It only acts for an SSH login with a terminal, outside tmux, and without `~/.no-tmux`. +- Turn it off for one login with `ssh -t host bash` (a non-login shell does not read `/etc/profile.d`), for one user with `touch ~/.no-tmux`, and for the host by setting the variable to `false` and running the role (it removes the snippet). +- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. +- Security: the name and commands are validated (`A-Za-z0-9_-`, one line) and shell-quoted, and come from the inventory, never from a user. The file is root-owned and not writable by its users. The commands run as the user who logs in, are readable by every user and show in `ps`: no secrets in a command. A session outlives the SSH connection, so a root session stays open until it is closed. + ## Notes - The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`. diff --git a/roles/system_baseline/defaults/main.yml b/roles/system_baseline/defaults/main.yml index 0f08499..64a213b 100644 --- a/roles/system_baseline/defaults/main.yml +++ b/roles/system_baseline/defaults/main.yml @@ -6,6 +6,13 @@ system_baseline_locale: "en_US.UTF-8" system_baseline_reboot_if_required: true # Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it. system_baseline_journal_max_use: 200M +# Attach an interactive SSH login to a tmux session (see tasks/tmux.yml). Off by default: it changes what every login does. +# Only the ubuntu_lxc and ubuntu_vm profiles honour it; pve never installs the snippet. +system_baseline_tmux_autostart: false +# Name of the session an SSH login attaches to. +system_baseline_tmux_session: main +# Windows created, as extra entries next to a plain shell, when the session is created: a list of {name, command}. +system_baseline_tmux_windows: [] # Per-system_type policy. Everything below is a role default, so group_vars and host_vars # override it with normal Ansible precedence. @@ -83,6 +90,7 @@ system_baseline_profiles: essential_packages: - logrotate - vim + - tmux - curl - wget - git @@ -137,6 +145,7 @@ system_baseline_profiles: - qemu-guest-agent - logrotate - vim + - tmux - curl - wget - git diff --git a/roles/system_baseline/meta/argument_specs.yml b/roles/system_baseline/meta/argument_specs.yml index 7e0346e..5dcd22c 100644 --- a/roles/system_baseline/meta/argument_specs.yml +++ b/roles/system_baseline/meta/argument_specs.yml @@ -5,7 +5,7 @@ argument_specs: description: - >- Validates C(system_baseline_system_type), then runs the update, packages, unattended-upgrades, locale, timezone, journald, - sysctl, tmpfs and reboot task files, in that order. + sysctl, tmpfs, tmux and reboot task files, in that order. - Needs gathered facts, because the reboot check reads C(ansible_os_family). - >- The resolved inputs C(system_baseline_profile), C(system_baseline_essential_packages), @@ -42,6 +42,39 @@ argument_specs: description: - Upper bound of the persistent systemd journal (journald C(SystemMaxUse), for example C(200M)). - Written to a drop-in under C(/etc/systemd/journald.conf.d). + system_baseline_tmux_autostart: + type: bool + default: false + description: + - >- + Attach an interactive SSH login to a tmux session, creating it when it does not exist. Installs C(/etc/profile.d/tmux-autostart.sh), + read only by an interactive login shell, so scp, sftp, C(ssh host command) and automation are unaffected. A user opts out with + C(~/.no-tmux). Only the C(ubuntu_lxc) and C(ubuntu_vm) profiles install it; with false, or on C(pve), the file is removed. + system_baseline_tmux_session: + type: str + default: main + description: + - Name of the session, 1 to 32 characters of C(A-Za-z0-9_-). Checked only when C(system_baseline_tmux_autostart) is true. + system_baseline_tmux_windows: + type: list + elements: dict + default: [] + description: + - >- + Windows made when the session is created (a login that only re-attaches adds none), next to a plain shell. A window closes when its + command exits. The commands come from the inventory and are shell-quoted, but they run as the user who logs in, are readable by + every user on the host and show in C(ps): put no secret in one. + options: + name: + type: str + required: true + description: + - Window name, 1 to 32 characters of C(A-Za-z0-9_-). + command: + type: str + required: true + description: + - One-line shell command (no line break) run in the window. system_baseline_timezone: type: str default: Etc/UTC diff --git a/roles/system_baseline/molecule/default/converge.yml b/roles/system_baseline/molecule/default/converge.yml index 2cbb555..4caf575 100644 --- a/roles/system_baseline/molecule/default/converge.yml +++ b/roles/system_baseline/molecule/default/converge.yml @@ -24,6 +24,10 @@ gather_facts: true vars: system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: true + system_baseline_tmux_session: molecule + system_baseline_tmux_windows: + - { name: logs, command: "echo 'a b'; true" } roles: - role: mortis.kamino.system_baseline @@ -44,6 +48,8 @@ ansible.builtin.assert: that: - "'ufw' not in system_baseline_essential_packages" + - "'tmux' not in system_baseline_essential_packages" + - not system_baseline_tmux_autostart - "'unattended-upgrades' in system_baseline_essential_packages" - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00' @@ -65,6 +71,7 @@ ansible.builtin.assert: that: - "'qemu-guest-agent' in system_baseline_essential_packages" + - "'tmux' in system_baseline_essential_packages" - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' - system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1 diff --git a/roles/system_baseline/molecule/default/verify.yml b/roles/system_baseline/molecule/default/verify.yml index 8849164..0b2c280 100644 --- a/roles/system_baseline/molecule/default/verify.yml +++ b/roles/system_baseline/molecule/default/verify.yml @@ -13,6 +13,7 @@ - "'ufw' in ansible_facts.packages" - "'fail2ban' in ansible_facts.packages" - "'unattended-upgrades' in ansible_facts.packages" + - "'tmux' in ansible_facts.packages" - "'telnet' not in ansible_facts.packages" quiet: true @@ -27,6 +28,29 @@ - system_baseline_verify_journald.content | b64decode is search('(?m)^SystemMaxUse=200M$') quiet: true + - name: Read the tmux auto-start snippet + ansible.builtin.slurp: + src: /etc/profile.d/tmux-autostart.sh + register: system_baseline_verify_tmux + + - name: Stat the tmux auto-start snippet + ansible.builtin.stat: + path: /etc/profile.d/tmux-autostart.sh + register: system_baseline_verify_tmux_stat + + - name: The snippet is root-owned, attaches to the session, and quotes the window command as one argument + ansible.builtin.assert: + that: + - system_baseline_verify_tmux_stat.stat.pw_name == 'root' + - system_baseline_verify_tmux_stat.stat.mode == '0644' + - system_baseline_verify_tmux.content | b64decode is search('tmux attach-session -t =molecule') + - system_baseline_verify_tmux.content | b64decode is search("-n logs 'echo '\"'\"'a b'\"'\"'; true'") + quiet: true + + - name: The snippet is valid shell + ansible.builtin.command: /bin/sh -n /etc/profile.d/tmux-autostart.sh + changed_when: false + - name: Read the apt configuration the role writes ansible.builtin.slurp: src: "{{ item }}" diff --git a/roles/system_baseline/tasks/main.yml b/roles/system_baseline/tasks/main.yml index aa70e51..28b8707 100644 --- a/roles/system_baseline/tasks/main.yml +++ b/roles/system_baseline/tasks/main.yml @@ -36,6 +36,10 @@ ansible.builtin.import_tasks: secure_tmp.yml tags: secure_tmp +- name: Start tmux on SSH login + ansible.builtin.import_tasks: tmux.yml + tags: tmux + - name: Reboot if required ansible.builtin.import_tasks: reboot.yml tags: update diff --git a/roles/system_baseline/tasks/tmux.yml b/roles/system_baseline/tasks/tmux.yml new file mode 100644 index 0000000..887dc4a --- /dev/null +++ b/roles/system_baseline/tasks/tmux.yml @@ -0,0 +1,42 @@ +--- +# Attach an interactive SSH login to a tmux session, created with the configured windows when it does not exist. +# /etc/profile.d is read only by an interactive login shell, so scp, sftp, `ssh host command` and automation never trigger it. +# sshd's ForceCommand is deliberately not used: it applies to every session type and a broken tmux would lock out all of them. +# +# Security: the session name, window names and commands are role inputs (inventory), never read from a user or a fact. They are +# validated here and shell-quoted in the template. The script is root-owned and not writable by the users it runs for. It is +# world-readable and the commands show in `ps`, so a command must hold no secret. Commands run as the user who logs in. +- name: Check the tmux inputs + ansible.builtin.assert: + that: + - system_baseline_tmux_session is match('^[A-Za-z0-9_-]{1,32}$') + - system_baseline_tmux_windows is sequence and system_baseline_tmux_windows is not string + - system_baseline_tmux_windows | map(attribute='name', default='') | map('regex_search', '^[A-Za-z0-9_-]{1,32}$') | select | list | length + == system_baseline_tmux_windows | length + - system_baseline_tmux_windows | map(attribute='command', default='') | select('match', '^[^\n\r]+$') | list | length + == system_baseline_tmux_windows | length + fail_msg: >- + system_baseline_tmux_session must be 1-32 characters of A-Z a-z 0-9 _ - ; every system_baseline_tmux_windows entry needs + a name (same characters) and a one-line command. + quiet: true + when: system_baseline_tmux_autostart | bool + +- name: Install the tmux auto-start snippet + ansible.builtin.template: + src: tmux-autostart.sh.j2 + dest: /etc/profile.d/tmux-autostart.sh + owner: root + group: root + mode: "0644" + validate: /bin/sh -n %s + when: + - system_baseline_tmux_autostart | bool + - system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm'] + become: true + +- name: Remove the tmux auto-start snippet + ansible.builtin.file: + path: /etc/profile.d/tmux-autostart.sh + state: absent + when: not (system_baseline_tmux_autostart | bool and system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm']) + become: true diff --git a/roles/system_baseline/templates/tmux-autostart.sh.j2 b/roles/system_baseline/templates/tmux-autostart.sh.j2 new file mode 100644 index 0000000..66dd9c0 --- /dev/null +++ b/roles/system_baseline/templates/tmux-autostart.sh.j2 @@ -0,0 +1,14 @@ +# Managed by Ansible (mortis.kamino.system_baseline, tasks/tmux.yml). Do not edit: the next run overwrites it. +# Interactive SSH logins only (profile.d is not read by scp, sftp, `ssh host command` or Ansible). +# Off for one user: touch ~/.no-tmux +if [ -n "$SSH_CONNECTION" ] && [ -z "$TMUX" ] && [ -t 0 ] && [ ! -e "$HOME/.no-tmux" ] && command -v tmux >/dev/null 2>&1; then + # new-session -d fails when the session exists, so the windows below are made only when this login creates it (once, even + # for two logins at the same moment). Windows close when their command exits; window 0 is always a plain shell. + if tmux new-session -d -s {{ system_baseline_tmux_session | quote }} 2>/dev/null; then + : +{% for window in system_baseline_tmux_windows %} + tmux new-window -d -t {{ ('=' ~ system_baseline_tmux_session ~ ':') | quote }} -n {{ window.name | quote }} {{ window.command | quote }} +{% endfor %} + fi + exec tmux attach-session -t {{ ('=' ~ system_baseline_tmux_session) | quote }} +fi -- 2.43.0 From da3389eac154c6490a8c519c2300f17cfd2124e3 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Sat, 14 Nov 2026 16:34:14 +0000 Subject: [PATCH 2/2] fix(system_baseline): keep tmux autostart from ending or swallowing logins Review of #122. - A failed attach no longer closes the connection: the snippet does not exec tmux, it prints a line and leaves the plain shell (a client TERM without terminfo made every login fail). A clean detach still ends the connection. - The snippet acts only for an interactive shell (case $-): a login shell that is not interactive, such as `ssh -t host 'bash -lc cmd'`, is left alone. Docs corrected. - Validation anchors with \Z, so a trailing newline from a YAML block scalar is refused. It moves to validate.yml (tag always); argument_specs already covers types. - Install keys on tmux being in the resolved package list, not a second profile list. - verify.yml: the snippet does nothing without a terminal, the trailing-newline refusals, and the removal path. The vacuous pve assert is gone. - README and argument_specs: window commands start with a minimal environment (use absolute paths), zsh and fish do not read /etc/profile.d, detach ends the connection. --- roles/system_baseline/README.md | 6 +- roles/system_baseline/meta/argument_specs.yml | 12 ++- .../molecule/default/converge.yml | 1 - .../molecule/default/verify.yml | 82 +++++++++++++++++++ roles/system_baseline/tasks/tmux.yml | 31 ++----- roles/system_baseline/tasks/validate.yml | 17 ++++ .../templates/tmux-autostart.sh.j2 | 28 ++++--- 7 files changed, 137 insertions(+), 40 deletions(-) diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index d012d1e..a259d79 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -106,9 +106,11 @@ system_baseline_tmux_windows: - { name: logs, command: "journalctl -f" } ``` -- It is `/etc/profile.d/tmux-autostart.sh`, read only by an interactive login shell, so `scp`, `sftp`, `ssh host command` and Ansible never trigger it. sshd's `ForceCommand` is not used: it applies to every session type and a broken tmux would lock all of them out. It only acts for an SSH login with a terminal, outside tmux, and without `~/.no-tmux`. +- It is `/etc/profile.d/tmux-autostart.sh`. Every login shell reads that directory, so the snippet itself acts only for an interactive shell (`case $-`) with a terminal and an SSH connection, outside tmux, and without `~/.no-tmux`. `scp`, `sftp`, `ssh host command`, Ansible and `ssh -t host 'bash -lc cmd'` never trigger it. sshd's `ForceCommand` is not used: it applies to every session type and a broken tmux would lock all of them out. Users whose login shell is zsh or fish are not affected, because those shells do not read `/etc/profile.d`. +- The snippet is installed when autostart is on and the resolved package list contains `tmux` (the `ubuntu_lxc` and `ubuntu_vm` profiles). If you override `system_baseline_essential_packages` without it, nothing is installed. +- A failed attach (for example a client `TERM` such as `xterm-kitty` or `wezterm` without a terminfo entry on the host) prints a line and leaves a plain shell. Detaching (`Ctrl-b d`) ends the SSH connection, as `exit` would. - Turn it off for one login with `ssh -t host bash` (a non-login shell does not read `/etc/profile.d`), for one user with `touch ~/.no-tmux`, and for the host by setting the variable to `false` and running the role (it removes the snippet). -- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. +- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. A window command runs with `sh -c` from the tmux server of the first login, before `~/.profile` is read, so it does not see `~/.local/bin` and other additions made there: use absolute paths. - Security: the name and commands are validated (`A-Za-z0-9_-`, one line) and shell-quoted, and come from the inventory, never from a user. The file is root-owned and not writable by its users. The commands run as the user who logs in, are readable by every user and show in `ps`: no secrets in a command. A session outlives the SSH connection, so a root session stays open until it is closed. ## Notes diff --git a/roles/system_baseline/meta/argument_specs.yml b/roles/system_baseline/meta/argument_specs.yml index 5dcd22c..0ead5bd 100644 --- a/roles/system_baseline/meta/argument_specs.yml +++ b/roles/system_baseline/meta/argument_specs.yml @@ -4,7 +4,8 @@ argument_specs: short_description: Apply the OS baseline for a system type description: - >- - Validates C(system_baseline_system_type), then runs the update, packages, unattended-upgrades, locale, timezone, journald, + Validates C(system_baseline_system_type) and, when C(system_baseline_tmux_autostart) is true, the tmux session name and + windows, then runs the update, packages, unattended-upgrades, locale, timezone, journald, sysctl, tmpfs, tmux and reboot task files, in that order. - Needs gathered facts, because the reboot check reads C(ansible_os_family). - >- @@ -48,8 +49,10 @@ argument_specs: description: - >- Attach an interactive SSH login to a tmux session, creating it when it does not exist. Installs C(/etc/profile.d/tmux-autostart.sh), - read only by an interactive login shell, so scp, sftp, C(ssh host command) and automation are unaffected. A user opts out with - C(~/.no-tmux). Only the C(ubuntu_lxc) and C(ubuntu_vm) profiles install it; with false, or on C(pve), the file is removed. + which acts only for an interactive login shell with a terminal, so scp, sftp, C(ssh host command) and automation are unaffected. + Shells that do not read C(/etc/profile.d) (zsh, fish) are unaffected too. A user opts out with C(~/.no-tmux). Installed only when + C(tmux) is in the resolved package list (the C(ubuntu_lxc) and C(ubuntu_vm) profiles); with false, or without tmux, the file is + removed. A failed attach leaves a plain shell; detaching ends the SSH connection. system_baseline_tmux_session: type: str default: main @@ -63,7 +66,8 @@ argument_specs: - >- Windows made when the session is created (a login that only re-attaches adds none), next to a plain shell. A window closes when its command exits. The commands come from the inventory and are shell-quoted, but they run as the user who logs in, are readable by - every user on the host and show in C(ps): put no secret in one. + every user on the host and show in C(ps): put no secret in one. They run with C(sh -c) from the tmux server started by the first + login, before C(~/.profile) is read, so use absolute paths for anything outside the default C(PATH). options: name: type: str diff --git a/roles/system_baseline/molecule/default/converge.yml b/roles/system_baseline/molecule/default/converge.yml index 4caf575..771f485 100644 --- a/roles/system_baseline/molecule/default/converge.yml +++ b/roles/system_baseline/molecule/default/converge.yml @@ -49,7 +49,6 @@ that: - "'ufw' not in system_baseline_essential_packages" - "'tmux' not in system_baseline_essential_packages" - - not system_baseline_tmux_autostart - "'unattended-upgrades' in system_baseline_essential_packages" - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00' diff --git a/roles/system_baseline/molecule/default/verify.yml b/roles/system_baseline/molecule/default/verify.yml index 0b2c280..1d1589d 100644 --- a/roles/system_baseline/molecule/default/verify.yml +++ b/roles/system_baseline/molecule/default/verify.yml @@ -127,3 +127,85 @@ ansible.builtin.file: path: /var/run/reboot-required state: absent + + # The snippet must do nothing without a terminal: SSH_CONNECTION is set, stdin is not a tty. It must reach the line after it + # and leave no tmux server behind. + - name: Source the snippet with an SSH connection and no terminal + ansible.builtin.command: + argv: [/bin/sh, -c, '. /etc/profile.d/tmux-autostart.sh; echo reached'] + environment: + SSH_CONNECTION: 192.0.2.1 50000 192.0.2.2 22 + register: system_baseline_verify_snippet + changed_when: false + + - name: It continued to the next line and started no tmux session + ansible.builtin.assert: + that: system_baseline_verify_snippet.stdout == 'reached' + quiet: true + + - name: Ask tmux for sessions + ansible.builtin.command: tmux list-sessions + register: system_baseline_verify_sessions + changed_when: false + failed_when: system_baseline_verify_sessions.rc == 0 + + # The inputs reject a trailing newline (a YAML block scalar adds one): the check anchors with \Z, not $. + - name: Run the validation with a session name that ends in a newline + block: + - name: Include the validation + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: true + system_baseline_tmux_session: "main\n" + - name: Unreachable when validation works + ansible.builtin.fail: + msg: a session name with a trailing newline was accepted + rescue: + - name: The validation refused it + ansible.builtin.assert: + that: "'system_baseline_tmux_session must be' in ansible_failed_result.msg | default('')" + quiet: true + + - name: Run the validation with a window command that ends in a newline + block: + - name: Include the validation + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: true + system_baseline_tmux_windows: + - name: logs + command: "journalctl -f\n" + - name: Unreachable when validation works + ansible.builtin.fail: + msg: a window command with a trailing newline was accepted + rescue: + - name: The validation refused it + ansible.builtin.assert: + that: "'system_baseline_tmux_session must be' in ansible_failed_result.msg | default('')" + quiet: true + + # The removal path runs last, because it deletes the snippet the checks above read. It lives here and not in converge: a + # converge that installs and then removes the file would not be idempotent. + - name: Run the tmux tasks with autostart off + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: tmux + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: false + + - name: Stat the snippet again + ansible.builtin.stat: + path: /etc/profile.d/tmux-autostart.sh + register: system_baseline_verify_removed + + - name: The snippet is gone + ansible.builtin.assert: + that: not system_baseline_verify_removed.stat.exists + quiet: true diff --git a/roles/system_baseline/tasks/tmux.yml b/roles/system_baseline/tasks/tmux.yml index 887dc4a..fde0c8c 100644 --- a/roles/system_baseline/tasks/tmux.yml +++ b/roles/system_baseline/tasks/tmux.yml @@ -1,26 +1,13 @@ --- # Attach an interactive SSH login to a tmux session, created with the configured windows when it does not exist. -# /etc/profile.d is read only by an interactive login shell, so scp, sftp, `ssh host command` and automation never trigger it. +# /etc/profile.d is read by every login shell: the snippet itself acts only for an interactive one with a terminal and an SSH +# connection, so scp, sftp, `ssh host command` and automation never trigger it. # sshd's ForceCommand is deliberately not used: it applies to every session type and a broken tmux would lock out all of them. # -# Security: the session name, window names and commands are role inputs (inventory), never read from a user or a fact. They are -# validated here and shell-quoted in the template. The script is root-owned and not writable by the users it runs for. It is -# world-readable and the commands show in `ps`, so a command must hold no secret. Commands run as the user who logs in. -- name: Check the tmux inputs - ansible.builtin.assert: - that: - - system_baseline_tmux_session is match('^[A-Za-z0-9_-]{1,32}$') - - system_baseline_tmux_windows is sequence and system_baseline_tmux_windows is not string - - system_baseline_tmux_windows | map(attribute='name', default='') | map('regex_search', '^[A-Za-z0-9_-]{1,32}$') | select | list | length - == system_baseline_tmux_windows | length - - system_baseline_tmux_windows | map(attribute='command', default='') | select('match', '^[^\n\r]+$') | list | length - == system_baseline_tmux_windows | length - fail_msg: >- - system_baseline_tmux_session must be 1-32 characters of A-Z a-z 0-9 _ - ; every system_baseline_tmux_windows entry needs - a name (same characters) and a one-line command. - quiet: true - when: system_baseline_tmux_autostart | bool - +# Installed when autostart is on and the resolved package list holds tmux (the ubuntu_lxc and ubuntu_vm profiles); the inputs are +# checked in validate.yml. Security: the session name, window names and commands are role inputs (inventory), never read from a user +# or a fact. They are validated and shell-quoted in the template. The script is root-owned and not writable by the users it runs for. +# It is world-readable and the commands show in `ps`, so a command must hold no secret. Commands run as the user who logs in. - name: Install the tmux auto-start snippet ansible.builtin.template: src: tmux-autostart.sh.j2 @@ -29,14 +16,12 @@ group: root mode: "0644" validate: /bin/sh -n %s - when: - - system_baseline_tmux_autostart | bool - - system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm'] + when: system_baseline_tmux_autostart | bool and 'tmux' in system_baseline_essential_packages become: true - name: Remove the tmux auto-start snippet ansible.builtin.file: path: /etc/profile.d/tmux-autostart.sh state: absent - when: not (system_baseline_tmux_autostart | bool and system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm']) + when: not (system_baseline_tmux_autostart | bool and 'tmux' in system_baseline_essential_packages) become: true diff --git a/roles/system_baseline/tasks/validate.yml b/roles/system_baseline/tasks/validate.yml index e71ebfc..daaf510 100644 --- a/roles/system_baseline/tasks/validate.yml +++ b/roles/system_baseline/tasks/validate.yml @@ -17,3 +17,20 @@ fail_msg: "system_baseline_system_type '{{ system_baseline_system_type }}' is invalid. Must be: ubuntu_vm, ubuntu_lxc, pve." success_msg: "system_baseline_system_type '{{ system_baseline_system_type }}' is valid." tags: always + +# \Z, not $: Python's `$` also matches before a final newline, which a YAML block scalar would add. Not inside a double-quoted +# YAML scalar, where \Z is an invalid escape. The types and required keys are checked by meta/argument_specs.yml. +- name: Validate the tmux session and windows + ansible.builtin.assert: + that: + - system_baseline_tmux_session is match('^[A-Za-z0-9_-]{1,32}\Z') + - system_baseline_tmux_windows | map(attribute='name') | select('match', '^[A-Za-z0-9_-]{1,32}\Z') | list | length + == system_baseline_tmux_windows | length + - system_baseline_tmux_windows | map(attribute='command') | select('match', '^[^\n\r]+\Z') | list | length + == system_baseline_tmux_windows | length + fail_msg: >- + system_baseline_tmux_session must be 1-32 characters of A-Z a-z 0-9 _ - ; every system_baseline_tmux_windows entry needs + a name (same characters) and a one-line command. + quiet: true + when: system_baseline_tmux_autostart | bool + tags: always diff --git a/roles/system_baseline/templates/tmux-autostart.sh.j2 b/roles/system_baseline/templates/tmux-autostart.sh.j2 index 66dd9c0..06250da 100644 --- a/roles/system_baseline/templates/tmux-autostart.sh.j2 +++ b/roles/system_baseline/templates/tmux-autostart.sh.j2 @@ -1,14 +1,22 @@ # Managed by Ansible (mortis.kamino.system_baseline, tasks/tmux.yml). Do not edit: the next run overwrites it. -# Interactive SSH logins only (profile.d is not read by scp, sftp, `ssh host command` or Ansible). +# Interactive login shells with a terminal and an SSH connection only: scp, sftp, `ssh host command` and Ansible have no terminal +# or no interactive shell, and `ssh -t host 'bash -lc cmd'` is a login shell that is not interactive (the case below keeps it out). # Off for one user: touch ~/.no-tmux -if [ -n "$SSH_CONNECTION" ] && [ -z "$TMUX" ] && [ -t 0 ] && [ ! -e "$HOME/.no-tmux" ] && command -v tmux >/dev/null 2>&1; then - # new-session -d fails when the session exists, so the windows below are made only when this login creates it (once, even - # for two logins at the same moment). Windows close when their command exits; window 0 is always a plain shell. - if tmux new-session -d -s {{ system_baseline_tmux_session | quote }} 2>/dev/null; then - : +case $- in + *i*) + if [ -n "$SSH_CONNECTION" ] && [ -z "$TMUX" ] && [ -t 0 ] && [ ! -e "$HOME/.no-tmux" ] && command -v tmux >/dev/null 2>&1; then + # new-session -d fails when the session exists, so the windows below are made only when this login creates it (once, even + # for two logins at the same moment). Windows close when their command exits; window 0 is always a plain shell. + if tmux new-session -d -s {{ system_baseline_tmux_session | quote }} 2>/dev/null; then + : {% for window in system_baseline_tmux_windows %} - tmux new-window -d -t {{ ('=' ~ system_baseline_tmux_session ~ ':') | quote }} -n {{ window.name | quote }} {{ window.command | quote }} + tmux new-window -d -t {{ ('=' ~ system_baseline_tmux_session ~ ':') | quote }} -n {{ window.name | quote }} {{ window.command | quote }} {% endfor %} - fi - exec tmux attach-session -t {{ ('=' ~ system_baseline_tmux_session) | quote }} -fi + fi + # Not exec: a failed attach (for example a client TERM this host has no terminfo for) must leave a usable shell instead of + # closing the connection on every login. A clean detach exits, so detaching ends the SSH connection. + tmux attach-session -t {{ ('=' ~ system_baseline_tmux_session) | quote }} && exit + echo 'tmux-autostart: could not attach to tmux, continuing with a plain shell (touch ~/.no-tmux to stop trying)' >&2 + fi + ;; +esac -- 2.43.0