Contents
- What an SSH attack means and what actually protects the server
- Prepare the way back first
- Go to the key and verify sudo as well
- Disable unnecessary authentication methods and verify the resulting configuration
- Limit network reach if management allows it
- Add Fail2ban as an additional layer
- How do you know the outcome and when to address the incident?
- Frequently asked questions
What an SSH attack means and what actually protects the server
A public SSH server will usually start logging login attempts as root, admin, or test soon. The number of denied attempts alone does not prove a breach. What matters is whether there is a viable way to log in: a weak password, a leaked private key, an insecure account, or an outdated service error. So, divide your protection into user authentication, network availability, and limiting failed connections.
Brute-force tries many combinations in succession; password spraying tries a smaller number of passwords on many accounts. An attacker can switch source addresses, so blocking a single IP is not a complete defense. Strong authentication protects an account even if an SSH request is made. A firewall, on the other hand, reduces the number of people and bots who can even initiate the authentication process.
The following procedure is intended for the administrator of your own Linux server with OpenSSH. The service examples correspond to Ubuntu and Debian with systemd. On other distributions, the unit names, logging backend and firewall management may differ. This is not a recommendation to change all servers in the same way: first determine whether you need access from the Internet, only via VPN, or from a permanent management network.
Prepare the way back first
Before changing the authentication, open the provider's or hypervisor's console and make sure that you can log in through it. Leave the current SSH session open. Prepare a second terminal next to it, in which you will perform a new login after each change. An already established session does not confirm that the server would accept a new connection under the new rules.
sudo systemctl status ssh.service --no-pager
sudo systemctl status ssh.socket --no-pager
sudo /usr/sbin/sshd -t
sudo ss -lntp
sudo journalctl -u ssh.service --since "-30 min" --no-pagerOn systems using sshd.service, substitute the name of the service. The ssh.socket unit may not exist; its absence is not an error in itself. Note the current port, network addresses, and activation method. Back up the specific file being edited, including its permissions, to the administrator's private directory. When restoring, revert your change, not the entire SSH directory, overriding any later changes by another administrator.
The commands in the article are examples for your server. Do not make any authentication, firewall, or blocking changes without a working alternate access. Replace the placeholder names and addresses with your own.
Go to the key and verify sudo as well
First, enable regular administrator account login using the public key. The private key belongs to the client and its backup, the public part to the authorized_keys server account. Do not upload the private part to a web form, log, or server as a way to install the public key. Protect the key with a strong passphrase; consider a hardware key and a spare depending on your usage.
ssh -o IdentitiesOnly=yes -o PreferredAuthentications=publickey \
-o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
-i ~/.ssh/id_ed25519 spravce@server.example
# Po přihlášení na serveru:
whoami
sudo -vTest with the key you actually want to use. Success with a different key loaded in the agent could create a false sense of security; IdentitiesOnly helps narrow the selection. Verify the server key fingerprint with a trusted, independent method. If sudo requires an account password, disabling passwordless SSH logins does not automatically remove that password. So verify both parts of the access separately.
You can use CH-J Tools to open a terminal and a second connection that will verify the new key. However, the security policy is enforced by the server. Do not consider connecting from a graphical application as evidence that every password method is disabled; the client could have successfully used the key while the server still accepts passwords.
Disable unnecessary authentication methods and verify the resulting configuration
If you have proven key access and do not need keyboard authentication, the target policy might be as follows. Put the contents in a file that your installation actually loads. On Ubuntu, Include for sshd_config.d is usually active; verify its existence and order. Simply creating a file with a higher number does not guarantee that its values will override previous settings.
# Příklad politiky pro správu klíčem, nikoli pro účty s PAM/TOTP:
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin noKbdInteractiveAuthentication can mediate multifactor authentication via PAM. If you use it, do not disable it as in this example; design appropriate AuthenticationMethods and validate the entire login sequence. Similarly, disable direct root login only after authenticating an alternate administrator. Do not remove PAM or system account restrictions just because you do not use passwords in SSH.
sudo /usr/sbin/sshd -t
sudo /usr/sbin/sshd -T -C user=spravce,addr=203.0.113.10,host=klient.example \
| grep -E "^(pubkeyauthentication|passwordauthentication|kbdinteractiveauthentication|permitrootlogin|authenticationmethods) "The address 203.0.113.10 is a documentation example: use the actual source address that the server sees in your test. Add additional context values if your Match blocks depend on them. The syntax check does not verify the existence of the correct public key or actual network availability. Therefore, compare the results with the intended policy before reloading the configuration.
sudo systemctl reload ssh.service
# V druhém terminálu na klientovi zopakujte přihlášení klíčem.On a server with sshd.service, use its name. After a successful test, check the journal. If the new login fails, revert the specific change via a still-open session or console and retest the syntax. Do not proceed with additional layers of protection until you understand the result of this change.
Limit network reach if management allows it
The smallest attack surface is when only a VPN or known management network can access the management port. Such restrictions must be consistent with real-world traffic: a laptop on mobile data may get a different address, and a connection through a bastion may appear on the target under the bastion address. Also, determine if the server has public IPv6. Restricting IPv4 only does not provide the same protection over IPv6.
# Pouze příklad přidání povolené IPv4 adresy do již spravovaného UFW:
sudo ufw allow from 203.0.113.10 to any port 22 proto tcp
sudo ufw status numberedThe new narrower permission does not override the old rule that allows the port from anywhere. Review the complete rules and only remove the specific redundant broad permission after a new login. This procedure cannot be blindly used to transition a previously disabled UFW to an active state: you would have to prepare rules for all necessary services at the same time. Do not flush existing nftables rules and do not combine several firewall managers without knowing the connections.
Changing the port can reduce the amount of normal scanning and noise in the log. It does not replace key authentication, updates, or access control. If the new port is public, it can be discovered. Additionally, on socket-enabled systems, simply changing the Port in sshd_config may not match the socket currently listening.
Add Fail2ban as an additional layer
Fail2ban reads failed authentication events and temporarily blocks the source according to the rules. Use the distribution package and check its version and default configuration. Do not edit the package configuration files directly; put your own jail in a .local file under jail.d. For an installation that sends SSH events to the journal, it might look something like this:
# /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
backend = systemd
port = 22
findtime = 10m
maxretry = 5
bantime = 1hThis is a default example to customize. The port must match the actual SSH port and the distribution filters must recognize your events. For the systemd backend, do not blindly add the logpath from the file log manual. Verify the availability of the appropriate backend and the blocking action, especially if you are using IPv6 or a custom firewall. Five failures in ten minutes with an hourly ban is not a universal safe limit for every organization.
sudo fail2ban-client -t
# Po úspěšném testu načtěte změnu podle stavu služby:
sudo systemctl restart fail2ban.service
sudo fail2ban-client status sshd
sudo journalctl -u fail2ban.service -n 50 --no-pagerOn a shared public address, a single user's mistake can get multiple administrators banned. Only give ignoreip exceptions to trusted addresses that really need protection from unwanted bans. An administrator must not accidentally disable the filter for the entire internet. Distributed slow attacks can remain below the filter threshold; therefore, Fail2ban does not deal with weak passwords or compromised keys.
# Příklad odstranění konkrétního chybného banu přes náhradní přístup:
sudo fail2ban-client set sshd unbanip 203.0.113.10How do you know the outcome and when to address the incident?
Compare the same time periods before and after the change. Monitor failed authentications, rejected new sessions, number of bans and, most importantly, successful logins. A decrease in the number of records can indicate an effective firewall, but also a malfunctioning log collection. Silent journaling alone is not proof of security. For restricted access, verify that legitimate logins from the allowed network continue to occur and are traceable.
- The new administrator logs in with the specified key and can use the required sudo.
- The resulting policy for the relevant account and resource does not allow unwanted password authentication.
- Both IPv4 and IPv6 have the same intended availability and security goals.
- Fail2ban actually reads events and uses a working blocking action.
- There is a tried and tested alternative approach and a recorded return procedure.
If you find a successful login that does not match an approved administrator or automation, do not consider installing Fail2ban to resolve the situation. Preserve timestamps and available evidence, verify the scope of access, and address the account or machine compromise. Simply deleting the log or changing the port will not remove foreign authorized_keys, altered service, or stolen credentials.
Frequently asked questions
Will key login stop all attacks?
It removes password guessing as a login path if other methods are truly disabled. It does not protect against a stolen key, service failure, or a compromised admin computer.
Is Fail2ban necessary even without passwords?
It can reduce noise and some retries. Its benefit depends on port availability and traffic; it is not a substitute for updates and access restrictions.
Why doesn't PasswordAuthentication work?
The effective value can be determined by a previously loaded configuration or a Match block. Keyboard authentication is a separate method and can offer a password via PAM.
Can I make changes only via SSH?
Technically yes, but to change authentication and firewall, first authenticate to the console or other independent access and leave the original session open.
Detailed documentation
OpenSSH: server configuration and authentication →
Fail2ban: reference jail configuration →