Fail2ban watches the server's login log. If someone tries to guess a password from one IP address too often, it blocks that address for a while.
Even if you already log in with SSH keys, fail2ban is useful. It cuts off bots, keeps the logs cleaner and helps you notice sooner if something unusual is going on.
1. Install fail2ban
The commands are run on the server.
# Refresh the package list and install fail2ban.
# python3-systemd lets fail2ban read the system journal
sudo apt update
sudo apt install -y fail2ban python3-systemd# fail2ban lives in the extra EPEL repository, so enable it
sudo dnf install -y epel-release
# Install fail2ban
sudo dnf install -y fail2ban2. Create a settings file
The main fail2ban settings file is overwritten during updates, so your own settings go into a separate jail.local file.
# Create your own settings file and open it in the editor
sudo nano /etc/fail2ban/jail.localPaste these settings into it.
[sshd]
# Turn on SSH protection
enabled = true
# SSH port. If you have changed it, put your own number, for
# example 2222
port = ssh
# Read the login log through systemd. This way fail2ban also works
# where there is no /var/log/auth.log file, for example in Debian 12
backend = systemd
# How many failed login attempts are allowed
maxretry = 5
# The time window in which the attempts are counted
findtime = 10m
# How long to block the offender's IP address
bantime = 1hTo save the file, press Ctrl + O and Enter, and to exit the editor, press Ctrl + X.
3. Start fail2ban
# Make fail2ban start automatically and start it right away
sudo systemctl enable --now fail2ban
# Restart it to make sure it picks up our settings file
sudo systemctl restart fail2ban
# Check the state of SSH protection
sudo fail2ban-client status sshdIn the output you will see two main lines.
Total failed shows how many failed login attempts there have been.
Banned IP list shows which addresses are blocked right now.
If the server has been on the internet for a while, the first “guests” will almost certainly show up in the list.
Useful commands
# View the blocked addresses
sudo fail2ban-client status sshd
# Unblock an address, for example if you mistyped the password
# yourself. Replace IP_ADDRESS with the address you need
sudo fail2ban-client set sshd unbanip IP_ADDRESS
# Restart fail2ban after changing the settings
sudo systemctl restart fail2banIf you have blocked yourself
If fail2ban has blocked your own address, connect from a different internet connection, for example mobile data, or open the server with the Console button in the server list in your client area. Then unblock your address with the command above. In any case, the block will lift on its own after an hour.
For the 3X-UI panel
3X-UI has its own built-in fail2ban setting, which is described in the article on setting up VLESS + TLS + XHTTP.
Our resources
Telegram channel: https://t.me/f3cloud_news
F3 Cloud: https://f3cloud.com