当前位置:网站首页>Protect your system with fail2ban and firewalld blacklists

Protect your system with fail2ban and firewalld blacklists

2022-06-24 03:45:00 User 8639654

If you are running a server that has a public facing SSH visit , You may have encountered malicious login attempts . This article describes how to use two utilities to prevent intruders from entering our system .

To prevent repeated ssh Login attempts , Let's see fail2ban. and , If you don't travel often , Basically stay in oneortwo countries , You can take FirewallD Configured to allow only Visit from the country of your choice .

First , Let's introduce some terminology to those unfamiliar with these applications , To complete the work :

fail2ban: A daemon , It is used to prohibit hosts with multiple authentication errors .fail2ban Will monitor SystemD journal , To find any enabled “ prison (jail)” Failed verification attempts for . After the specified number of failures , It will add a firewall rule , Block the specific for the configured time IP Address .

FirewallD: With a D-Bus Interface firewall daemon , Provide dynamic firewall . Unless you decide otherwise to use traditional iptables, Otherwise you're already in support of all Fedora and CentOS Installed on FirewallD.

Suppose the premises

  • The host system has an Internet connection , And either it is directly exposed to the Internet , Either through DMZ( Both of these are very bad ideas , Unless you know what you're doing ), Or there is a port forwarding from the router .
  • Although most of the content may be applicable to other systems , But this paper assumes that the current system is Fedora(31 And above ) or RHEL/CentOS 8 edition . stay CentOS On , You have to use sudo dnf install epel-release Enable Fedora EPEL Warehouse .

Installation and configuration

Fail2Ban

It is quite possible that there is already some Firewalld The zone has allowed SSH visit , but sshd The service itself is not enabled by default . To start it manually , And does not permanently enable it at startup :

$ sudo systemctl start sshd

Or enable... When the system starts , And start it at the same time :

$ sudo systemctl enable --now sshd

The next step is to install 、 To configure 、 Enable fail2ban. As usual , Installation can be done from the command line :

$ sudo dnf install fail2ban

After installation , The next step is to configure “ prison ”( Services you want to monitor and disable at any threshold you set ). By default ,IP Will be banned 1 Hours ( This is not long enough ). The best way is to use *.local File overwrite system defaults , Instead of directly modifying *.config file . If we look at my jail.local, We can see :

# cat /etc/fail2ban/jail.local
[DEFAULT]

# "bantime" is the number of seconds that a host is banned.
bantime  = 1d

# A host is banned if it has generated "maxretry" during the last "findtime"
findtime  = 1h

# "maxretry" is the number of failures before a host get banned.
maxretry = 5

Speak in popular language , Is to try in the last hour 5 Next time , The IP Will be banned 1 God . For many times sealed IP, You can also choose to increase the blocking time , But this is the subject of another article .

The next step is to configure “ prison ”. Shown in this tutorial is sshd, But the steps for other services are roughly the same . stay /etc/fail2ban/jail.d Create a configuration file in . This is my file :

# cat /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true

It's that simple ! Many configurations are already in progress for Fedora The built package deals with ( Tips : I am the current maintainer ). Next, enable and start fail2ban service :

$ sudo systemctl enable --now fail2ban

I hope there is no immediate error , without , Please use the following command to check fail2ban The state of :

$ sudo systemctl status fail2ban

If it doesn't start up incorrectly , It should be :

$ systemctl status fail2ban
● fail2ban.service - Fail2Ban Service
Loaded: loaded (/usr/lib/systemd/system/fail2ban.service; disabled; vendor preset: disabled)
Active: active (running) since Tue 2020-06-16 07:57:40 CDT; 5s ago
Docs: man:fail2ban(1)
Process: 11230 ExecStartPre=/bin/mkdir -p /run/fail2ban (code=exited, status=0/SUCCESS)
Main PID: 11235 (f2b/server)
Tasks: 5 (limit: 4630)
Memory: 12.7M
CPU: 109ms
CGroup: /system.slice/fail2ban.service
└─11235 /usr/bin/python3 -s /usr/bin/fail2ban-server -xf start
Jun 16 07:57:40 localhost.localdomain systemd[1]: Starting Fail2Ban Service…
Jun 16 07:57:40 localhost.localdomain systemd[1]: Started Fail2Ban Service.
Jun 16 07:57:41 localhost.localdomain fail2ban-server[11235]: Server ready

If it is just started ,fail2ban It is unlikely to display any interesting information , But check fail2ban The state of , And ensure “ prison ” Be enabled , Please enter :

$ sudo fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd

sshd “ prison ” The parent status of the will also be displayed . If more than one is enabled “ prison ”, They will show up here .

To check out a “ prison ” Detailed state , Just add... To the previous command “ prison ” name . Here is the output of my system , It has been running for some time . I have removed the forbidden from the output IP:

$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 8
|  |- Total failed:     4399
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 101
   |- Total banned:     684
   `- Banned IP list:   ...

monitor fail2ban Whether the log file has any intrusion attempts , Can pass “ Follow ” Log to achieve :

$ sudo tail -f /var/log/fail2ban.log

tail Is a good command line tool , By default , It can display the last... Of a file 10 That's ok . add to -f Tell it to follow the file , This is a good way to observe a file that is still being written .

Because the output content contains real IP, So no samples will be provided here , But it is highly readable .INFO Line is usually an attempt to log in . If from a particular IP Address has made enough attempts , You'll see one NOTICE The line shows a IP The address is forbidden . After the prohibition time is reached , You'll see one NOTICE Lifting the ban .

Notice a few warning lines . The most common situation is , When a prohibition is added ,fail2ban Find out what to do IP The address is already in its forbidden database , This means that prohibition may not work properly . If it is recently installed fail2ban package , It should be set to FirewallD The rich rules of . This bag is in fail2ban-0.11.1-6 Version from ipset Mode switches to rich rule mode , So if your fail2ban Installed earlier , It may still be trying to use ipset The way , This method uses the traditional iptables, Not very reliable .

FirewallD To configure

Passive or active ?

There are two strategies that can be used separately or together : passive Place a single IP Address or Take the initiative The place will permanently blacklist the subnet according to the country of origin .

For the passive way , once fail2ban Running for a while , It is better to run again sudo fail2ban-client status sshd Let's see who the bad guys are . There are likely to be many banned IP Address . Select a , Then try to run it whois. There may be a lot of interesting information in the output , But for this method , Only the country of origin is important . To keep it simple , Let's filter out all the information except the country .

In this case , We will use some famous domain names :

$ whois google.com | grep -i country
Registrant Country: US
Admin Country: US
Tech Country: US
$ whois rpmfusion.org | grep -i country
Registrant Country: FR
$ whois aliexpress.com | grep -i country
Registrant Country: CN

Use grep -i The reason is to make grep Case insensitive , And most of the entries use “Country”, Some entries are all lowercase “country”, So this method can match anyway .

Now we know the country of origin of the attempted invasion , The problem is ,“ Is there anyone from this country who has a legitimate reason to connect to this computer ?” If the answer is no , Then it should be acceptable to blockade the whole country .

functionally , The active method is not very different from the passive method , However , Attempts to invade from some countries are very common . If your system is not in these countries , There are no customers from these countries , So why not add them to the blacklist now and wait ?(LCTT Translation notes : My experience is that , It is too arbitrary to be included in the blacklist by the category of countries . It is suggested that this IP Of WHOIS Put the network segment into the blacklist , Because these network segments often have the same usage properties , For example, both are used for user access or IDC trusteeship , The security situation is also roughly the same , therefore , If there is a... From this network segment IP A malicious attempt , You can expect others in this segment IP It may also be used to make such an attempt .)

Blacklist scripts and configurations

So how to do this ? use FirewallD ipset. I developed the following script to automate this process as much as possible :

#!/bin/bash
# Based on the below article
# https://www.linode.com/community/questions/11143/top-tip-firewalld-and-ipset-country-blacklist

# Source the blacklisted countries from the configuration file
. /etc/blacklist-by-country

# Create a temporary working directory
ipdeny_tmp_dir=$(mktemp -d -t blacklist-XXXXXXXXXX)
pushd $ipdeny_tmp_dir

# Download the latest network addresses by country file
curl -LO http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gz
tar xf all-zones.tar.gz

# For updates, remove the ipset blacklist and recreate
if firewall-cmd -q --zone=drop --query-source=ipset:blacklist; then
    firewall-cmd -q --permanent --delete-ipset=blacklist
fi

# Create the ipset blacklist which accepts both IP addresses and networks
firewall-cmd -q --permanent --new-ipset=blacklist --type=hash:net \
    --option=family=inet --option=hashsize=4096 --option=maxelem=200000 \
    --set-description="An ipset list of networks or ips to be dropped."

# Add the address ranges by country per ipdeny.com to the blacklist
for country in $countries; do
    firewall-cmd -q --permanent --ipset=blacklist \
        --add-entries-from-file=./$country.zone && \
        echo "Added $country to blacklist ipset."
done

# Block individual IPs if the configuration file exists and is not empty
if [ -s "/etc/blacklist-by-ip" ]; then
    echo "Adding IPs blacklists."
    firewall-cmd -q --permanent --ipset=blacklist \
        --add-entries-from-file=/etc/blacklist-by-ip && \
        echo "Added IPs to blacklist ipset."
fi

# Add the blacklist ipset to the drop zone if not already setup
if firewall-cmd -q --zone=drop --query-source=ipset:blacklist; then
    echo "Blacklist already in firewalld drop zone."
else
    echo "Adding ipset blacklist to firewalld drop zone."
    firewall-cmd --permanent --zone=drop --add-source=ipset:blacklist
fi

firewall-cmd -q --reload

popd
rm -rf $ipdeny_tmp_dir

This should be installed to /usr/local/sbin, Don't forget to make it executable !

$ sudo chmod +x /usr/local/sbin/firewalld-blacklist

Then create a profile /etc/blacklist-by-country

# Which countries should be blocked?
# Use the two letter designation separated by a space.
countries=""

And another configuration file /etc/blacklist-by-ip, There is only one... Per line IP, No extra formatting .

In this case , from ipdeny Selected at random from the zone file of 10 A country :

# ls | shuf -n 10 | sed "s/\.zone//g" | tr '\n' ' '
nl ee ie pk is sv na om gp bn

Now just add at least one country to the configuration file , It's ready to run !

$ sudo firewalld-blacklist
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   142  100   142    0     0   1014      0 --:--:-- --:--:-- --:--:--  1014
100  662k  100  662k    0     0   989k      0 --:--:-- --:--:-- --:--:--  989k
Added nl to blacklist ipset.
Added ee to blacklist ipset.
Added ie to blacklist ipset.
Added pk to blacklist ipset.
Added is to blacklist ipset.
Added sv to blacklist ipset.
Added na to blacklist ipset.
Added om to blacklist ipset.
Added gp to blacklist ipset.
Added bn to blacklist ipset.
Adding ipset blacklist to firewalld drop zone.
success

To verify FirewallD Whether the blacklist is successful , Please check drop Area and blacklist ipset.

$ sudo firewall-cmd --info-zone=drop
drop (active)
  target: DROP
  icmp-block-inversion: no
  interfaces:
  sources: ipset:blacklist
  services:
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

$ sudo firewall-cmd --info-ipset=blacklist | less
blacklist
  type: hash:net
  options: family=inet hashsize=4096 maxelem=200000
  entries:

The second command will output all subnets , These subnets are added based on the blocked countries , It could be quite long .

So what should I do now ?

Although at the beginning , The frequency of monitoring will be relatively high , But over time , The number of intrusion attempts should decrease as the blacklist increases . Then the goal should be maintenance, not active monitoring .

So , I created a SystemD Service files and timers , This will refresh every month ipdeny Maintain subnets for each country . in fact , Everything discussed here can be found in my pagure.io Download from project .

I'm glad you read the whole article ? Now just download the service file and timer to /etc/systemd/system/, And enable the timer :

$ sudo systemctl daemon-reload
$ sudo systemctl enable --now firewalld-blacklist.timer
原网站

版权声明
本文为[User 8639654]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210922150102220w.html