Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 29 ยท Secrets and Security

SSH, Privilege Escalation and Hardening

Secure Ansible access: SSH keys and agents, ansible.cfg connection settings, become and become_user, least privilege, host key checking and a server hardening playbook.

Ansible's power comes from one fact: from a single machine it can log in everywhere and become root. That makes your control node and its SSH keys some of the most sensitive assets you own. This lesson shows how to set up SSH access properly, how privilege escalation (become) works, how to apply least privilege, and how to use Ansible itself to harden servers.

The real examples are read-only because they change SSH and system settings on real hosts. Two JavaScript stand-ins show the logic: one resolves which become settings win, and one models host key checking decisions.

SSH keys and the agent

Ansible connects with plain OpenSSH, so everything you know about SSH applies. Use key pairs, not passwords.

CONSOLE
$ ssh-keygen -t ed25519 -C "ansible control node" -f ~/.ssh/ansible_ed25519
$ ssh-copy-id -i ~/.ssh/ansible_ed25519.pub deploy@web1.example.com
$ eval "$(ssh-agent)"
$ ssh-add ~/.ssh/ansible_ed25519          # type the key's passphrase once

Protect the private key with a passphrase and load it into ssh-agent, so that Ansible (and its many parallel connections) can use it without prompting each time. You can point to a key per host or group in the inventory with ansible_ssh_private_key_file, or globally in the configuration.

Create a dedicated account such as deploy for automation instead of logging in as root. The key you give it should be used only for Ansible.

Connection settings in ansible.cfg

Ansible reads its settings from ansible.cfg (the first file found among the ANSIBLE_CONFIG variable, the current directory, ~/.ansible.cfg and /etc/ansible/ansible.cfg). A project-local file keeps team settings in git:

INI
[defaults]
inventory = inventory/
remote_user = deploy
private_key_file = ~/.ssh/ansible_ed25519
host_key_checking = True
forks = 10

[privilege_escalation]
become = False
become_method = sudo
become_user = root
become_ask_pass = False

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

A few notes:

  • remote_user is who Ansible logs in as; it can be overridden per host with ansible_user and on the command line with -u.
  • host_key_checking should stay on (see below).
  • ControlMaster and ControlPersist reuse one SSH connection for many tasks, which makes runs much faster. They are part of Ansible's default SSH arguments; if you set ssh_args yourself, include them.
  • pipelining = True sends module code over the existing connection instead of copying it to a temporary file first, which saves round trips. It requires that requiretty is not set in the host's sudoers rules, which is the default on modern systems.
  • Setting become = False as the default and enabling it only where needed follows least privilege.

You can check which file is in use and which values are active with ansible --version and ansible-config dump --only-changed.

Privilege escalation with become

Logging in as deploy does not let you install packages or edit /etc. Privilege escalation runs a task as another user, usually root. In Ansible this is the become family of keywords:

Keyword Meaning Default
become turn escalation on false
become_user the user to become root
become_method how to escalate sudo
become_flags extra flags for the method none

Other methods include su, doas, pbrun, runas (Windows) and enable (network devices). You can set the keywords at several levels: the play, a block, a single task, or the configuration. The most specific keyword wins. The matching connection variables (ansible_become, ansible_become_user) set in the inventory are different: they override the keywords. On the command line, -b turns it on and -K (--ask-become-pass) prompts for the password.

YAML
- name: Web server setup
  hosts: web
  become: true                     # every task below runs as root...
  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present

    - name: Write a file owned by the app user
      ansible.builtin.copy:
        content: "ready\n"
        dest: /home/appuser/status.txt
        owner: appuser
      become: true
      become_user: root

    - name: Run a check as the app user only
      ansible.builtin.command: /opt/myapp/bin/self-test
      become_user: appuser          # ...this one runs as appuser instead
      changed_when: false

    - name: A task that needs no privileges
      ansible.builtin.command: id -un
      become: false                 # explicitly off for this task
      changed_when: false

When you become an unprivileged user (not root), Ansible has to share a temporary module file with that user, which can fail unless pipelining is on or the system supports file ACLs. If you meet an error about temporary files, enabling pipelining is the usual fix.

Here is the decision logic in code. It resolves the effective user for each task by checking the most specific setting first.

JS Which user runs the task?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last case: a variable such as ansible_become set in the inventory wins over the become keyword at any level of the playbook, which surprises many people. Among keywords, the closer a setting is to the task, the more it matters. The real rules have a few more sources (command line options, for example), but this order covers the common cases.

Least privilege

Giving every task root is easy and dangerous. Better habits:

  • Escalate only where needed. Turn become on for the tasks that change system state; leave reading and app-level work to normal users.
  • Use a dedicated automation user with a limited sudoers rule when you can. A rule such as deploy ALL=(root) NOPASSWD: /usr/bin/systemctl, /usr/bin/apt-get limits what a stolen key can do, but it is harder to maintain than full sudo, so decide with your threat model.
  • Do not use NOPASSWD: ALL unthinkingly. It is common for automation accounts because there is nobody to type a password, which is exactly why the key must be well protected.
  • Keep the control node small. Fewer people with access, full-disk encryption, no shared accounts.
  • Separate environments. Use different keys, accounts and vault IDs for dev and prod.

Host key checking

The first time SSH connects to a host, it shows the host's key fingerprint, and stores it in known_hosts. On later connections, it compares the stored key with the one presented. A change might mean the server was rebuilt, or that someone is intercepting the connection (a man-in-the-middle attack).

Ansible keeps this protection on by default. Many tutorials suggest host_key_checking = False to avoid the "authenticity of host can't be established" prompt, but that switches the protection off everywhere. Better options for automation:

  • Add expected keys ahead of time: ssh-keyscan -H web1.example.com >> ~/.ssh/known_hosts (verify the fingerprints through another channel, such as your cloud console, the first time).
  • Use ssh_args = -o StrictHostKeyChecking=accept-new for lab or provisioning flows: new hosts are accepted and remembered, but a changed key is still refused.
  • Keep real checking on for production.

The stand-in below compares a host's presented key with the stored ones and decides the outcome under each policy. It models OpenSSH's rules in a simplified way.

JS Host key decisions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that with no, even a changed key is only a warning, which is exactly the situation the check exists to catch. Real OpenSSH also disables some features (password logins, for example) in that case, but you should treat no as unsafe anyway.

Hardening with Ansible

Ansible is excellent at applying a security baseline consistently, and at proving it with --check. Here are typical building blocks. They illustrate ideas; adapt them to your distribution and test them on a disposable machine first, because a mistake in SSH or firewall settings can lock you out.

YAML
- name: Baseline hardening
  hosts: all
  become: true
  tasks:
    - name: Disable root login and password authentication
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        validate: "/usr/sbin/sshd -t -f %s"
      loop:
        - { regexp: '^#?PermitRootLogin\s', line: "PermitRootLogin no" }
        - { regexp: '^#?PasswordAuthentication\s', line: "PasswordAuthentication no" }
      notify: Reload sshd

    - name: Allow only SSH and HTTPS through the firewall (Debian/Ubuntu)
      community.general.ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop: ["22", "443"]
      when: ansible_facts['os_family'] == 'Debian'

    - name: Turn the firewall on with a default deny policy
      community.general.ufw:
        state: enabled
        policy: deny
      when: ansible_facts['os_family'] == 'Debian'

    - name: Install unattended security upgrades
      ansible.builtin.apt:
        name: unattended-upgrades
        state: present
      when: ansible_facts['os_family'] == 'Debian'

    - name: Restrict a sensitive file
      ansible.builtin.file:
        path: /etc/shadow
        owner: root
        mode: "0640"

  handlers:
    - name: Reload sshd
      ansible.builtin.service:
        name: ssh        # the unit is called sshd on RHEL-family systems
        state: reloaded

Remember the order for the SSH and firewall tasks: allow SSH before enabling a deny-by-default firewall, and use validate so a broken sshd_config is never installed. Keep a second session open the first time you test changes like these. Run the play with --check --diff first to preview them (see Testing, Linting and Debugging). The lines you manage with lineinfile are covered in Files, Users and Packages, and the full reusable role comes in Project: Security Baseline Role.

flowchart TD
  K["Control node<br/>protected private key + agent"] -- "ssh as deploy" --> H["Managed host"]
  H --> Q{"Task needs<br/>root?"}
  Q -- yes --> S["become: sudo to root"]
  Q -- no --> U["Run as deploy<br/>or become_user appuser"]
  S --> L["Least privilege:<br/>escalate per task, not per play"]

Log in as a limited user, and escalate only for tasks that need it.

What is real and what is the stand-in

The ssh-keygen, ansible.cfg and playbook examples are real, read-only code. The two JavaScript programs are simplified models of the decisions Ansible and OpenSSH make; they do not read your configuration or any known_hosts file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A play sets become: true, and one task sets become: false. How does that task run?

    Settings closer to the task override broader ones. The task runs as the user Ansible logged in as.
  2. 2. Why is setting host_key_checking = False everywhere a bad idea?

    Host key checking is what lets SSH notice a changed or fake server. Use ssh-keyscan or StrictHostKeyChecking=accept-new instead of switching it off.
  3. 3. What does ssh-agent give you when running Ansible?

    You type the passphrase once with ssh-add, and the agent signs for each new connection Ansible opens.
  4. 4. Which approach best follows least privilege?

    Limit who and what can escalate. A leaked key or a mistaken task then has a smaller blast radius.

Summary

  • Use SSH keys with passphrases and ssh-agent, and a dedicated automation account instead of root.
  • ansible.cfg holds connection and escalation defaults; pipelining and ControlPersist speed up runs.
  • become, become_user and become_method can be set at several levels; the most specific keyword wins, but inventory variables such as ansible_become override keywords.
  • Escalate per task rather than per play, and avoid broad passwordless sudo when you can.
  • Keep host key checking on; pre-seed known_hosts or use accept-new for provisioning.
  • Harden with Ansible using validate, careful ordering (allow SSH before a deny-all firewall) and --check --diff.

Next: Testing, Linting and Debugging.