Set Up SSH Key Authentication

In progress Linux

Goal

Log in to servers and Git hosts with a key pair instead of a password, with short host aliases, and then turn password logins off.

Prerequisites

  • Password access to each server, one last time.

Steps

  1. Generate a key on your own machine (Ed25519 is short, fast and secure). Add a passphrase: the agent will remember it.
    ssh-keygen -t ed25519 -C "homelab-key"
    
  2. Load it into the agent (on macOS, --apple-use-keychain keeps the passphrase in the Keychain):
    eval "$(ssh-agent -s)"
    ssh-add ~/.ssh/id_ed25519
    
  3. Copy the public key to each server:
    ssh-copy-id user@SERVER_IP
    
  4. For GitHub or GitLab, paste the public key (cat ~/.ssh/id_ed25519.pub, or pbcopy < on macOS) in your profile's SSH Keys settings, then test: ssh -T git@gitlab.com.
  5. Add aliases in ~/.ssh/config:
    Host mynode
        HostName SERVER_IP
        User user
    
  6. Once key logins work, disable password authentication on each server in /etc/ssh/sshd_config.d/no-passwords.conf:
    PasswordAuthentication no
    
    then sudo systemctl reload ssh.

Verify

  • ssh mynode logs in without a password prompt.
  • ssh -o PubkeyAuthentication=no mynode is refused once step 6 is done.

Troubleshooting

  • Still asked for a password: check permissions on the server: ~/.ssh must be 700 and authorized_keys 600.
  • Permission denied (publickey) on Git: ssh -vT git@gitlab.com shows which keys were offered.
  • WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! after reinstalling a server: the new OS has new host keys. Remove the old entry with ssh-keygen -R <ip> (and ssh-keygen -R <hostname> if you also connect by name), then reconnect and check the fingerprint.
  • Ansible hangs or fails on the first connection to a rebuilt node: it is waiting at the host-key prompt. Connect once by hand with ssh user@<ip> and accept the key, then run the playbook.
  • Ansible's --ask-pass errors with sshpass missing: password SSH from Ansible needs sshpass (brew install sshpass on macOS). Or push the key once with ssh-copy-id user@<ip> and drop --ask-pass.

References