Sub topic 2
Protecting your private key with a passphrase
Assumptions: You use a Linux or macOS terminal, you can log in to a server with a password, and you are comfortable with Unix file permissions and a text editor such as nano or vim.
Protecting the private key with a passphrase
A passphrase is a password that encrypts your private key file. ssh-keygen asks for one when it creates the key pair. Without a passphrase, anyone who copies the file can log in as you. With one, the copied file is useless without the passphrase.
ssh-keygen -t ed25519 -C "alice@laptop" -f ~/.ssh/id_ed25519Enter a strong passphrase at the prompt. You will type it each time you use the key unless you cache it with ssh-agent, which the next part of the tutorial covers.
::: callout warning A lost passphrase cannot be recovered. You must generate a new key pair and install the new public key on every server. :::
Getting file permissions right
ssh and sshd refuse keys when other users can read or write the files. Set these modes:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 600 ~/.ssh/authorized_keys| Path | Mode | Reason |
|---|---|---|
| `~/.ssh` | 700 | Only the owner can list or enter the directory. |
| `~/.ssh/id_ed25519` | 600 | Only the owner can read the private key. |
| `~/.ssh/authorized_keys` | 600 | Only the owner can change the list of accepted keys. |
Installing the public key on the server
The public key is the file ending in .pub. It is safe to share. Use ssh-copy-id to log in once with your password and append the key to authorized_keys:
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]If ssh-copy-id is unavailable, run this command instead. The umask 077 setting makes any new directory or file private to your user:
cat ~/.ssh/id_ed25519.pub | ssh [email protected] 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys'Logging in and verifying the host
Connect with:
ssh [email protected]On the first connection, ssh shows the server's host key fingerprint and asks you to confirm it. Check that the fingerprint matches the one on the server. Run this on the server:
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubType yes only if the fingerprints match. ssh saves the host key in ~/.ssh/known_hosts. If you later see REMOTE HOST IDENTIFICATION HAS CHANGED, the server key differs from the saved one. Investigate before you connect again.
After the host check, ssh asks for your key passphrase. Entering it completes the login.
Exercise
Why does ssh refuse a private key that other users can read?
Show answer
A private key that others can read lets them impersonate you. ssh checks the permissions and refuses the key when group or other users have access.