In todayâs digital world, web server security is not just an option, but an absolute necessity. In an era where cyber attacks are multiplying and constantly evolving, effectively protecting oneâs online infrastructure has become paramount. This article focuses on securing a Nginx web server, a platform widely used for its reliability and performance.
We will address two essential tools in the arsenal of computer security: Fail2ban and UFW (Uncomplicated Firewall). Fail2ban is an intrusion prevention software that protects your server against unauthorized access attempts, often marked by multiple failed login attempts. On the other hand, UFW offers simplified firewall management, allowing easy control of incoming and outgoing traffic.
In this article, we will detail how these tools can be used together to enhance the security of your Nginx server. We will explore the steps of installation and configuration, guiding you through the process of setting up effective security rules.
Fail2ban is an indispensable tool for server security. Its primary role is to monitor your serverâs logs for signs of malicious activities, especially repeated unsuccessful login attempts. By detecting these attempts, often indicative of a brute-force attack, Fail2ban intervenes by temporarily banning the attackerâs IP address, thereby quarantining it to prevent future intrusions.
This software operates through âfiltersâ defined by the user, which specify the conditions under which an IP address should be banned. These filters are associated with âactionsâ, such as modifying firewall rules to block traffic from the banned address. Thus, using Fail2ban is a proactive method to protect your server against common attacks, while remaining flexible enough to adapt to various threat scenarios.
UFW: A Simplified Firewall Approach
UFW, standing for Uncomplicated Firewall, is an easy-to-use firewall for Linux-based operating systems. True to its name, UFW aims to simplify firewall management while offering robust protection. It serves as a user interface for iptables, the default firewall in Linux.
With UFW, you can easily set up rules that determine which traffic is allowed to enter or leave your server. These rules can be defined based on ports, protocols, and IP addresses. UFW also allows for the configuration of more complex rules if necessary, while maintaining a simple interface for less experienced users.
Essential Complementarity
The combination of Fail2ban and UFW provides a solid layer of security for your Nginx server. While Fail2ban focuses on preventing brute-force attacks by banning suspicious IPs, UFW manages overall inbound and outbound traffic, thus offering a barrier against a wide range of threats. By using these two tools together, you create a server environment that is not only resistant to the most common attacks but also adaptable to emerging threats.
Basic Installation and Configuration
While the following instructions are specific to Ubuntu Linux distribution, the principles and commands are largely transferable to other Linux systems. With minor adaptations, these steps can be applied to various distributions, making this guide useful for a wide range of Linux users.
Step 1: Installing UFW
1. Install UFW: To install UFW, run:
Shell
Step 2: Installing Fail2ban
1. Install Fail2ban: Execute the following commands to install Fail2ban on your Ubuntu server:
Shell
2. Activate the Fail2ban service: To start the service and enable it automatically at system startup, run the following commands:
Shell
3. Verify the installation: To ensure that the service has started and is functioning correctly, launch:
Shell
You should see:
Output
Step 3: Understanding How Fail2ban Works
Before delving into configuration, it is crucial to understand how Fail2ban operates. This software relies on three main components located in different directories: jails, filters, and actions.
1. Jails: These are sets of rules defining when and how an IP address should be banned. A jail is defined by log files to monitor, using filters (in the form of regex), and triggers actions when failures are detected (the filters return a result).
Fail2ban includes predefined jail configurations in /etc/fail2ban/jail.conf.
2. Filters: They are used to analyze service logs via regex to detect suspicious behavior, such as intrusion attempts.
They are found in /etc/fail2ban/filter.d/.
3. Actions: These can include banning an IP address, sending notifications, or executing custom scripts.
The actions, defining commands to ban or unban an IP address, are located in /etc/fail2ban/action.d/.
Step 4: Configuring Fail2banâs Basic Rules
Warning
Do not directly modify the files /etc/fail2ban/fail2ban.conf and /etc/fail2ban/jail.conf: these files, containing fail2banâs default configurations, can be reset during system updates.
1. Create a dedicated configuration file: To do this, open your favorite editor, here nano, by executing the command:
Shell
2. Override the base configurations: All default parameters and configurations are found in the file /etc/fail2ban/jail.conf. Here is a list of important parameters to override and adapt according to the behavior you desire:
bantime: Defines the duration of an IP ban (default 10 minutes, recommended several hours or days).
findtime: Period during which anomalies are searched for in the logs.
ignoreip: List of IPs to ignore, including yours to avoid self-banning.
maxretry: Number of failed attempts allowed before banning.
Also define the use of UFW to take control of the banning (banaction and banaction_allports).
Here is an example of a drastic configuration, banning any first intrusion attempt for 1 day. We also define the use of UFW, (note the local IP addresses that you may need to adjust according to your local network configuration):
Conf
3. Restart the Fail2ban service: To apply your modifications, restart the Fail2ban service by launching the command:
Shell
4. Verify the service status:
Shell
Which should give you:
Output
Advanced Configuration of UFW
We will apply the principle of least privilege by defaulting to blocking all incoming and outgoing connections, and only allowing the necessary traffic for specific services. By following this principle, we minimize the risks associated with unauthorized access or exploitation of vulnerabilities, ensuring that only essential ports and services are accessible.
Letâs see how to configure the firewall rules with UFW:
Step 5: Block Everything and Open Only Whatâs Necessary
Setting default rules: Block all incoming and outgoing connections by default:
Shell
Authorizing necessary connections: Open HTTP and HTTPS ports in both directions, SSH, and outgoing DNS:
Allow incoming connections for the web (HTTP and HTTPS):
Shell
Allow outgoing connections for the web:
Shell
Allow SSH connections (for remote management):
Shell
Allow outgoing DNS connections (for domain name resolution):
Shell
Step 6: Activating the Rules
Activating the UFW firewall: Enable UFW with:
Shell
Checking the configured rules: Recheck the status and rules of the firewall with:
Shell
Step 7: Add Additional Rules Based on Your Services
Mail: Allow outgoing SMTP connections for sending emails:
Shell
Additional Security (optional):
Limit SSH connection attempts to enhance security:
Shell
Restrict SSH access to certain IP addresses:
Shell
Advanced Configuration of Fail2ban
Step 8: List Preconfigured Filters on Your Server
Nginx Filters: List existing filters (may differ on your server):
Output
Create Filters: Create filters that do not exist on your server. For this, enter the commands:
For the nginx-sslerror.conf filter: This filter protects against SSL handshake failure attacks, where an attacker tries to negotiate an SSL/TLS connection with incorrect or malicious parameters.
Shell
For the nginx-4xx.conf filter: This filter detects requests generating HTTP 4xx errors (like 404, 403, 400), often the result of attempts to access unauthorized or non-existent resources, indicating malicious probing.
Shell
For the nginx-forbidden.conf filter: This filter targets attempts to access forbidden directories. It is useful for blocking directory scans attempting to discover hidden files or folders on the server.
Shell
For the nginx-botsearch.conf filter: This filter focuses on requests for URLs that do not exist (404 errors), often a sign of a bot or scanner trying to find vulnerabilities or hidden pages.
Shell
For the nginx-http-auth.conf filter: This filter is used to detect and block repeated failed authentication attempts, indicating a possible brute-force attack on password-protected areas.
Shell
For the nginx-limit-req.conf filter: This filter aims to block IP addresses that exceed the request limits defined in Nginx (limit_req), typical of a distributed denial of service (DDoS) attack or aggressive bot behavior.
Shell
Step 9: Add Jails to Your Configuration
To add these jails to the Fail2Ban configuration in the custom.conf file, follow these steps:
Open the configuration file: Use the command to open the file in a text editor:
Shell
Add jail configurations: Copy and paste the following configurations at the end of the file:
Conf
Save and close the file: After adding the configurations, save the file and close the text editor.
Restart Fail2Ban: To apply the changes, restart Fail2Ban with:
Shell
This configuration will add and activate the specified jails for SSH, various Nginx configurations, and UFW.
Step 10: Verification and Testing
After configuring, it is essential to test and verify that everything is working correctly.
Checking Fail2ban: Use this command to list the active jails and check that Fail2ban is functioning properly.
Shell
Which returns:
Output
These steps form the basis for securing your Nginx server on Linux with Fail2ban and UFW. Remember that the configuration can be customized according to the specific needs of your server and network.
You will find multiple filters for Fail2ban on the internet, tailored to the services running on your server.
Visualization and Analysis of Bans
Data Extraction
To effectively understand and analyze Fail2Banâs security actions, itâs useful to have an overview of the banned IP addresses.
The following script provides this visibility, categorized by jail:
Shell
Here is an example of all the IPs that have been blocked on my server:
Output
I truncated the IPs, there were more than 2600 for 24 hours of retention! This example shows that a very large number of IP addresses were blocked on my server, which does not contain highly sensitive data.
The significant volume of banned IPs also highlights the extent and consistency of automated attacks against online servers. Even systems that seem uninteresting are frequently targeted by bots and cyber attackers seeking vulnerabilities, for malicious purposes such as spam or botnet creation. There are also many legitimate companies scanning the internet for compromised servers.
Calculating Some Statistics
The analysis of IP data can reveal significant information about the geographical distribution, organizational ownership, and location of these scans.
The Bash script below allows for precise statistics to be calculated from the collected IP addresses. These statistics include the counting of the number of IP addresses by country, organization, and city. This process helps understand the trends of attacks and their geographic distribution.
Bash
Scans by Country
Results
Output
Interpretation of Blocked Scans by Country
1. High Scanning Activity in the United States (US)
Number of occurrences: 1055
Implication: This high activity suggests a significant presence of scans, possibly automated, originating from the United States. This could indicate either a large number of active servers and computer systems or the presence of compromised networks.
2. Notable Presence of China (CN) and the United Kingdom (GB)
China: 361 occurrences
United Kingdom: 252 occurrences
Implication: High frequency of scans from these regions, possibly indicating malicious activities or strong cyber defense.
3. Scans Originating from Europe
Countries involved: Netherlands, Germany, Belgium, France, Russia
Implication: Active scanning activities or networks often targeted by attacks, necessitating proactive defense.
4. Diversity of Asian Sources
Countries involved: Taiwan, South Korea, India, Japan, Vietnam
Implication: Regions active in scanning or targeted by attacks, reflecting the trends in cyber security in Asia.
5. Activity in Latin America and Africa
Latin America: Brazil, Argentina, Mexico, Colombia
Africa: Less prevalent but notable presence
Implication: Trend towards the automation of attacks or the presence of compromised systems in these regions.
6. Countries with Few Occurrences
Examples: African countries, European and Asian countries with a single or very few counts
Implication: Sporadic scanning attempts or isolated actors.
These statistics provide an insight into trends in cyber security and malicious activities on the Internet. They reveal the effectiveness of security measures like Fail2Ban and UFW in protecting a server from unauthorized or malicious access attempts.
Scans by Organization
Results
Output
Interpretation of Blocked Scans by Organization
1. Google LLC (AS396982)
Number of occurrences: 590
Implication: Significant activity from IP addresses associated with Google, indicating potential use of Google services for network scanning or misuse of their PaaS GCP platform.
2. DigitalOcean, LLC (AS14061)
Number of occurrences: 384
Implication: High scanning activity from this cloud organization, suggesting either legitimate services or potentially compromised cloud instances.
3. Hurricane Electric LLC (AS6939)
Number of occurrences: 165
Implication: Notable presence of scans from this Internet service provider, possibly indicating abuse of its services for scanning activities.
4. Chinese Organizations
Number of occurrences:
CHINANET-BACKBONE (AS4134): 108
Hangzhou Alibaba (AS37963): 71
Tencent (AS45090): 59
CHINA UNICOM (AS4837): 54
Other Chinese organizations with significant occurrences
Implication: Scanning activities emanating from major Chinese corporations, reflecting either legitimate operations or abuse of their networks.
5. Censys, Inc. (AS398324, AS398705)
Number of occurrences: Total of 145
Implication: Censys, a data security-focused company, appears engaged in scanning activity, likely in a security research context.
6. OVH SAS (AS16276) and Other Hosting Providers
Implication: Scans from OVH and other hosting providers may indicate either legitimate services or abuse of hosting resources.
7. Diversity of Global Sources
Implication: The presence of organizations from many countries (e.g., KR, IN, RU, JP, VN) shows a diversity in the geographical origin of scans, which may reflect a wide range of intentions and practices.
8. Scanning Activities by ISPs and Telecommunications Companies
Examples: Korea Telecom (AS4766), NTT Communications (AS4713)
Implication: These ISPs and telecommunications companies may be involved in scans for maintenance, security, or other legitimate activities.
These statistics underscore the importance of ongoing monitoring and protection against potentially malicious scanning activities. The diversity of sources, ranging from cloud service providers to major telecommunications companies, illustrates the complexity of the online security ecosystem.
Scans by City
Results
Output
Interpretation of Blocked Scans Statistics by City
1. San Francisco (314 Occurrences)
Implication: Significant activity from this technologically advanced city, likely reflecting the use of services based in Silicon Valley.
2. London (218 Occurrences)
Implication: Strong activity from this global metropolis, suggesting scanning operations from companies based in London or using services hosted there.
3. North Charleston (210 Occurrences)
Implication: A surprising number of scans from this city, possibly indicating the presence of cloud service infrastructures or other technology companies.
4. Chinese Cities (Shenzhen, Shanghai, Beijing, etc.)
Total Occurrences: Over 150
Implication: Significant scans emanating from several major Chinese cities, illustrating the breadth of technological and digital presence in China.
5. Amsterdam (103 Occurrences)
Implication: With its cloud service infrastructure and data centers, Amsterdam is a notable source of scans.
6. Frankfurt am Main (75 Occurrences)
Implication: High activity in this German city, known for its data centers and key role in European networks.
7. Diversity of Global Sources
Implication: The variety of cities (such as Seoul, Tokyo, Paris, Moscow) indicates a global distribution of scan sources, reflecting the global nature of online activity and potential threats.
8. Specific Activities of Certain Cities
Examples: SĂŁo Paulo, Singapore, Santa Clara
Implication: These cities, known for their concentration of technology companies, show scanning activity that may be attributed to legitimate research or network abuses.
These statistics highlight the geographical diversity of scanning activities and underscore the importance of cybersecurity measures. The presence of scans from major technological and financial cities indicates that these regions are hotspots for online activities, necessitating increased vigilance for network protection.
Conclusion
Securing your Nginx server with Fail2ban and UFW is a crucial step in protecting your data and infrastructure against increasingly sophisticated cyber attacks. In this article, we have seen how Fail2ban and UFW can be used together to form a robust barrier against attacks, by combining the detection and banning of malicious IP addresses with rigorous management of network traffic.
Implementing these tools is just the beginning of an ongoing security process. It is essential to keep these systems updated, regularly adjust configurations in response to new threats, and continuously monitor logs for intrusion attempts. Data analysis clearly demonstrates the importance of these tools in detecting and blocking a multitude of unauthorized access attempts from around the world.
Finally, keep in mind that security is an evolving practice. Threats are constantly changing, and our defense methods must adapt accordingly. Do not hesitate to explore new tools, share your knowledge with the community, and stay informed of the latest trends in cybersecurity.
Seasoned professional in the field of information technology, I bring over 20 years of experience from working within major corporate IT departments. My diverse expertise has played a pivotal role in a myriad of projects, marked by the implementation of innovative DevOps practices.