Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use fail2ban and FirewallD blacklists to protect your system

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to use fail2ban and FirewallD blacklists to protect your system. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

To prevent repeated ssh login attempts, let's take a look at fail2ban. Also, if you don't travel often and basically stay in one or two countries, you can configure FirewallD to allow only visits from countries of your choice.

First, let's introduce some terminology for people who are not familiar with these applications to do this:

Fail2ban: a daemon that forbids hosts with multiple authentication errors. Fail2ban will monitor the SystemD log to find failed authentication attempts for any enabled Prison jail. After the specified number of failures is reached, it adds a firewall rule that blocks that particular IP address for the configured time.

FirewallD: a firewall daemon with a D-Bus interface that provides a dynamic firewall. Unless you decide otherwise to use traditional iptables, you have installed FirewallD on all supported Fedora and CentOS.

Hypothetical premise

The host system has an Internet connection and is either directly exposed to the Internet or via DMZ (both are very bad ideas, unless you know what you are doing), or a port is forwarded from the router.

While most of the content may be applicable to other systems, this article assumes that the current system is Fedora (31 and above) or RHEL/CentOS 8. On CentOS, you must enable the Fedora EPEL repository with sudo dnf install epel-release.

Install and configure Fail2Ban

It is likely that some Firewalld zone has already allowed SSH access, but the sshd service itself is not enabled by default. To start it manually and not permanently enable it at startup:

$sudo systemctl start sshd

Or enable it when the system starts and start it at the same time:

$sudo systemctl enable-now sshd

The next step is to install, configure, and enable fail2ban. As usual, the installation can be done from the command line:

$sudo dnf install fail2ban

After installation, the next step is to configure the "prison" (services that you want to monitor and disable at any threshold you set). By default, IP is banned for an hour (which is not long enough). It is best to overwrite the system defaults with the * .local file instead of directly modifying the * .config file. If we check 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

In popular language, the IP will be banned for one day after five attempts in the past hour. For IP that has been blocked many times, you can also choose to increase the blocking time, but this is the subject of another article.

The next step is to configure the "prison". Sshd is shown in this tutorial, but the steps for other services are roughly the same. Create a configuration file in / etc/fail2ban/jail.d. This is my file:

# cat / etc/fail2ban/jail.d/ SSHD. Local [SSHD] enabled = true

It's that simple! Many of the configurations are already being handled in the package built for Fedora (hint: I am the current maintainer). Next, enable and start the fail2ban service:

$sudo systemctl enable-now fail2ban

I hope there is no immediate error, and if not, check the status of fail2ban using the following command:

$sudo systemctl status fail2ban

If it didn't start incorrectly, it would look like this:

$systemctl status fail2ban ● fail2ban.service-Fail2Ban ServiceLoaded: loaded (/ usr/lib/systemd/system/fail2ban.service; disabled; vendor preset: disabled) Active: active (running) since Tue 2020-06-16 07:57:40 CDT 5s agoDocs: 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.7MCPU: 109msCGroup: / system.slice/fail2ban.service └─ 11235 / usr/bin/python3-s / usr/bin/fail2ban-server-xf startJun 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 is unlikely to display any interesting information, but to check the status of fail2ban and make sure Prison is enabled, enter:

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

The superior status of the sshd "prison" will also be displayed. If multiple "prisons" are enabled, they will be displayed here.

To see the detailed status of a "prison", simply add the "prison" name to the previous command. Here is the output of my system, which has been running for some time. I have removed the prohibited IP from the output:

$sudo fail2ban-client status sshdStatus 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:.

Monitoring fail2ban log files for intrusion attempts can be achieved through the "trailing" log:

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

Tail is a good command-line tool that displays the last 10 lines of a file by default. Add-f to tell it to follow the file, which is a good way to observe a file that is still being written.

Because there is a real IP in the output, no sample is provided here, but it is highly readable. The INFO line is usually an attempt to log in. If enough attempts are made from a particular IP address, you will see a NOTICE line showing that an IP address is prohibited. After the forbidden time is reached, you will see a NOTICE unbanned.

Pay attention to a few warning lines. In the most common case, when a prohibition is added, fail2ban finds that the IP address is already in its forbidden database, which means that the prohibition may not work properly. If it is a recently installed fail2ban package, it should be set to the rich rule of FirewallD. This package has switched from ipset mode to rich rule mode in fail2ban-0.11.1-6 version, so if your fail2ban is installed earlier, it may still be trying to use ipset mode, which uses the traditional iptables, which is not very reliable.

Is the FirewallD configuration passive or active?

There are two strategies that can be used separately or together: passively blacklist a single IP address or actively blacklist a subnet permanently based on the country of origin.

For passive mode, once fail2ban has been running for a while, it's best to run sudo fail2ban-client status sshd again to see if there are any bad guys. There are likely to be many banned IP addresses. Select one and try to run whois on it. There may be a lot of interesting information in the output, but for this approach, only the country of origin is important. To keep it simple, let's filter out all the information except the country.

In this example, we will use some famous domain names:

$whois google.com | grep-i countryRegistrant Country: USAdmin Country: USTech Country: US$ whois rpmfusion.org | grep-i countryRegistrant Country: FR$ whois aliexpress.com | grep-i countryRegistrant Country: CN

The reason for using grep-I is to make grep case-insensitive, while most entries use "Country", while some entries are all-lowercase "country", so this method matches anyway.

Now that we know the country of origin of the attempted invasion, the question is, "does anyone from this country have a legitimate reason to connect to this computer?" If the answer is no, then a blockade of the entire country should be acceptable.

Functionally, the active method is not much different from the passive method, however, intrusion attempts from some countries are very common. If your system is neither in these countries nor any customers from these countries, why not blacklist them now and wait? (LCTT translation note: my experience is that it is too arbitrary to be blacklisted on the basis of a country. It is suggested that the WHOIS network segment to which the IP belongs can be blacklisted, because these network segments often have the same nature of use. if they are all used for user access or IDC hosting, their security conditions are roughly the same. therefore, if there is a malicious attempt from a certain IP of this network segment, it can be expected that other IP in this network segment may also be used to make such an attempt. )

Blacklist scripts and configuration

So how do you do that? Use FirewallD ipset. I developed the following script to automate the 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 directoryipdeny_tmp_dir=$ (mktemp-d-t blacklist-XXXXXXXXXX) pushd $ipdeny_tmp_dir # Download the latest network addresses by country filecurl-LO http://www.ipdeny.com/ipblocks/data/countries/all-zones.tar.gztar xf all-zones.tar.gz # For updates, remove the ipset blacklist and recreateif firewall-cmd-Q-- zone=drop-- query-source=ipset:blacklist Then firewall-cmd-Q-permanent-- delete-ipset=blacklistfi # Create the ipset blacklist which accepts both IP addresses and networksfirewall-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 blacklistfor 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 emptyif [- 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 setupif 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:blacklistfi firewall-cmd-Q-- reload popdrm-rf $ipdeny_tmp_dir

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

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

Then create a configuration file / etc/blacklist-by-country:

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

The other configuration file, / etc/blacklist-by-ip, has only one IP per line, without any additional formatting.

In this example, 10 countries are randomly selected from ipdeny's zone file:

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

Now just add at least one country to the configuration file and you can run it!

$sudo firewalld-blacklist% Total% Received% Xferd Average Speed Time Current Dload Upload Total Spent Left Speed100 142 100 142 00 1014 0--:-1014100 662k 100 662k 00 989k 0 -: -:--: -989kAdded nl to blacklist ipset.Added ee to blacklist ipset.Added ie to blacklist ipset.Added competes for 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 that the FirewallD blacklist is successful, check the drop area and blacklist ipset.

$sudo firewall-cmd-- info-zone=dropdrop (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 | lessblacklist type: hash:net options: family=inet hashsize=4096 maxelem=200000 entries:

The second command will output all subnets, which are added based on blocked countries and can be quite long.

So what am I supposed to do now?

Although the frequency of monitoring will be high at the beginning, the number of intrusion attempts should decrease with the increase of the blacklist over time. Then the goal should be maintenance rather than active monitoring.

To do this, I created a SystemD service file and timer to refresh the subnets of each country maintained by ipdeny every month. In fact, everything discussed here can be downloaded from my pagure.io project.

Aren't you glad you read the whole article? Now all you have to do is 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 Thank you for your reading! This is the end of this article on "how to use fail2ban and FirewallD blacklists to protect your system". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report