Setup fail2ban to protect services
mouse 2797 · person cloud · link
Last update
2024-03-13
2024
03-13
«secure apps/server with fail2ban jails
ssh and ssh ddos»

Install fail2ban:

1
apt-get install fail2ban

Configure fail2ban:

Put this file in in /etc/fail2ban/jail.d/local.conf (it is a modified copy of jail.conf):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[DEFAULT]
# space separeted list of IP addresses, CIDR masks, DNS hosts
ignoreip = 127.0.0.1/8 192.168.1.1/24

# number of seconds that a host is banned
bantime  = 3600

# a host is banned if it has generated "maxretry" during the
# last "findtime" seconds
findtime = 600
maxretry = 1

[sshd]
enabled  = true
maxretry = 1
mode     = extra

[sshd-ddos]
enabled  = true
maxretry = 1

Starting, status, unblock IPs:

1
2
3
4
5
6
7
8
9
10
# restart service after any config modification
systemctl restart fail2ban

# show jailing info/counters
fail2ban-client status
fail2ban-client status sshd
fail2ban-client status sshd-ddos

# look suspicious IPs in the logs
journalctl -f -t sshd

Ban management:

1
2
3
4
5
6
# unlock blocked IPs
fail2ban-client unban IP1 IP2 IP3 ...
fail2ban-client unban --all

# block an IP
fail2ban-client -vvv set sshd banip x.x.x.x

SSH tips

You can allow or deny access to specific users by editing /etc/ssh/sshd_config:

1
2
3
4
5
# allow ssh access only to users A and B and disallow all the others
AllowUsers user_a user_b

# deny ssh access only to users A and B and allow all the others
DenyUsers user_a user_b

in this way the SSH demon triggers a faster failure+ban for the disallowed users.


Source: debianizzati, digitalocean, stackoverflow