Cybersecurity

SSH Security Basics

Harden SSH with keys, sensible server settings and host key checks, in an order that will not lock you out of your own machine.

Key takeaways

  • Public key authentication defeats password guessing because there is no password for an attacker to guess.
  • A private key should have a passphrase and should never be copied onto servers or shared between people.
  • Check a server's host key fingerprint the first time you connect, and treat an unexpected change as a warning.
  • Test every server configuration change with a second session open before you close the first.
  • Restricting which addresses can reach SSH matters more than moving it to a different port.

To secure SSH, log in with keys instead of passwords, protect your private key with a passphrase, stop direct root logins, keep the software updated and limit who can reach the port at all. Those five steps remove most of the realistic risk, and none of them takes long.

SSH (Secure Shell) is the standard way to run commands on a remote machine over an encrypted connection. If the basics are new to you, start with SSH explained for beginners. This article assumes you can already connect and want to do it safely. Examples use OpenSSH on Linux and macOS; Windows ships an OpenSSH client too, with some paths that differ.

How an SSH connection protects you

SSH, defined in a family of standards beginning with RFC 4251, does three things in order. It agrees on encryption keys for the session. It proves the server's identity using the server's host key. Then it authenticates you, by password, key or another method, inside the encrypted channel.

The second step is easy to skip past. On your first connection, the client shows the server's key fingerprint and asks whether to trust it. If you answer yes, the key is saved in ~/.ssh/known_hosts and compared on every later visit.

Logging in with an SSH key
Your computer Server Connect and negotiate algorithms 1 Host key and signed key exchange 2 Client checks known_hosts I want to log in with this public key 3 That key is allowed, prove you hold it 4 Signature made with the private key 5 Private key never leaves Signature verified, shell opened 6 Your computer Server Connect and negotiate algorithms 1 Host key and signed key exchange 2 Client checks known_hosts I want to log in with this public key 3 That key is allowed, prove you hold it 4 Signature made with the private key 5 Private key never leaves Signature verified, shell opened 6

Check host keys properly

Get the fingerprint from a trusted source, such as your hosting provider's console or someone with physical access. On the server, this prints it:

ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

Compare it with what your client shows. If you later see a warning that the host identification has changed, stop. The usual cause is innocent, such as a rebuilt server or a reused address, but the same warning is what you would see during a man-in-the-middle attack. Confirm the reason before removing the old entry with ssh-keygen -R server.example.com.

Switch to keys

Generate a key pair on your own computer:

ssh-keygen -t ed25519 -C "alex laptop"

You get a private key (~/.ssh/id_ed25519) and a public key (~/.ssh/id_ed25519.pub). The public key is safe to hand out. The private key is your identity. Choose a passphrase when asked, so a copied file is not immediately usable. Ed25519 is a good modern default; use RSA with at least 3072 bits only if an old system requires RSA.

Install the public key on the server:

ssh-copy-id [email protected]

If ssh-copy-id is not available, append the public key line to ~/.ssh/authorized_keys on the server. That directory should be readable only by you, typically mode 700 for ~/.ssh and 600 for the file.

To avoid retyping the passphrase constantly, load the key into an agent with ssh-add. The agent holds the unlocked key in memory for your session.

Hardware-backed keys

OpenSSH 8.2 and later can use FIDO security keys:

ssh-keygen -t ed25519-sk -C "alex security key"

The file on disk is then useless without the physical device, and by default you must touch it to log in. Both ends need a recent enough OpenSSH. Keep a second key registered in case you lose the first; hardware security keys explains the general idea.

Harden the server settings

The server reads /etc/ssh/sshd_config, and many distributions also include files from /etc/ssh/sshd_config.d/. For most keywords, the first value read wins, so a drop-in file included near the top can silently override what you edit further down.

A reasonable starting point:

PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
AllowUsers alex sam
MaxAuthTries 3
X11Forwarding no
Setting What it does Watch out for
PasswordAuthentication no Refuses password logins Install your key first
KbdInteractiveAuthentication no Closes the other password-like prompt Some one-time code setups need it on; older versions use a different name
PermitRootLogin no Forces login as a normal user, then sudo Make sure that user has sudo rights
AllowUsers Only listed accounts may log in Forgetting your own name locks you out
MaxAuthTries Limits attempts per connection An agent holding many keys can use them up

Apply changes without locking yourself out

A safe order for changing SSH settings
1 Keep one session open Leave a working connection logged in until you are finished. 2 Confirm key login works Open a new connection and verify it does not ask for the account password. 3 Edit and test syntax Run sudo sshd -t, which prints errors and stays silent when the file is valid. 4 Check the effective values Run sudo sshd -T to see what the server will really use. 5 Reload the service The unit is usually called ssh on Debian and Ubuntu, sshd on many others. 6 Test from a new window Only close the original session once a fresh login succeeds. Keep one session open Leave a working connection logged in until you are finished. 1 Confirm key login works Open a new connection and verify it does not ask for the account password. 2 Edit and test syntax Run sudo sshd -t, which prints errors and stays silent when the file is valid. 3 Check the effective values Run sudo sshd -T to see what the server will really use. 4 Reload the service The unit is usually called ssh on Debian and Ubuntu, sshd on many others. 5 Test from a new window Only close the original session once a fresh login succeeds. 6

The reload command looks like sudo systemctl reload ssh or sudo systemctl reload sshd. Some newer systems start SSH through a systemd socket, which can mean port changes are configured elsewhere; check your distribution's documentation. Before touching anything remote, make sure you have another way in, such as a provider's web console.

Control who can reach the port

An SSH server open to the whole internet will log a steady stream of guessing attempts. With password authentication off they will fail, but narrowing access also protects you against a future flaw in the server software.

  • Allow the port only from your office or home address ranges in the firewall, if those are stable.
  • Or put SSH behind a VPN, so it listens only on a private interface. See reaching home through your own VPN.
  • Tools such as fail2ban temporarily block addresses after repeated failures.
  • Changing the port from 22 cuts log noise. It does not hide the service from anyone who scans all ports.

Handle keys and trust with care

One key per person and per device. When a laptop is lost, you remove exactly one line from authorized_keys. Comments such as the -C text above tell you which line.

Review authorized keys regularly. Old contractors and forgotten automation accumulate. Check every account that can log in, including service accounts.

Be careful with agent forwarding. Forwarding your agent (ssh -A) lets the remote machine request signatures from your key while you are connected. An administrator or intruder on that machine can abuse it. To reach a server through an intermediate host, use a jump instead:

ssh -J [email protected] [email protected]

Your authentication stays on your own computer and the intermediate host only relays the encrypted stream.

Restrict automation keys. A line in authorized_keys can start with options such as restrict or command="..." and from="192.0.2.0/24", so a backup key can run only the backup job from the backup server.

Save your good habits in the client config

The client reads ~/.ssh/config, and a few lines there make the safe way the easy way:

Host web1
    HostName server.example.com
    User alex
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes
    ForwardAgent no

Host inside
    HostName 192.0.2.20
    User alex
    ProxyJump [email protected]

Now ssh web1 uses the right account and key, and ssh inside goes through the jump host automatically. IdentitiesOnly yes stops the client from offering every key in your agent to every server, which avoids "too many authentication failures" errors and reveals less about which keys you hold.

On Windows, the file lives in the .ssh folder inside your user profile. If the client complains that a key file's permissions are too open, remove other users' access to it.

SSH is more than a shell

The same connection can copy files (scp, sftp) and forward ports. Forwarding is useful, for example to reach a database that only listens on the server itself:

ssh -L 5432:127.0.0.1:5432 [email protected]

Your local port 5432 now leads to the server's. It also means anyone allowed to log in may be able to tunnel to things your firewall was meant to protect. For accounts that only need to move files or run one job, set AllowTcpForwarding no in a Match block, or restrict the key as described above. For file transfer only accounts, ForceCommand internal-sftp with a restricted directory is a common arrangement, though the directory ownership rules are strict, so test it carefully.

Watch the logs and stay patched

Successful and failed logins are recorded by the system logger, viewable with journalctl -u ssh or -u sshd, or in files such as /var/log/auth.log. Look for successful logins from places or at times you cannot explain. Reading server logs covers the technique.

On a team, send these records to a separate log server so that someone who gains root on one machine cannot quietly erase the history. A simple alert on any successful root login, or any login from outside your expected address ranges, is more useful than a daily pile of failed guesses.

Install updates for OpenSSH and the operating system promptly. Distributions often fix security bugs without changing the main version number, so judge by the package changelog instead of the version banner alone.

If you suspect a private key has leaked, remove its public key from every server first, then generate a new pair. Adding a passphrase to the old file afterward does nothing to the stolen copy. Then check those servers for new keys, accounts or scheduled jobs that you did not create.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Cybersecurity →

Latest news on this topic