Post

Fail2ban: Protecting Your Server from Brute-Force Attacks

I maintain my own physical server and will share methods to prevent brute-force attacks.

Fail2ban: Protecting Your Server from Brute-Force Attacks

You must set a strong password or SSH key when exposing your server to the internet. Many hacking bots attempt to access your server.

1
2
fail2ban v1.1.0
Ubuntu 24.04.2 LTS x86_64

1. Overview

If you maintain your own server, you may be under brute-force attack by bots. As shown in my terminal output, hackers attempt to gain authentication through SSH every second. Records Number of attempts by hackers to access SSH per IP

Setting SSH pubkey is the best option but I sometimes use other computers and other IPs to access remote servers through password authentication. However, since password authentication is weaker than public key authentication, I tried to find a way to enhance SSH security.

There are two main ways to prevent SSH hacking attempts. One is using a Firewall (including Web Application Firewall) and the other is using programs designed to prevent hacking. In this post, I will introduce fail2ban, an intrusion prevention software that you can easily install and set up.

2. Commands

2.1. install

1
2
sudo apt update 
sudo apt install fail2ban

2.2. Run

If the SSH server access fails multiple times, fail2ban will ban the IP address that attempted the access.

1
2
sudo systemctl enable fail2ban # start automatically when boot
sudo systemctl start fail2ban

2.3. Verify banned ips

1
sudo fail2ban-client status sshd

Records Banned Ips by fail2ban

2.4. Modify Conditions

/etc/fail2ban/jail.local If jail.local does not exist, copy jail.conf. fail2ban gives precedence to the setting values in jail.local over those in jail.conf.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[DEFAULT]

ignoreip = 1.2.3.5 1.2.3.4 # Set whitelist IP addresses

...

[sshd]
enabled = true
port = ssh # The port number that SSH service is running on
filter = sshd # The name of the filter to use for SSH service monitoring

# Note: auth.log only saves one day of logs and compresses old logs to .gz files
logpath = /var/log/auth.log 

# If an IP fails 3 times within 6000 seconds, it will be banned for 36000 seconds
maxretry = 3
findtime = 6000 
bantime = 36000 # -1 is forever

You must test a configuration file and fail2ban and after modifying jail.local

1
2
fail2ban-client -t
sudo systemctl restart fail2ban

2.5. Ban in manual

1
sudo fail2ban-client set sshd banip 1.2.3.4

2.6. Unban in manual

1
sudo fail2ban-client set sshd unbanip 1.2.3.4
This post is licensed under CC BY 4.0 by the author.