Sign In
Sign In

How to Set Up a Firewall with UFW on Ubuntu

How to Set Up a Firewall with UFW on Ubuntu
Mohammad Waqas Shahid
Technical writer
Ubuntu Firewall
02.04.2024
Reading time: 10 min

In this comprehensive tutorial, users are guided through the process of setting up a robust firewall using the Uncomplicated Firewall (UFW) on Ubuntu. UFW provides an intuitive interface for managing netfilter firewall rules, offering an accessible solution for securing Ubuntu systems effectively.

Introduction to UFW

UFW, or Uncomplicated Firewall, is a user-friendly interface for managing iptables, the standard firewall management tool for Linux systems. It simplifies the process of creating and managing firewall rules, making it accessible even to users with limited networking knowledge.

Understanding Firewall Basics

Before diving into the configuration process, it's essential to understand some fundamental concepts related to firewalls and how they operate.

What is a Firewall?

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It acts as a barrier between a trusted internal network and untrusted external networks, such as the internet.

On Hostman, you can buy a cloud firewall that provides cutting-edge defense tailored for businesses of all sizes.

Types of Firewalls

There are several types of firewalls, including packet-filtering firewalls, stateful inspection firewalls, proxy firewalls, and application layer firewalls. Each type operates differently but serves the common purpose of protecting networks and systems from unauthorized access and malicious activity.

Creating Account and Server on Hostman

To kick off the process, prospective server hosts are encouraged to visit the official Hostman website. Sign up for a new account by providing essential details and create a strong password. Following this, check your email for a verification link, click on it, and swiftly log in to your Hostman account.

Image1

Within the Hostman control panel, the user-friendly interface offers to start a new server. By navigating to the Create button, users can initiate the server creation process. Select the parameters you need, including software (for the purposes of this guide, we need a server with the Ubuntu operating system), configuration, geographical region, and backups, choose the project for this server, then click Order to create your server. 

The server will be installed in a couple of minutes and you will see the server's dashboard. Later on, to find your server you can go directly to Cloud servers or to the project the server is added to. 

234567

Click on your server, start it by the play button and scroll down to see the SSH command and root password for your Ubuntu server.

593f4dc2 53df 4468 8352 F2309e4ffb7f

Accessing Your Server

Access the server through the web-based terminal provided by Hostman or use preferred SSH client. For this tutorial accessing through SSH is used.

Image5

Updating System Packages

The following code is to be written in terminal to update system packages of Ubuntu:

sudo apt-get update
sudo apt-get upgrade

Image7

Type “y” and hit Enter.

After the upgrade, the following screen may appear. (If there is nothing to upgrade on your server, i/e. you already had the latest versions of the installed packages, you will not see this window and can proceed to the next step.)

Image6

In this popup, you are prompted to select which services should be restarted after the installation process. The services listed are part of the systemd system and are related to various system functionalities.

Here's a brief explanation of the options:

  • systemd-journald.service: The journal service, which handles system logs.

  • systemd-logind.service: The login service, which manages user logins.

  • systemd-manager: The service manager for the system.

  • systemd-networkd.service: The network service, responsible for network configuration.

  • systemd-resolved.service: The DNS resolver service.

  • systemd-timesyncd.service: The time synchronization service.

  • unattended-upgrades.service: A service for automatically applying package updates.

  • [email protected]: A user-specific service (user 0 refers to the root user).

Given the importance of network-related services for firewall functionality, it is recommended to restart the following services after the upgrade:

  • systemd-networkd.service: This service is responsible for network configuration. Restarting it ensures that any changes made during the upgrade, particularly those related to networking or firewall rules, take effect.
  • systemd-resolved.service: The DNS resolver service handles DNS resolution. Restarting it is advisable if there were changes to DNS configurations or updates to the DNS resolver service, which could impact firewall rules that rely on domain name resolution.

  • systemd-timesyncd.service: The time synchronization service ensures accurate timekeeping on the system. Proper time synchronization is crucial for security measures such as certificate validation and timestamping of firewall logs.

These services are crucial for maintaining system functionality and security, especially in the context of firewall configuration. 

Installing UFW on Ubuntu

Before starting the firewall configuration, it's essential to ensure that UFW is installed on your Ubuntu system. Here's how to do it:

Checking UFW Installation Status

Open the terminal and run the following command to check if UFW is installed:

sudo ufw status

You should see the status Active (running). If the status is inactive, start the service using the command:

sudo ufw enable

If UFW is not installed, the terminal will output the message Command ‘ufw’ not found. Follow the instruction below to install it.

Installing UFW

Install UFW by executing the following commands in the terminal:

sudo apt update
sudo apt install ufw

After completing the installation, recheck the status by typing:

sudo ufw status

Basic Firewall Configuration with UFW

Once UFW is installed, it's time to configure the basic firewall settings. Here's how to get started:

Enabling UFW

Activate UFW by running the following command in the terminal:

sudo ufw enable

You will receive a confirmation message indicating that the firewall is now operational.

Allowing SSH Access

If SSH access is not permitted by default, allow SSH connections using the command:

sudo ufw allow ssh

Permitting Specific Ports

To enable specific ports for various services such as web servers or database servers, use the command:

sudo ufw allow <port_number>

Replace <port_number> with the designated port number you wish to allow.

Advanced UFW Configuration

For advanced users looking to customize their firewall settings, UFW offers a range of configuration options:

Denying Incoming Connections

For enhanced security, deny all incoming connections by default and allow only designated ones:

sudo ufw default deny incoming

Allowing Outgoing Connections

Allow all outgoing connections by default:

sudo ufw default allow outgoing

Implementing Custom Rules

Define custom rules based on specific requirements:

sudo ufw <rule>

Below are examples of configuring custom rules in UFW for various scenarios, including allowing SSH, HTTP/HTTPS, specifying port ranges, and denying access based on IP addresses or subnets:

Allowing SSH Connections

To allow SSH connections, you can use the service name or specify the port number:

sudo ufw allow ssh

Or:

sudo ufw allow 22

Allowing HTTP and HTTPS Connections

To allow HTTP and HTTPS traffic, use the respective service names or port numbers:

sudo ufw allow http
sudo ufw allow https

Or:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Allowing Access to a Specific Port Range

To allow access to a range of ports, specify the port range:

sudo ufw allow 8000:9000/tcp

Allowing Access from Specific IP Addresses or Subnets

To allow access from specific IP addresses or subnets, specify the IP address or subnet:

sudo ufw allow from 192.168.1.100
sudo ufw allow from 192.168.0.0/16

Denying Access to a Specific Port

To deny access to a specific port, use the deny command:

sudo ufw deny 1234

Denying Access from Specific IP Addresses or Subnets

To deny access from specific IP addresses or subnets, use the deny command:

sudo ufw deny from 10.0.0.1
sudo ufw deny from 172.16.0.0/24

Denying All Incoming Connections (Except Allowed Ones)

To deny all incoming connections by default and allow only specific ones, use the default deny command:

sudo ufw default deny incoming

Allowing All Outgoing Connections

To allow all outgoing connections by default, use the default allow command:

sudo ufw default allow outgoing

These examples demonstrate how to configure custom rules in UFW for different scenarios, including allowing or denying access based on services, ports, IP addresses, and subnets. Customise these rules according to your specific requirements to enhance the security and control of your firewall configuration.

A Brief Guide for Requirements for Custom Rules

Following is a brief elaboration on which requirements may necessitate specific customizations in firewall rules to enhance security and control:

  1. Requirement: Secure Remote Access

Allowing SSH access (port 22) for remote administration while restricting access from specific IP addresses or subnets to prevent unauthorised access.

  1. Requirement: Hosting Web Services

Allowing HTTP (port 80) and HTTPS (port 443) traffic to host web services, while potentially restricting access to specific IP addresses or subnets to limit exposure to the public internet.

  1. Requirement: Application with Specific Port Range

Allowing access to a range of ports required by a specific application (e.g., ports 8000-9000) while denying access to all other ports to reduce attack surface.

  1. Requirement: Network Segmentation

Defining rules to allow communication between different segments of the network while denying access from external networks to sensitive segments to enforce network segmentation and control.

  1. Requirement: Denial of Service (DoS) Protection

Implementing rate-limiting rules to mitigate DoS attacks by limiting the number of incoming connections per second from specific IP addresses or subnets.

  1. Requirement: Compliance with Regulatory Standards

Implementing firewall rules to enforce compliance with regulatory standards (e.g., PCI DSS, HIPAA) by restricting access to sensitive data and ensuring secure communication channels.

  1. Requirement: Log Monitoring and Analysis

Enabling logging for specific firewall rules to monitor and analyze network traffic for security incidents, compliance audits, and troubleshooting purposes.

  1. Requirement: Application-Specific Rules

Defining application-specific rules based on the requirements of the deployed applications, such as allowing access to database ports only from application servers.

  1. Requirement: BYOD (Bring Your Own Device) Policies

Implementing rules to allow access for authorised devices while restricting access for unauthorised devices based on device attributes or user credentials.

  1. Requirement: High Availability and Failover

Configuring redundant firewall rules across multiple firewall instances to ensure high availability and failover in case of hardware or network failures.

These customizations align with best practices and address specific requirements to enhance security, control, and compliance in firewall configurations without technical errors or inaccuracies.

Testing Firewall Configuration

After configuring the firewall, it's essential to verify that the rules are applied correctly and test connectivity:

Verifying Firewall Rules

Ensure the correct application of firewall rules:

sudo ufw status verbose

Testing Connectivity

Conduct connectivity tests to verify that permitted connections function as intended. Users can do this by attempting to establish connections to services running on the system from both local and remote hosts.

Monitoring and Managing UFW

Once the firewall is configured, it's important to monitor and manage UFW to ensure optimal security.

Checking UFW Status

Monitor the status of UFW at any time:

sudo ufw status

Disabling UFW

Temporarily disable UFW when necessary:

sudo ufw disable

Logging Firewall Activity

Enable logging to monitor firewall activity and identify potential security threats:

sudo ufw logging on

Conclusion

Implementing a firewall using UFW on Ubuntu is crucial for enhancing system security and safeguarding against potential threats. By following the steps outlined in this tutorial, users can effectively configure and manage their firewall settings, ensuring the protection of their Ubuntu systems. With UFW's user-friendly interface and powerful capabilities, users can easily create and enforce firewall rules to control network traffic and prevent unauthorized access. By understanding the basics of firewalls and utilizing the advanced configuration options provided by UFW, users can create a robust defense against cyber threats.

Ubuntu Firewall
02.04.2024
Reading time: 10 min

Similar

Ubuntu

How to Install Caddy Web Server on Ubuntu 22.04

Caddy is a cross-platform web server built in the Go and uses HTTPS by default. It stands out for its ease of use and simple configuration. It is known for being easy to configure, especially for users who do not have much experience with web server administration.  Unlike other web servers, Caddy is designed to work with HTTPS out of the box and has integration with Let's Encrypt, allowing you to automatically receive and renew certificates. Below, we will explain how to install Caddy on Ubuntu 22.04 and how to configure it. Why Use Caddy? Why do you need Caddy and what does it offer compared to Apache or Nginx? As we said above: simplicity and security. You do not need to configure encryption parameters and protocol usage, Caddy will do everything out of the box, and in the best possible way, using the most modern technologies. It has the latest features such as HTTP/2, IPv6, Markdown, WebSockets, CreateCGI, templates, and other standard features. The configuration itself is extremely simple, you need to set a minimum of options to get a working server, but at the same time you can manage it quite flexibly, redefining the necessary parameters. The only downside is compatibility with old systems, as Caddy automatically disables outdated protocols and ciphers. Installing the Caddy Web Server via Cloudsmith  There are four different methods to install Caddy. We can do it by simply downloading the executable binary, by compiling the source code, using docker image, or installing it from the repository. In this article, we will do the latter. Before we start installing the Caddy web server, it is recommended that we first update the Ubuntu host system and at the same time update the package sources. We always want to benefit from the most recent releases and prefer to avoid outdated software packages. Perform updates and upgrades: sudo apt update && sudo apt upgrade -y Installing Caddy requires appropriate sudo permissions on the host system. To install Caddy on Linux Ubuntu 22.04, we first start by setting up the necessary dependencies: apt install gnupg curl apt-transport-https debian-keyring debian-archive-keyring -y Once the installation of all dependencies for the web server has been successfully completed, we need to add the GPG key using the following command: curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg Next we have to add the Caddy repository to the APT sources list, allowing Caddy to be installed from this repository: curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list Update the package sources: sudo apt update -y Finally, the Caddy can be installed via the command line. At this point, all prerequisites, and preparations for the installation have been successfully completed. Run the command below to install. sudo apt install caddy -y Now that the web server has been installed on the Linux host system, the service just needs to be activated. We do this with the following command. sudo systemctl enable --now caddy The version you just installed can be validated with the following command: caddy version Is a version number displayed? Then Caddy has been successfully installed on the system. Caddy Configuration The internal format of the caddy configuration is stored in JSON format and can be managed online via REST API, a more classic format of setting via a configuration file is also available, for this purpose the configuration file /etc/caddy/Caddyfile is used.  It already contains an example of the configuration, and we only need to correct it. Please note that the indents in the file are formed strictly using tabulation and two, four, six, etc. indents should be used, otherwise you will receive a warning about incorrect formatting of the configuration file. Set up a Static Site If we want to set a website with Caddy over the local network or over the Internet, we have to save the files and subdirectories associated with the website in the www directory. To do this, we first create a new directory for the output of a web page: sudo mkdir -p /var/www/htmlcd /var/www/html Create a website index with the editor: sudo nano index.html Copy the following content and paste this example page into the index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello, I'm Caddy, your reliable web server!</title> </head> <body> <p>Great projects can be created here! All that is needed is HTML and CSS knowledge, rounded off with a little JavaScript.</p> </body> </html> Now we need to edit the Caddy configuration file so that the web page can be displayed. To do this, execute the following commands from your system. sudo nano /etc/caddy/Caddyfile  Edit: :80 { # Path of the website root * /var/www/html/ The website should now be accessible via the IP address from the local network. If you want to make the website accessible via the Internet, the web ports (80/443) must be released for the server IP address within the NAT settings in the router/firewall. Set up a Domain To set up a domain, you first need to specify the domain's A/AAAA DNS records on this server in the DNS control panel. Then create a document root directory for the website in the /var/www/html folder: mkdir /var/www/html/example.com Replace example.com with your domain. When using SELinux, we will change the file security context for web content: # chcon -t httpd_sys_content_t /var/www/html/example.com -R# chcon -t httpd_sys_rw_content_t /var/www/html/example.com -R To configure a domain in this configuration, we will only have to replace <name> :80 with our domain. Also, if we want to change the path of our website, we will have to modify the parameter root. example.com { root * /var/www/html/example file_server } To reload the configuration, we have to restart the service: systemctl reload caddy Also, if we want, we can configure the logs for access: example.com { root * /var/www/html/example file_server log { output file /var/log/caddy/access.log format console } } Configure a Dynamic Site  To work with dynamic content, we will need support for PHP, the scripting language in which most CMS are written. Caddy does not have its own process manager, so we will use PHP-FPM for this purpose: sudo apt install php-fpm Then we go to /etc/php/8.3/fpm/php.ini and adjust some parameters. First, we find, uncomment and change the option to the following: cgi.fix_pathinfo=0 Then we set the maximum size of the request being sent: post_max_size = 32M And the maximum size of the uploaded file, it must be less than or equal to the size of the request sent: upload_max_filesize = 30M Save the changes and restart the fpm service: sudo systemctl restart php8.3-fpm Now, after adding the fpm directive, configuration will look like this: example.com { root * /var/www/html/example file_server encode zstd gzip php_fastcgi unix//run/php/php8.3-fpm.sock # Uses PHP-FPM to serve PHP files (through a Unix socket) log { output file /var/log/caddy/access.log format console } } Set up Caddy as Reverse Proxy To set up a reverse proxy, add a new site block with the following structure: example.com { encode zstd gzip handle_path /static/* { root * /var/www/html/example file_server } reverse_proxy localhost:3000 log { output file /var/log/caddy/access.log format console } } This Caddyfile sets up a reverse proxy where requests to hostman.com are forwarded to localhost:3000, except for requests starting with /static/, which are served directly from /var/www/html/example. The reverse_proxy directive ensures all non-static requests are proxied to the backend server at localhost:3000. Wrapping Up If you are a beginner and want to set up a web server without the hassle of long configuration, Caddy is perfect for you. Even if you are an experienced user who needs an instant and simple web server, then you should pay attention to Caddy.  If you require a more sophisticated server with advanced features, then with minimal configurations you can set folder permissions, manage authentication, error pages, archiving, HTTP request redirection, and other settings.
07 February 2025 · 7 min to read
PostgreSQL

How to Install PostgreSQL on Ubuntu

PostgreSQL is a well-known relational database management system that provides high-availability features. These are renowned for their functionalities, such as support for complex statements, views, triggers, and foreign keys. PostgreSQL is installed on Ubuntu to provide a secure as well as flexible DB infrastructure. By installing it on the Linux distribution, you can enable and deal with the vast data in an efficient and secure manner. This infrastructure is designed to deal with different workloads, from single-machine apps to large internet-facing apps with multiple concurrent users. In this tutorial, we will walk through installing and setting up PostgreSQL on Ubuntu. Installing PostgreSQL on Ubuntu Ubuntu comes with the PostgreSQL package in its default repositories. You can install it on a Linux system following the given steps. It downloads the stable package. This is important for DB analysts, administrators, and industries that require a dependable DB solution for managing a large volume of data.  Let’s move forward into each step of installing PostgreSQL with detailed explanations on Ubuntu. Step 1: Refresh Ubuntu Repository First, refresh the Ubuntu package indexes. It is useful for maintaining system stability and security: sudo apt update Step 2: PostgreSQL Installation  PostgreSQL is included in Ubuntu's default repositories, making installation straightforward. To install it with some additional tools, execute the below command: sudo apt install -y postgresql postgresql-contrib Here: postgresql: The core PostgreSQL DB server. postgresql-contrib: Additional utilities and extensions useful for DB. Step 3: Start and Enable Services It is essential to enable the PostgreSQL service after installation and ensure it starts automatically upon bootup. The installed package utilizes the systemd daemon, which deals with the DB server runtime operations.  Run the commands below to make sure the DB server automatically initializes when the server boots up. Let’s initialize the service: sudo systemctl start postgresql And enable it so that it launches automatically when the machine boots up: sudo systemctl enable postgresql Step 4: Verify Installation To verify if the installed package is operating properly, check out its status through the below: sudo systemctl status postgresql In the figure, you can see an active status. It represents the services that are correctly running. Step 5: Access Shell Finally, switch to the PostgreSQL user account and launch the CLI to interact with database operations. Here, the -i flag provides an interactive login shell: sudo -i -u postgres The above display gives access to a user account. Once you're in the user environment, launch the CLI through the given command: psql As you can see in the above screenshot, this command launchs the CLI, where users can perform multiple operations by executing commands. Step 6: Basic Database Commands The creation of a database and a new user for any application is a good practice rather than using the root. In this way, a particular user can access the shell interface and run basic statements on the particular database. Here are general commands with thorough explanations and examples: Creation of the New Database To prevent conflicts, ensure data integrity and control access privileges for different applications or users, you need to create a new database. For creation, use the given command within the shell: CREATE DATABASE hostmandb; The screenshot shows that a database has been created. Creation of the New User Create a customized user and set a strong password: CREATE USER hostman_user WITH ENCRYPTED PASSWORD 'Qwer1234'; We have created a hostman_user with the password Qwer1234. Give Privileges to the Created User You can grant hostman_user complete privileges to the hostmandb through the given command. This allows controlled accessibility to database objects, enhancing data integrity as well as security: GRANT ALL PRIVILEGES ON DATABASE hostmandb TO hostman_user; Exit Shell For closing the shell, you can utilize the \q option as below: \q The figure shows that the shell has been exited. Finally, you can exit the user environment by executing the given command: exit The output confirms that you have returned to the main system user account. Access a Database as the Particular User You can connect to the particular database from the specific user account through the -U flag: psql -U hostman_user -d hostmandb -h 127.0.0.1 -p 5432 Here: -U hostman_user: Indicates the user. -d hostmandb: Indicates the database name. -h 127.0.0.1: Indicates the host (local machine). -p 5432: Indicates the PostgreSQL default port. In the given output, you can see that the user hostman_user has accessed the hostmandb console. Listing of All Databases View all databases and check whether the hostmandb database is available or not: \l In the figure, you can see that the database hostmandb is listed. Switch/Connect to the Particular Database To switch to a specific database, such as hostmandb, within PostgreSQL, use the \c command: \c hostmandb The above output confirms that the postgres user has successfully connected to the hostmandb database. Creation of the Particular Table To create a customized table, use the below statement. In our example, we create a hostmantb table: CREATE TABLE hostmantb(    id SERIAL PRIMARY KEY,    name VARCHAR(100),    age INTEGER,    department_id INTEGER); Here: id SERIAL PRIMARY KEY: It creates an auto-incrementing primary key column with the name id. name VARCHAR(100): It creates a name column that can store up to 100 characters. age INTEGER: It creates an age column that stores integer values. department_id INTEGER: This line creates a department_id column that stores integer values. The outcome of the above screenshot confirms that the table hostmantb is successfully created with specific attributes. List All Tables in the Particular Database For listing all tables in the hostmandb database, use the \dt command: \dt It displays all tables as well as confirms that the hostmantb is listed above. Overview a Table's Structure You can view the structure of the created table through the \d command. Let’s display the structure of hostmantb table: \d hostmantb In the above figure, you can see the complete structure of hostmantb table with id, name, age, and department_id having specific types. Input Entries into a Particular Table To input entries into a hostmantb table, use the below statement. This way, we input the values Peter, 35, and 1 to the columns name, age, and department_id, respectively: INSERT INTO hostmantb(name, age, department_id) VALUES ('Peter', 35, 1); The output confirms that we have successfully input data into the hostmantb table. Select All Data from a Particular Table You can select all data from the hostmantb table through the below statement: SELECT * FROM hostmantb; Modify Data in Particular Table For modifying data in hostmantb, you can utilize the below statement. For example, set the age column to 40 for the row where the name column equals Peter: UPDATE hostmantb SET age = 40 WHERE name = 'Peter'; The output confirms that the age column is updated. Remove Data from the Particular Table In this section, you can remove data from the specific table through the DELETE statement. It deletes all entries from the hostmantb table where the value in the name column is Peter: DELETE FROM hostmantb WHERE name = 'Peter'; In the screenshot, one entry from the hostmantb table is removed. Exit CLI You can easily exit the CLI via the \q utility: \q This tutorial has given you thorough guidelines for every step involved in installing as well as setting PostgreSQL on Ubuntu.  Conclusion By installing PostgreSQL on Ubuntu, you can optimize the DB infrastructure. PostgreSQL is often chosen for its freely available nature, which allows for customization, the system's stability and security features. In addition, PostgreSQL's supporters' help and comprehensive guide make it simpler to enhance operations and troubleshoot problems.  This combination makes sure that the DB system is both powerful as well as adaptable to several needs. In this tutorial, there are a lot of fundamental DB commands to get you started with database administration. Therefore, you will be able to create databases, and users and perform basic tasks.
24 January 2025 · 7 min to read
Firewall

How to Install CSF (ConfigServer Security & Firewall) on Ubuntu 22.04

ConfigServer Security & Firewall (CSF) is a highly regarded tool for securing Linux servers against varying cyberattacks. Its robust functionality and simple interface proves that it is the best choice for system administrators. Whether you're managing a small server or large network, this tool provides an effective defense mechanism which is easy to deploy and manage. The below manual discusses the installation process and configuration of this tool on Ubuntu 22.04 LTS to maximize protection and performance of the server. Advantages of Usage of CSF Firewall on Ubuntu 22.04 LTS This versatile security solution has a variety of benefits tailored for servers using Linux as an operating system. User-Friendly Management With an easy-to-edit configuration file and simple command-line utilities, it ensures even novice administrators can quickly implement server security measures. Powerful Security Features Port Restrictions: Secure sensitive services like MySQL (port 3306) and SSH (port 22) by allowing or denying specific traffic. DDoS Attack Mitigation: Safety against high-traffic denial-of-service attempts. False Login Notifications: Automatically blocks IPs after repeated false login attempts to protect from brute force attacks. GeoIP Filtering: Restriction ofentry from certain geographic regions which gives enhanced security Effortless Update Integrated with the system's package manager, CSF updates seamlessly, making sure that firewall contains the latest security patches. Low Resource Consumption Optimized for performance, this tool works without placing unnecessary strain on system resources. Custom Alerts and Logs Receive real-time notifications for security events and go through detailed logs to monitor server activity. Step-by-Step Guide to Install CSF on Ubuntu 22.04 LTS Below is a detailed manual which explains installing it on Ubuntu 22.04 LTS. Step 1: Updating the System First, update the system’s package repository to make sure you have the latest software. To update the system’s package repository, use the following command: sudo apt update && sudo apt upgrade -y Step 2: Installation of Dependencies CSF relies on some dependencies to function appropriately. To install dependencies, use command below: sudo apt install -y perl libwww-perl liblwp-protocol-https-perl iptables nano Essential Dependencies: Perl: It is a programming language. Many of the CSF scripts and configuration tools are written in Perl. Installing perl will ensure that the system will run necessary scripts to manage firewall operations properly. libwww-perl and liblwp-protocol-https-perl: These libraries handle HTTP & HTTPS requests. CSF uses them to fetch updates, download remote blocklists, and securely manage real-time threat data feeds over HTTPS, enhancing firewall’s ability to keep itself updated with the new security information. iptables: Serving as the foundation for the Linux firewall functionality, iptables is integral for operations. It allows to define and implement traffic filtering rules, block specific ports, and restrict connectivity by IP addresses at the kernel level. nano: While optional, it is included to simplify the method of editing the configuration files directly from the terminal. It enables system administrators for doing quick modifications to firewall settings while staying in terminal. Step 3: Download and install CSF The package is available to download through its official website. For downloading, run these commands: cd /usr/srcsudo wget https://download.configserver.com/csf.tgz Extract the files: sudo tar -xvzf csf.tgz For installation, go to the extracted directory:  cd csf And execute the installer by running the following command: sudo sh install.sh When the installation is complete, it will look like the following: To confirm installation, check the CSF version by running: sudo csf -v CSF version will appear on the screen: Step 4: Configure CSF Firewall Settings CSF needs to be configured according to the user’s needs. There are two ways to configure it, through GUI and through terminal. By Terminal For this, we will perform changes in csf.conf located at /etc/csf/csf.conf. Use the following command to open the csf.conf file: sudo nano /etc/csf/csf.conf Output: Do the following changings for basic firewall protection: Testing mode (TESTING = "1") temporarily clears firewall rules to prevent being locked out during configuration. Enable it until you verify all settings, then disable it (TESTING = "0") to activate full protection. TESTING = "0" Allow MySQL Port: If you need to allow using MySQL, update csf.conf as below: TCP_IN = "22,3306" After modifications have been done in configuration, apply them, using: sudo csf -rsudo systemctl restart csf By GUI This tool already has a GUI mode built in. It needs to be configured through the csf.conf and a few commands. Following is the procedure of enabling it. 1. Install prerequisites: To install prerequisites, use the following command: apt-get install libio-socket-ssl-perl libcrypt-ssleay-perl \                    libnet-libidn-perl libio-socket-inet6-perl libsocket6-perl 2. Perform amendments in csf.conf: Perform edits in csf.conf to enable the UI mode and allow endpoints. Also update the username and password for UI. Note that the default username and password have to be updated. So to access the csf.conf, use the following command: sudo nano /etc/csf/csf.conf Now find ui = "0" and convert it to "1". This will enable the UI mode. Then find UI_PORT =  and write an entry of 7171. This will be the specific gateway on which you can interact with the GUI. Be sure that the port number is always bigger than 1024. After these, also edit the UI_USER and UI_PASSWORD. If the default UI_USER and UI_PASSWORD are not updated the UI will not work. Its a MUST to edit these from default values. Place the same port in TCP_IN and TCP_OUT.  Enter this command to add your IP address to ui.allow file: sudo echo "your_IP_adress" >> /etc/csf/ui/ui.allow In this command you have to paste your IP address. If you do not know your IP address, then you can just google "Whats my IP" and it will show you your IP. Just copy and paste in the above command and hit enter. Then in the terminal, type: csf -rsystemctl restart csfsystemctl restart lfd This will properly apply the ammendmets you have performed. Now, your UI has been set up. Now you need to enter your IP address with the endpoint you allowed (7171). Finally, interact with the UI. To connect with the GUI, you need to type the IP of the server along with the port that you set (7171) in your browser. In my case it was the following: 195.133.93.222:7171 195.133.93.222: The public IP address of the server 7171: Gateway number which I set Now you have the GUI. Additional CSF Firewall Commands With the tool now installed, you can make additional commands that can be highly useful for enhancing firewall management. Following is some detail: To block an IP address: sudo csf -d <IP_ADDRESS> To allow an IP address: sudo csf -a <IP_ADDRESS> To view status: sudo csf -l To restart: sudo csf -r Setting Up Alerts in CSF Activating notifications allows the admins of the server to get timely updates on important events, such as IP blocks, failed login attempts, and other security incidents. These are important in quickly detecting, as well as addressing safety risks. Below is the explanation about setting up notifications via email. Updating the Configuration File Use a text editor like Nano to open the tool’s main configuration file by writing: sudo nano /etc/csf/csf.conf Search for the line starting with LF_EMAIL_ALERT. This setting determines whether CSF sends email notifications. LF_EMAIL_ALERT = "0" Change the value from 0 to 1 to enable email notifications. LF_EMAIL_ALERT = "1" Find the LF_ALERT_TO option in the file, which defines the recipient email for alerts. Add the preferred email here: LF_ALERT_TO = "[email protected]" Define email of the sender by utilizing the option LF_ALERT_FROM. The notifications will be sent from this email address: LF_ALERT_FROM = "[email protected]" Press CTRL + O to save changes and CTRL + X to exit Nano. Restart CSF and LFD: sudo csf -rsudo systemctl restart lfd Customizing Alert Types You can customize which types of events would trigger email notifications. A few common options in the config are below: Login Failures: Controlled by LF_ALERT_LOGIN. Blocked IP Alerts: Enabled by LF_EMAIL_ALERT. Excessive Resource Usage: Configured via LF_ALERT_RESOURCE. For example, to enable login failure notifications, set: LF_ALERT_LOGIN = "1" Benefits of Email Notifications Real-Time Monitoring: Immediate awareness of suspicious activities or potential threats. Quick Response: Reduces the time between detecting and mitigating safety issues. Audit Trail: Email warnings provide a record of important safety events. By enabling notifications, it becomes an even more proactive tool in managing server safety. Example: Configuring CSF for WordPress Here's how to configure CSF to meet the requirements for a server hosting WordPress (WP), MySQL, and Redis: 1: Open the CSF configuration file: sudo nano /etc/csf/csf.conf 2: Allow endpoints 80 (HTTP) and 443 (HTTPS). These are required for serving the WordPress site. Find the line that starts with TCP_IN and modify it as follows: TCP_IN = "22,80,443,3306,6379" Explanation: 22: SSH access 80: HTTP for WordPress 443: HTTPS for WordPress 3306: MySQL gateway 6379: Redis gateway 3: Add a custom rule to limit interaction to Redis (port 6379) from the internal network only. Find the csf.allow file and add: 192.168.1.0/24 6379 # Internal network access to Redis Replace 192.168.1.0/24 with your internal network's CIDR notation. 4: Restrict MySQL connectivity. Allow MySQL authorization from internal network. In the csf.allow file, add: 192.168.1.0/24 3306 # Internal network access to MySQL Allow MySQL access from an external developer IP. In the same csf.allow file, add: 203.0.113.5 3306 # Developer IP access to MySQL Replace 203.0.113.5 with the developer's external IP address. 5: Restrict SSH Access. To allow SSH visibility only from a specific subnet, add the subnet to csf.allow: 192.168.1.0/24  # SSH access from the specific subnet Also, explicitly deny SSH visibility from all other IPs in csf.deny: ALL 22 # Block SSH for all except explicitly allowed IPs 6: Apply changes by restarting CSF and LFD: sudo csf -rsudo systemctl restart lfd 7: Verify that the connections points are correctly opened: sudo csf -l Check specific IP connectivity using: csf -g <IP_ADDRESS> Conclusion Using ConfigServer Security & Firewall on Ubuntu 22.04 LTS significantly improves the safety of the server. Along with its advanced functions like managing gateways, DDoS protection, and warnings in real-time, it also provides a comprehensive solution for safeguarding servers of Linux. To find more about different options and settings of this tool, check its official website. By utilizing this guide, you'll establish a robust firewall infrastructure capable of defending against modern cyber threats while maintaining optimal server performance. In addition, you can install Ubuntu on our cloud VPS server.
21 January 2025 · 9 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support