Course contents · Lesson 15 of 19

SSH Basics: Log In to Remote Servers Safely

Running Services · Lesson 15 of 19 · 11 min Engineer

Your team has created a cloud server for you and sent an address, 203.0.113.10 in this lesson's examples, and a user name, asha. To install packages or read logs there, you need its command line from your laptop. This lesson covers SSH basics: how the connection works, the first-login question, logging in with a key, and staying safe.

What SSH is

SSH, short for Secure Shell, lets you run commands on another computer over a network. The client, ssh, runs on your laptop; the server, sshd, is a service (lesson 12) on the remote machine, listening on TCP port 22 by default (ports explained). Everything between them is encrypted, scrambled so only the two ends can read it (encryption explained).

SSH relies on key pairs: a private key, a secret file, and a matching public key that is safe to share. What the private key signs, the public key can check. The server's pair, its host key, proves it is the machine you meant; your pair proves you are you.

Step-by-step diagram with two lanes, your laptop running the ssh client and the server web1 running sshd on port 22. Step 1: the laptop connects to TCP port 22, where sshd is listening. Step 2: the server sends its host key, and both sides agree on fresh session keys. Step 3: the laptop checks the host key in known_hosts; if it is new, ssh asks you, and if it has changed, ssh refuses. A band marks everything after step 3 as encrypted. Step 4: the laptop proves it holds the private key, and sshd checks the signature with authorized_keys. Step 5: the session opens and you get a shell, where your commands run on web1
The server proves its identity first; your login already travels encrypted.

In step 2, a key exchange gives both ends the same fresh session key without ever sending it. Notice that step 4 sits inside the encrypted band: your key pair only proves who you are; the session key encrypts.

Your first login and known_hosts

To log in, write the user name and the server's address or DNS name as user@host:

ssh asha@203.0.113.10

ssh has never met this server, so it shows the host key's fingerprint, a short hash of the public host key, and asks whether to trust it. Here the user typed yes (the fingerprint is illustrative):

The authenticity of host '203.0.113.10 (203.0.113.10)' can't be established.
ED25519 key fingerprint is SHA256:Xz3c9VxQe2Lk0eMf1N4bq8p7Ws6dJtYhRaUo5iGvK0E.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '203.0.113.10' (ED25519) to the list of known hosts.
asha@203.0.113.10's password:

Type yes only if the fingerprint matches one the server's owner gave you; on the server, ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub prints it. ssh saves the key in ~/.ssh/known_hosts, then asks for a password if the server allows them; later, exit logs you out.

Next time, ssh compares the key silently. If it ever differs, ssh prints WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! and refuses: the server was rebuilt, or someone sits in the middle. Ask the owner; only if the change is expected, run ssh-keygen -R 203.0.113.10 and reconnect.

Log in with a key instead of a password

Passwords are a weak lock: bots try common ones against port 22 all day, and you hand yours to the server at every login. A key is a long random secret that never leaves your laptop; the server only sees proof.

ssh-keygen makes the pair. Ed25519 is a modern signature method with short keys, and the default type in recent versions:

ssh-keygen -t ed25519

Press Enter to accept the suggested place, the hidden .ssh folder in your home folder:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/asha/.ssh/id_ed25519):

It then asks twice for a passphrase, a password that encrypts the private key file, and prints where it saved id_ed25519, the private key, and id_ed25519.pub, the public key.

Two panels. Your laptop, in the folder ~/.ssh: id_ed25519, the private key, kept secret with mode 600; id_ed25519.pub, the public key, safe to share; and known_hosts, holding web1's public host key. Server web1: /etc/ssh/ssh_host_ed25519_key, the host private key, which stays on web1; ~/.ssh/authorized_keys, holding your .pub line, one key per line; and ssh_host_ed25519_key.pub, the host public key in /etc/ssh. An arrow labelled ssh-copy-id copies your .pub line into authorized_keys. An arrow labelled first login, you typed yes, copies the host public key into known_hosts. A note between the private keys says private keys never travel, and a footer says anyone holding id_ed25519 can log in as you
Each machine keeps its private key; only public halves are copied.

sshd checks keys against ~/.ssh/authorized_keys in the home folder of the user you log in as, one public key per line. ssh-copy-id logs in with your password once and adds your .pub line there:

ssh-copy-id -i ~/.ssh/id_ed25519.pub asha@203.0.113.10

After you type the password one last time, you should see this (trimmed):

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/asha/.ssh/id_ed25519.pub"
asha@203.0.113.10's password:

Number of key(s) added: 1

From now on, ssh asks only for the key's passphrase, if it has one. Where ssh-copy-id is missing, as on Windows, append your .pub line to the server's authorized_keys yourself, for example through the cloud provider's console.

Shortcuts: config, scp and rsync

The file ~/.ssh/config on your laptop gives each server a short name. A Host line starts an entry, and the indented lines below it apply to that name:

Host web1
    HostName 203.0.113.10
    User asha
    IdentityFile ~/.ssh/id_ed25519

Now ssh web1 does the same as the long command; add a Port line if a server does not use 22. scp and rsync use it too. scp copies files, with the remote side written host:path:

scp report.txt web1:/tmp/

It prints one progress line per file (numbers illustrative):

report.txt                                    100%   12KB 410.2KB/s   00:00

Add -r to copy a folder. For folders you update often, rsync -av site/ web1:/srv/site/ sends only what changed: -a recurses and keeps permissions and times, -v lists each file, and -n first shows what would happen. The slash after site/ copies the folder's contents. rsync must be installed on both machines.

Keep keys and servers safe

Anyone who copies id_ed25519 can log in wherever its .pub line is listed. Never email it, paste it into chat or commit it to Git, and give each laptop its own key. A passphrase means a stolen copy is useless without it; ssh-add unlocks the key once, and ssh-agent, a helper program, keeps it ready in memory.

Permissions matter too (lesson 6). If anyone but you can read your private key, ssh prints WARNING: UNPROTECTED PRIVATE KEY FILE! and ignores it. sshd ignores authorized_keys if anyone but you can write to it, to ~/.ssh or to your home folder. These commands set the usual modes:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519        # on your laptop
chmod 600 ~/.ssh/authorized_keys   # on the server

chmod prints nothing when it works; ls -ld ~/.ssh then starts with drwx------.

Lock down the server

Once your key works, turn off root logins (lesson 7) and password logins. On Ubuntu, files in /etc/ssh/sshd_config.d/ override /etc/ssh/sshd_config, so as root, with sudo nano, create /etc/ssh/sshd_config.d/10-hardening.conf containing:

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no

The last line closes keyboard-interactive login, another way to type a password. Check the files, then restart sshd (the unit is sshd on Fedora and Red Hat):

sudo sshd -t
sudo systemctl restart ssh

sshd -t prints nothing if the files are valid. If passwords still work, an earlier file in that folder set the value first, because sshd keeps the first value it reads; sudo sshd -T lists the values it really uses. Keep this session open and test a new login in a second terminal, so a mistake cannot lock you out.

When ssh says Permission denied (publickey)

The most common error is asha@203.0.113.10: Permission denied (publickey). The brackets list the login methods the server still allows. ssh cannot see why your keys failed, so check in this order; ssh -v prints debug lines such as Offering public key: with your key's path.

Flowchart. Start: ssh prints Permission denied (publickey), meaning the server accepted none of your keys. Question 1: is your key offered? Check ssh -v for Offering public key; if not, point ssh at the key with ssh -i or an IdentityFile line. If yes, question 2: is the public key on the server, in ~/.ssh/authorized_keys? If not, add your .pub line with ssh-copy-id or a cloud console. If yes, question 3: are the permissions strict enough, ~/.ssh 700 and its files 600? If not, fix them with chmod, and keep the home folder writable only by you. If yes, question 4: are you the right user, such as ubuntu, ec2-user or your own name? If not, log in as the user whose authorized_keys holds the key. If all four pass and you are still denied, read the server's log with sudo journalctl -u ssh, because sshd logs the real reason while ssh only says denied
ssh only knows it was refused; sshd's log says why.

Cloud images often expect a fixed user, such as ubuntu, or ec2-user on Amazon Linux. If all four pass, sudo journalctl -u ssh on the server (lesson 13) often names the reason after Authentication refused:.

Check yourself

You email your id_ed25519.pub to a colleague, and a stranger reads the email. Can the stranger log in as you?

No. A public key can only check signatures, not make them, and logging in needs a signature from the private key, which never left your laptop.

A server you use daily was rebuilt overnight, and ssh now says REMOTE HOST IDENTIFICATION HAS CHANGED. Why does it refuse, and what do you do?

The new host key does not match known_hosts, which is exactly how an impostor would look. Confirm the new fingerprint with the owner, then run ssh-keygen -R with the host and reconnect.

After you set PasswordAuthentication no, a colleague with no key gets Permission denied (publickey). Is sshd broken?

No, it now accepts only keys, as intended. The colleague makes a key pair, and someone who can log in adds their .pub line to authorized_keys.