authorized_keys and ssh-copy-id

SSH · Essentials · 8 min

This is how key-based login is actually switched on for an account, and permission mistakes here are the top cause of failures.

On the server, each account lists the public keys allowed to log in as it in ~/.ssh/authorized_keys, one key per line.

The easy way to add yours is ssh-copy-id, which logs in (with your password, the last time you will need it) and appends the key:

ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@server

Doing it by hand works too: append the contents of the .pub file to ~/.ssh/authorized_keys on the server.

Permissions matter because sshd (with the default StrictModes yes) ignores the file if others could have tampered with it:

  • ~/.ssh must be 700, authorized_keys should be 600, and the home directory must not be group- or world-writable.
  • The files must be owned by the account.

When key login fails and falls back to asking for a password, run ssh -v on the client (look for "Offering public key" and the server's reply) and check the server log (journalctl -u ssh or /var/log/auth.log), which says exactly why a key was refused.

Each line can carry options before the key to limit it, for example from="10.0.0.0/8" or command="/usr/local/bin/backup",restrict for a key that may only run a backup.

Example

ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@server   # asks for the password once
ssh alice@server                                     # now logs in with the key

# manual alternative, on the server:
mkdir -p ~/.ssh && chmod 700 ~/.ssh
echo 'ssh-ed25519 AAAAC3Nz... alice@laptop' >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

# a restricted key: may only run the backup script, only from one network
# from="10.0.0.0/8",command="/usr/local/bin/backup",restrict ssh-ed25519 AAAA... backup

Remember

  • ~/.ssh/authorized_keys lists keys allowed for that account
  • ssh-copy-id installs your key; ~/.ssh 700, authorized_keys 600
  • Server logs explain refused keys; ssh -v shows what was offered

Watch out for

  • A group-writable home or .ssh directory: sshd silently ignores the keys and asks for a password.

Check yourself

  1. Key login keeps falling back to a password prompt. Which is a likely cause?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man.openbsd.org/sshd#AUTHORIZED_KEYS_FILE_FORMAT