SSH hardening
Key-based SSH login
-
ssh-keygen -t ed25519 -C "user@laptop"Creates an Ed25519 key pair on your computer, the recommended type and the default in recent OpenSSH versions. When the command asks for a passphrase, it's best to set one: it protects the private key if the file is ever exposed.
-
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@example.comCopies the public key to the user's ~/.ssh/authorized_keys file on the server. This step still logs in with a password, so run it before you disable password login.
-
ssh -o PasswordAuthentication=no deploy@example.comChecks that key login works, with no fallback to a password. Disable password login on the server only after this test succeeds.
-
chmod 700 ~/.sshOn the server: restricts access to the ~/.ssh directory to the user only. When the directory, the file, or the home directory is writable by other users, the SSH server ignores the keys (StrictModes).
-
chmod 600 ~/.ssh/authorized_keysOn the server: restricts reading and writing the authorized keys file to the user only.
-
from="203.0.113.10" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@laptopA line in authorized_keys: the from option at the start of the line allows the key only from the listed addresses, separated by commas. Even if the private key falls into the wrong hands, it can't be used to log in from another address.
-
restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... backup@serverA line in authorized_keys: the restrict option disables all forwarding for the key, such as tunnels and agent forwarding, as well as terminal allocation. A good fit for keys used by backup scripts or automation tools.
-
ssh-keygen -t ed25519-skCreates a key tied to a physical security key (FIDO), so every login also requires touching the device. The security key must be connected to the computer when you create the key, and both the server and the computer you connect from must support this key type.
Disabling passwords and restricting root
-
PasswordAuthentication noCaution: disables password login, so you can log in only with a key. Set it only after key login has been tested, or you will lose access to the server. The OpenSSH default is yes.
-
KbdInteractiveAuthentication noDisables keyboard-interactive authentication, which in some setups still lets you enter a password even when PasswordAuthentication is turned off. On Ubuntu and Debian it is already set to no in the file that ships with the package. In older configuration files it appears under its former name, ChallengeResponseAuthentication.
-
PermitEmptyPasswords noPrevents login for an account with an empty password. This is the default; write it explicitly when you want to make sure no other file has changed it.
-
PermitRootLogin prohibit-passwordLets root log in with a key only, never with a password. This is the OpenSSH default, but the server installation may change it, so check the effective value with sudo sshd -T.
-
PermitRootLogin noCaution: blocks all direct root logins. Before setting it, create a regular user with sudo rights, and check that it logs in with a key and gets admin rights.
-
sudo adduser deploy && sudo usermod -aG sudo deployOn Ubuntu and Debian: creates a regular user and adds it to the sudo group. On RHEL-family distributions, such as AlmaLinux and Rocky Linux, create the user with sudo useradd -m deploy and add it to the wheel group.
-
PubkeyAuthentication yesAllows key login. This is the default; write it only if one of the configuration files sets it otherwise.
Who can log in
-
AllowUsers deploy adminCaution: allows login only for the listed users and blocks every other user, including root. Make sure the user you log in with is on the list.
-
AllowUsers deploy@203.0.113.10The user@host form allows the user to log in only from the given address. Useful when you have a static IP address, such as your office's.
-
sudo groupadd sshusers && sudo usermod -aG sshusers deployCreates a group for the users allowed to log in over SSH and adds a user to it. Run it before you enable AllowGroups.
-
AllowGroups sshusersAllows login only for members of the group. Write the group name, not its number. To give a new user access, add them to the group, with no need to edit the configuration file.
-
DenyUsers guest testBlocks specific users. The checks run in this order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups, so a user listed in DenyUsers is blocked even if they are on the allowed list.
-
Match Address 203.0.113.0/24Opens a conditional block: the settings on the lines that follow, such as PasswordAuthentication yes, apply only to connections from the given network, up to the next Match line or the end of the file. That's why Match blocks go at the end of the sshd_config file.
-
sudo sshd -T -C user=deploy,host=example.com,addr=203.0.113.10 | grep -i passwordauthenticationShows the setting that will apply to a connection with the given user and address, including Match blocks. This is how you test a Match block before you connect.
Example:
passwordauthentication yes
Attempts, timeouts, and idle connections
-
MaxAuthTries 3The maximum number of authentication attempts per connection. The default is 6. A value that is too low can block login when your SSH agent holds several keys, because each key counts as an attempt.
-
LoginGraceTime 30The time in seconds to complete login. If login isn't completed by then, the server drops the connection. The default is 120 seconds.
-
MaxStartups 10:30:100Limits connections that haven't completed login yet. With the default values shown here, above 10 such connections the server rejects 30% of new connections, and the rate rises gradually until every new connection is rejected at 100 such connections.
-
ClientAliveInterval 300Sends a check to a connection that hasn't sent any data for 300 seconds. The default is 0, meaning no checks. A connection that answers the checks stays connected even when it is idle.
-
ClientAliveCountMax 3The number of unanswered checks after which the server drops the connection. The default is 3. Together with ClientAliveInterval 300, a connection that stops responding is dropped after about 15 minutes.
-
MaxSessions 10The number of sessions (terminals, file transfers) you can open within a single SSH connection. The default is 10.
Forwarding and tunnels
-
X11Forwarding noDisables forwarding graphical windows from the server over SSH, which a server without a graphical interface doesn't need. The OpenSSH default is no, but on Ubuntu and Debian the file that ships with the package sets yes.
-
AllowTcpForwarding noBlocks SSH tunnels (port forwarding). Note: a tunnel to a database, or using the server as a jump host (ProxyJump), will stop working. Blocking improves security mainly when users have no command-line access.
-
AllowAgentForwarding noDisables forwarding the SSH agent from your computer to the server. The default is yes. If you don't hop from this server to other servers with the same keys, you don't need this forwarding.
-
DisableForwarding yesDisables all forwarding types at once: X11, the SSH agent, TCP tunnels, and sockets. A good fit in a Match block for users who only transfer files.
sshd_config.d files and setting order
-
/etc/ssh/sshd_config.d/A directory for additional configuration files with the .conf extension. On Ubuntu and Debian, the line Include /etc/ssh/sshd_config.d/*.conf is at the top of the sshd_config file, so settings in the directory take precedence over those in the main file.
-
grep -i '^Include' /etc/ssh/sshd_configChecks whether the main file includes the directory, and where. If there is no Include line, write the settings directly in sshd_config.
Example:
Include /etc/ssh/sshd_config.d/*.conf -
sudo nano /etc/ssh/sshd_config.d/00-hardening.confCreates a separate file for the hardening settings. For each setting, the first value read is the one that applies, and the files in the directory are read in name order. So a name that starts with 00 takes precedence over the other files in the directory, and also over the main file when the Include line is at its top.
-
sudo grep -ri passwordauthentication /etc/ssh/sshd_config /etc/ssh/sshd_config.d/Finds every place where the setting appears. Useful when a file created during the server installation sets a different value from the one you wrote.
Testing and applying the settings
-
sudo sshd -tChecks that the configuration and the host keys are valid, without changing the service. No output means the configuration is valid. Run it before every reload.
-
sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin|kbdinteractive'Shows the settings actually in effect, after all the files are read. This is how you make sure the change was picked up and that no other file overrides it.
Example:
passwordauthentication no -
sudo systemctl reload sshOn Ubuntu and Debian: reloads the configuration, and open connections stay connected.
-
sudo systemctl reload sshdOn RHEL-family distributions, such as AlmaLinux and Rocky Linux: reloads the configuration. On these distributions the service is named sshd.
-
ssh deploy@example.comCaution: run this test in a new terminal window while your existing session is still open. Close the existing session only after login in the new window succeeds, so you can fix a mistake without losing access to the server.
Changing the port
-
Port 2222Caution: changes the port the SSH service listens on. Before reloading, open the new port in the firewall, and on servers with SELinux allow it there too. The change reduces automated login attempts in the logs, but it is not protection on its own.
-
sudo ufw allow 2222/tcpOpens the new port in the UFW firewall. Delete the port 22 rule only after login on the new port succeeds.
-
sudo firewall-cmd --permanent --add-port=2222/tcp && sudo firewall-cmd --reloadOpens the new port in the firewalld firewall and applies the change.
-
sudo semanage port -a -t ssh_port_t -p tcp 2222On servers with SELinux enabled, such as AlmaLinux and Rocky Linux: allows the SSH service to listen on the new port. Without this, the service won't listen on the port.
-
sudo systemctl daemon-reload && sudo systemctl restart ssh.socketOn Ubuntu, when the service is started through ssh.socket: after changing Port or ListenAddress, run both commands so the change takes effect.
-
sudo ss -tlnp | grep sshShows which port and address the SSH service is actually listening on.
-
ssh -p 2222 deploy@example.comConnects to the server on the new port. Run it in a new window while your existing session is still open.
Host keys and algorithms
-
sudo ls -l /etc/ssh/ssh_host_*Lists the server's host keys. The files without the .pub extension are the private keys, and they must be accessible to root only. When others can access them, the SSH service won't start.
-
HostKey /etc/ssh/ssh_host_dsa_keyA line that may remain on older servers. Recent OpenSSH versions no longer support DSA keys, so delete the line and the ssh_host_dsa_key and ssh_host_dsa_key.pub files.
-
sudo ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pubShows the size and fingerprint of the host key, to compare with what is shown on the first connection.
-
sudo ssh-keygen -ACreates any missing host keys of the default types and doesn't touch existing keys. When you replace an existing host key, computers that connected before will show a warning that the key has changed.
-
sudo sshd -T | grep -Ei '^(kexalgorithms|ciphers|macs)'Shows the algorithms the server actually offers. The defaults in recent OpenSSH versions are strong and are updated with every release, so don't write Ciphers, MACs, and KexAlgorithms lists by hand unless you have a specific requirement.
-
ssh -Q kexLists the key exchange algorithms supported by the SSH client on your computer. The ssh -Q cipher and ssh -Q mac commands work the same way.
Two-factor authentication (2FA)
-
sudo apt install libpam-google-authenticatorOn Ubuntu and Debian: installs the module that adds a one-time code from an authenticator app on your phone (TOTP) to the login.
-
google-authenticatorEach user runs this command themselves, scans the QR code with the authenticator app, and keeps the backup codes somewhere safe. Complete this step before you change the SSH settings.
-
auth required pam_google_authenticator.soThe line to add to the /etc/pam.d/sshd file. According to the Ubuntu documentation, it replaces the @include common-auth line, so that after the key, login asks for a code instead of a password.
-
AuthenticationMethods publickey,keyboard-interactiveRequires two steps: first an SSH key, then a one-time code. Along with it, set KbdInteractiveAuthentication yes and PasswordAuthentication no, check with sudo sshd -T that no other file sets KbdInteractiveAuthentication no, and reload while an existing session is open.
Logs and monitoring
-
sudo journalctl -u ssh -fShows the SSH service log in real time, including successful and failed logins. On RHEL-family distributions the service is named sshd.
-
sudo journalctl -u ssh --since today | grep -Ei 'failed|invalid user'Filters today's failed login attempts from the log, including attempts with user names that don't exist on the server.
-
last -a | headShows the most recent logins to the server, with the address each one came from.
No matching settings and commands.
Before hardening SSH on a remote server
- An open session is your safety net: one mistake in sshd_config, in AllowUsers, or in the firewall can cut off your access to the server. So keep your current SSH session open throughout the change, run sudo sshd -t, reload the configuration, and test logging in from a new terminal window. Close the existing session only after the new login succeeds.
- Order of steps: first copy a key and test it, and only then disable passwords. First open the new port in the firewall, and only then change Port. First create a user with sudo, and only then block root.
- Changing the port: moving to another port greatly reduces automated attempts in the logs, but a scan of the server finds the new port too. The real protection comes from key-based login, disabling passwords, and restricting access.
- Algorithms: the defaults in recent OpenSSH versions include modern algorithms, among them key exchange that resists even quantum computers. Regular operating system security updates keep them current, while lists written by hand can become outdated.
To block addresses that keep trying to guess passwords, add fail2ban, and limit access to the port in the firewall with UFW or firewalld. The commands for connecting, keys, and file transfer are on the SSH commands page. The IP addresses on this page, such as 203.0.113.10, belong to a range reserved for documentation, so replace them and the user names with your real values.
On a Linux VPS, you connect over SSH with full root access and harden the server with every setting on this page: key-based login, disabling passwords, restricting users, changing the port, and two-factor authentication.
SSH hardening FAQ
What are the first steps to harden SSH on a new server?
Start by creating an SSH key on your computer and copying it to the server with ssh-copy-id. Once key login has been tested, set PasswordAuthentication no and PermitRootLogin prohibit-password or no, and limit the allowed users with AllowUsers or AllowGroups. Finally, enable fail2ban and limit access to the port in the firewall. When login is key-only, automated password guessing can't succeed.
Does changing the SSH port protect the server?
Changing the port greatly reduces automated login attempts, so the logs are cleaner. The real protection comes from key-based login, disabling passwords, and restricting access, so combine the port change with them, not instead of them. When you change the port, open it in the firewall first, and on servers with SELinux also allow it with semanage.
How do I change SSH settings without locking myself out of the server?
Keep your existing SSH session open throughout the change. After editing, run sudo sshd -t, reload the service, and test logging in from a new terminal window. Close the old session only when the new login succeeds. If something doesn't work, fix the setting from the session that is still open.
Should I block direct root login?
The OpenSSH default, PermitRootLogin prohibit-password, already stops root from logging in with a password and allows a key only. A stricter level is PermitRootLogin no: you log in as a regular user and switch to admin rights with sudo, so every action is logged under the user who ran it. Before blocking root, make sure the regular user logs in with a key and that its sudo rights work.
How do I add two-factor authentication to SSH login?
On Ubuntu and Debian, install the libpam-google-authenticator package, and have each user run google-authenticator and scan the code with an authenticator app. Then add the module to the /etc/pam.d/sshd file and set AuthenticationMethods publickey,keyboard-interactive, so every login requires both a key and a code from the phone. Another option is a physical security key, created with ssh-keygen -t ed25519-sk.