Sign In
Sign In

How to Configure a Firewall with Firewalld

How to Configure a Firewall with Firewalld
Adnene Mabrouk
Technical writer
Firewall Linux
24.09.2024
Reading time: 7 min

Firewalld is a dynamic firewall management tool for Linux systems, providing a user-friendly interface to define rules for controlling network traffic. It offers a high level of flexibility by supporting network zones, services, and ports, allowing administrators to tailor network security according to specific needs. Unlike traditional static firewall tools such as iptables, Firewalld allows for real-time modification of firewall settings without interrupting active connections.

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

Installation of Firewalld

Firewalld is often included by default in many Linux distributions like Fedora, CentOS, and RHEL. However, if it’s not installed on your system, you can easily do so using your package manager.

For CentOS/RHEL:

sudo yum install firewalld

For Ubuntu/Debian:

sudo apt install firewalld

After installation, ensure the package is updated to the latest version:

For CentOS/RHEL:

sudo yum update firewalld

For Ubuntu/Debian:

sudo apt update firewalld

Starting and Enabling Firewalld

Once installed, Firewalld must be started and enabled to automatically start at boot.

Start the Firewalld service:

sudo systemctl start firewalld

Enable Firewalld to start at boot:

sudo systemctl enable firewalld

Check the status of Firewalld:

sudo systemctl status firewalld

The output looks like this:

Image1

Basic Concepts: Zones, Services, and Ports

Firewalld operates around three key concepts: zones, services, and ports.

  • Zones: Zones define trust levels for incoming traffic. Firewalld comes with predefined zones like public, home, internal, dmz, and drop. Each zone has specific rules determining how traffic from different network interfaces is handled. For example, traffic in the public zone may be restricted to a few essential services, while traffic in the home zone can allow more access.

    • Public Zone: This zone is used for networks where you don’t trust other computers on the network (e.g., a café’s Wi-Fi). Traffic is restricted to a few essential services, such as SSH, which allows secure remote access. For example, in the public zone, only SSH (port 22) and HTTPS (port 443) may be allowed, blocking all other incoming requests. You might allow:

sudo firewall-cmd --zone=public --add-service=ssh --add-service=https --permanent
    • Home Zone: This zone is designed for home networks, where you trust the devices connected. In this zone, you may allow more services like file sharing (SMB or NFS), media servers, and printers, alongside SSH and HTTPS. For example, you could allow:

sudo firewall-cmd --zone=home --add-service=samba --add-service=nfs --add-service=ssh --add-service=https
    • Internal Zone: This is typically used for networks inside your organization, like a private LAN. It can have even more relaxed rules since it's generally assumed the network is trusted. You might allow database connections (MySQL or PostgreSQL), in addition to file sharing and basic services:

sudo firewall-cmd --zone=internal --add-service=mysql --add-service=postgresql --add-service=samba
    • DMZ (Demilitarized Zone): This zone is for systems that are exposed to the public internet, but should be isolated from your internal network for security reasons. Services that need to be publicly available, like web servers or FTP, are allowed here, but internal services like file sharing remain restricted. For example:

sudo firewall-cmd --zone=dmz --add-service=http --add-service=ftp
    • Drop Zone: In the drop zone, all incoming network connections are dropped without any notification, making it the most restrictive zone. This is used when you want to ensure that no communication is allowed except outgoing traffic. For example, if an interface is assigned to this zone, no services are allowed, and all incoming packets are simply discarded:

sudo firewall-cmd --zone=drop --set-target=DROP --permanent
  • Services: Services represent predefined protocols, such as SSH, HTTP, or DNS, and are defined in XML configuration files. Firewalld can allow or block these services in different zones without having to know specific port numbers.

  • Ports: Instead of relying on predefined services, administrators can directly open or close specific ports using Firewalld, allowing more granular control over network access.

Assigning Zones to Interfaces

To assign a zone to a specific interface (e.g., eth0), you can use the following command:

sudo firewall-cmd --zone=public --change-interface=eth0

In this example, we assign the public zone to the eth0 interface. All rules associated with the public zone (such as blocking non-essential services) will now apply to traffic passing through eth0.

Let’s walk through an example of assigning different zones to different interfaces based on their network type.

  1. Check Active Interfaces and Zones

To see which zones are currently assigned to your interfaces, run:

sudo firewall-cmd --get-active-zones

This will display a list of interfaces and the zones currently assigned to them.

  1. Assigning the Public Zone to an External Interface (eth0)

If eth0 is your external network interface connected to the internet, you might want to assign it to the public zone to restrict access to only critical services like SSH and HTTPS:

sudo firewall-cmd --zone=public --change-interface=eth0

You can also verify the configuration by listing the current zone settings for eth0:

sudo firewall-cmd --zone=public --list-all
  1. Assigning the Internal Zone to a Local Network Interface (eth1)

If eth1 is connected to a trusted internal network (such as a private LAN), you might want to assign it to the internal zone, where more services like file sharing or databases can be allowed:

sudo firewall-cmd --zone=internal --change-interface=eth1

This allows more open access to trusted devices on the network while keeping other external traffic restricted.

Allowing and Denying Services and Ports

With Firewalld, you can allow or deny services and ports using simple commands.

Allowing Services:

To allow a service (like HTTP) in a specific zone (like the public zone):

sudo firewall-cmd --zone=public --add-service=http

Allowing Ports:

To allow specific ports (e.g., port 8080) in the public zone:

sudo firewall-cmd --zone=public --add-port=8080/tcp

Denying Services or Ports:

To remove an allowed service:

sudo firewall-cmd --zone=public --remove-service=http

To remove an allowed port:

sudo firewall-cmd --zone=public --remove-port=8080/tcp

Permanent and Runtime Configuration

Firewalld has two modes of operation: runtime and permanent.

  • Runtime Configuration: Changes apply immediately but are lost after a reboot or Firewalld restart.

  • Permanent Configuration: Changes are saved and applied after reboots or service restarts.

By default, commands apply only to the runtime configuration. To make changes permanent, use the --permanent option.

Making Rules Permanent:

sudo firewall-cmd --zone=public --add-service=http --permanent

After making permanent changes, reload Firewalld to apply them:

sudo firewall-cmd --reload

Verifying Firewall Rules

To verify that your firewall rules are applied correctly, Firewalld provides several commands.

List all active zones:

sudo firewall-cmd --get-active-zones

Check the services and ports allowed in a particular zone:

sudo firewall-cmd --zone=public --list-all

To makeruntime permanent settings:

sudo firewall-cmd --runtime-to-permanent

Best Practices for Securing Firewalls

  1. Least Privilege Access: Only allow services and ports that are absolutely necessary. Close unnecessary ports to minimize attack vectors.

  2. Use Default Drop Policy: Set the default zone to drop or block to deny incoming traffic by default unless explicitly allowed.

  3. Enable Logging: Turn on logging to monitor traffic and detect unusual patterns.

sudo firewall-cmd --set-log-denied=all
  1. Regular Rule Review: Periodically review and update firewall rules to adapt to new services or evolving security requirements.

  2. Segmentation via Zones: Assign different interfaces to different zones based on their trust level, like using the internal zone for a private network and the public zone for external connections.

Conclusion

Firewalld offers a robust and flexible framework for managing Linux firewall rules, allowing you to define policies dynamically using zones, services, and ports. By understanding how to install, configure, and verify Firewalld settings, you can effectively secure your Linux systems (you can try our Linux VPS server). Additionally, following best practices such as limiting access, enabling logging, and routinely reviewing rules will help fortify your firewall defenses against potential threats.

Firewall Linux
24.09.2024
Reading time: 7 min

Similar

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
Ubuntu

How to Configure Uncomplicated Firewall (UFW) on Ubuntu 24.04

Setting up a firewall is one of the fundamental steps in safeguarding an Ubuntu 24.04 installation. Security is an important part of running any server or system. A firewall restricts which services are permitted to communicate with the server, thus acting as a barrier between the system and any potential threats. On Ubuntu, the Uncomplicated Firewall (UFW) offers an intuitive frontend for controlling firewall rules. It makes setting up iptables, the robust but intricate underlying firewall mechanism, easier. UFW makes it simple to set up and manage their firewall settings, even if they have little experience with networking concepts. This increases system security without requiring a high level of technical expertise. With the help of this article, you will be able to install, configure, and manage UFW on Ubuntu 24.04, protecting the server from undesirable network traffic while maintaining the seamless operation of authorized services. Hostman offers a cloud managed firewall that provides cutting-edge defense tailored for businesses of all sizes. Prerequisites A local computer or a cloud server with Ubuntu 24.04 installed Root access or user with sudo privileges Installing UFW On Ubuntu 24.04, installing the Uncomplicated Firewall (UFW) is straightforward. Normally, Ubuntu has it pre-installed, but if it's not, one may easily install it on the machine by following the instructions below: Update the package lists to ensure to have the most recent information on package versions and dependencies. Run the command below:  sudo apt update && sudo apt upgrade -y The below command can be used to install UFW on the machine. sudo apt install ufw -y Once installation is complete, the default status of UFW is inactive. Check it using the command below: sudo ufw status Enabling UFW You must enable UFW beforehand to begin securing the system. When UFW is enabled, it will begin enforcing both its default rules and any custom rules that have been established. If you are configuring a remote server, make sure to allow SSH connections before starting UFW, to avoid locking users out. Now that UFW is installed and operational, you can start creating firewall rules that meet the unique security needs.  Enable UFW using the command below and type "y" to proceed. sudo ufw enable Allowing SSH Connections Enabling the firewall before enabling SSH connections is crucial when deploying UFW on a server, particularly if if administering it remotely over SSH. SSH blocking may prevent you from accessing the server and render it unusable.  On Ubuntu 24.04, you can enable SSH connections by following these steps: It is easy to permit SSH traffic using UFW. Use the following command to enable it. sudo ufw allow ssh To confirm that the rule was successfully added, check the status of UFW by running thecommand below. sudo ufw status If the SSH service is operating on a non-standard port, you can choose that port instead of the default by issuing the following command. sudo ufw allow <custom_port>/tcp Understanding UFW Default Policies It's critical to learn about the default policies that UFW applies to incoming, outgoing, and forwarded traffic before digging into custom firewall rules. These default policies provide the firewall's baseline behavior, which can subsequently be adjusted with particular rules to permit or prohibit particular kinds of traffic.  UFW prevents all incoming connections to the server by default. This security precaution keeps unwanted users from accessing the system.  Any request that comes in from outside the system will be rejected unless a particular rule is configured to authorize it. Requests for SSH, FTP, HTTP, and HTTPS are included in this.  By default, UFW permits all outgoing connections. This implies that there are no restrictions on the connections the server can make to other servers or services. Because outgoing traffic is normally safe, this policy allows the server to access the internet, download updates, and connect to other services without requiring any additional settings. Since UFW's default forwarding policy is set to refuse, all forwarded traffic is blocked. Packets that are received by the firewall and subsequently forwarded to a different location are referred to as forwarded traffic. This is especially important for systems that serve as gateways or routers. The server must modify this policy if it is intended to forward traffic between networks. Allowing and Denying Specific Ports and Services The ability of UFW to simply control which ports and services are granted or denied access to the system is one of its main features. This feature is necessary to secure the Ubuntu 24.04 server and manage traffic. Using UFW, you can use this method to enable or block particular ports and services. To enable traffic on a specific port, run the ufw allow command followed by the port number. In this example, to allow http (port 80), run the command below. sudo ufw allow 80/tcp To allow https (port 443), run the command below. sudo ufw allow 443/tcp If a non-standard port is used by the application, the port can also specify using the command below. sudo ufw allow <custom_port>/tcp For example: sudo ufw allow 3026/tcp Traffic on port 3026, which is frequently used for database configurations, is now permitted. Likewise, in order to prevent access, you can restrict traffic on a particular port, run the command below. sudo ufw deny 80/tcp Checking UFW Status and Rules After configuring Ubuntu 24.04's UFW (Uncomplicated Firewall), it's critical to frequently check the firewall's status and go over the rules that have been set up. By doing this, you can be sure the firewall is up and running as it should. To inspect the current firewall rules and verify the status of UFW, run the following command:  sudo ufw status Managing UFW Application Profiles Predefined application profiles included in Ubuntu 24.04's UFW (Uncomplicated Firewall) make it easier to grant or restrict traffic for particular services. Firewall management is made easier by these profiles, which include preconfigured rules for popular services including SSH, POSTIFX, OPENSSH, HTTP, HTTPS, and others. Managing UFW application profiles can be done as follows. Use the following command to view every application profile that is available on the system. sudo ufw app list Use the below command to view the rules included in a particular application profile. The ports and protocols that the profile controls will be displayed in the output. sudo ufw app info <application_name> For example: sudo ufw app info OpenSSH The application profile that you wish to use can be allow with UFW once it has been identified. For instance, use the following command to enable HTTP traffic. sudo ufw allow http Likewise, the deny command can be used to prevent traffic for a certain application profile. For example, use the following command to stop all communication related to the HTTP. sudo ufw deny http If a rule related to an application profile is no longer required, it can be deleted using the following command: sudo ufw delete allow http Disabling UFW Even though Ubuntu 24.04's UFW (Uncomplicated Firewall) is an effective tool for controlling firewall rules and system security, there may be circumstances in which it needs to be turned off, either permanently or temporarily. Unless another firewall or security solution is in place, disabling UFW will halt the firewall and erase all active rules, leaving the system unsecured. To disable UFW, run the below command. By using this command, you can successfully turn off the firewall and stop the UFW service.  sudo ufw disable Use the command below to verify that UFW has been successfully disabled. The status output should show below. sudo ufw status Troubleshooting Common Issues Although UFW (Uncomplicated Firewall) is meant to be user-friendly, there could be some problems with installation or firewall rule management. Here are some typical issues that may run into and solutions for issues. If UFW is not listed on the installed packed, try reinstalling it by running sudo apt update and sudo apt install ufw respectively. If the installation fails to install, look for issues in your sources or package management. You can also try apt update and apt clean. Conflicting firewall service. Before activating UFW, make sure that all other firewall services, such as firewall and iptables, have been stopped and deactivated. For further information, review the UFW logs if the issue continues. Useful command is sudo tail -f /var/log/ufw.log. Once UFW is enabled, you cannot connect remotely to the server and SSH access is restricted. If the you are locked out due to UFW blocking SSH, you need to access the server on the console and run command sudo ufw allow ssh to regain access. Conclusion In conclusion, one of the most important steps in protecting Ubuntu 24.04 is configuring the Uncomplicated Firewall (UFW), which controls inbound and outbound network traffic. Because of its intuitive interface, UFW makes firewall control simple enough even for individuals with little experience with Linux system administration. You can effectively control traffic to and from the server by following the instructions to install UFW, create default policies, allow or deny certain ports and services, and manage application profiles. Monitoring the firewall rules and UFW status on a regular basis guarantee that the system is always shielded from unwanted access. Whether it's administering a production environment or protecting a personal server, UFW offers a reliable and simple way to improve the security of the system. By adding the capability to diagnose common problems, one can keep the firewall configuration secure and effective for what is needed.
21 August 2024 · 8 min to read
CentOS

Configuring Firewalld on CentOS

Firewalld is a firewall management tool that comes pre-installed on most RHEL-based distributions. In this article, we will look at setting up a firewall with firewalld on a CentOS server using the firewall-cmd utility. Prerequisites To follow this guide, you will need: A cloud server running CentOS A root user or a user with sudo privileges What is firewall? A firewall is a program for access control at the network level. Based on the set up rules, the firewall determines which devices can access this or that part of the network, which traffic is allowed and which is blocked. In Linux, these functions are performed by the netfilter program built into the kernel. So, netfilter works at the kernel level. To configure the firewall, you need tools in user space. ip_tables/nf_tables, implemented as kernel modules, are used as frameworks for managing netfilter. And on top of them, at the user level, either iptables or nft are used. Experienced system administrators know that manually writing rules for iptables or nft is not so easy, especially when you need to set up a large network or transfer rules to another system. That's where more user-friendly and feature-rich add-ons come into play. For example, in Ubuntu such an add-on is a tool with the self-explanatory name ufw (Uncomplicated Firewall). And in RedHat distributions (CentOS, Alma, Fedora, RHEL, OpenSUSE, SUSE Linux Enterprise), it is firewalld. Our cloud-based firewall provides cutting-edge defense tailored for businesses of all sizes. Working with firewalld There are two programs to manage firewalld: firewall-cmd for working in the terminal and firewall-config GUI.  In this article, we will work with firewall-cmd. Installation Connect to your server and check the service status: sudo systemctl status firewalld As mentioned before, in RHEL-based distributions, firewalld is pre-installed. If you wish to use it on Ubuntu/Debian, you can easily install it manually:  sudo apt install firewalldsudo systemctl enable firewalld --now Don't forget to disable ufw, as using two utilities for iptables/nftables may cause issues. Active rules Check the existing active rules by using the command: sudo firewall-cmd --list-all Note that you need superuser privileges for this, so log in as root or use sudo/su. In the command output you can see many different parameters. Let's look at them in order. Configuring ports The ports field shows the ports on which connections are allowed.  To better understand how it works, let's change the listening port of the OpenSSH daemon from 22 to 3333 in the /etc/ssh/sshd_config file: Port 3333#AddressFamily any#ListenAddress 0.0.0.0#ListenAddress :: sudo systemctl restart sshd List the ports listened by sshd: sudo ss -nl4p | grep sshd Output: tcp LISTEN 0 128 *:3333 *:* users:(("sshd",pid=7602,fd=3)) As you can see, the port 3333 is now listening. The current session has not been interrupted, but if we try to connect again using the standard or new port, we won't be successful: ssh [email protected]: connect to host 166.1.227.252 port 22: Connection refused ssh [email protected] -p 3333ssh: connect to host 166.1.227.252 port 3333: No route to host You need to add an allowing rule to firewalld that allows you to connect via 3333/tcp: sudo firewall-cmd --add-port=3333/tcp Or: sudo firewall-cmd --add-port=3333/tcp --permanentsudo firewall-cmd --reload In the first case, the changes are active only in the current runtime, and when the machine or service is restarted, everything is reset. In the second case, the --permanent flag indicates that we are changing the settings permanently, so you need to restart the firewall (the --reload option). Let's check which ports are now allowed: sudo firewall-cmd --list-ports Output: 3333/tcp Now everything works: ssh [email protected] -p [email protected]'s password: You might wonder how we managed to connect via SSH earlier, as at first the ports field in the policy output was empty. The fact is that the settings were specified using service descriptions. Configuring services Services in firewalld are service descriptions that make configuration more convenient and centralized. Let's look up the current services and information about them: sudo firewall-cmd --list-services sudo firewall-cmd --info-service=ssh Note that SSH still has port 22. The fact is that the daemons' own parameters are in no way related to their descriptions in firewalld. Let's try to remove the standard port and add 3333 to the ssh service description (don't forget to remove port 3333/tcp from the policies): sudo firewall-cmd --service=ssh --remove-port=22/tcp --permanentsudo firewall-cmd --remove-port=3333/tcp --permanentsudo firewall-cmd --service=ssh --add-port=3333/tcp --permanentsudo firewall-cmd --reload Now let's check again: sudo firewall-cmd --info-service=ssh Let's try to remove and add a service: sudo firewall-cmd --remove-service=dhcpv6-clientsudo firewall-cmd --add-service=mysqlsudo firewall-cmd --runtime-to-permanent Check the list of services: sudo firewall-cmd --list-services The --runtime-to-permanent option makes the runtime permanent. You don't have to specify --permanent after each command, but execute a set of commands and only after that make the settings permanent (please note that it does not always work since some commands require the --permanent option). Files with predefined services are located at /lib/firewalld/services. Let's list them: sudo firewall-cmd --get-services You can create your own services. To do this, create an .xml file in the /etc/firewalld/services directory. For convenience, you can copy a configuration from /etc/firewalld/services and make the necessary changes. Then restart the firewall with the --reload flag. ICMP, protocols and targets The output of --list-all has the following fields: sudo firewall-cmd --list-all | grep -E '(target|icmp|protocols)' In firewalld, you can configure not only services and ports, but also protocols. Let's say we set up a firewall on a router. It makes sense to indicate a list of allowed protocols. To illustrate, let's enable the OSPF dynamic routing protocol: sudo firewall-cmd --add-protocol=ospfsudo firewall-cmd --list-protocols The icmp-blocks and icmp-blocks-inversion fields contain parameters for the ICMP protocol used for network testing and error notifications. It is used by ping and traceroute utilities. Using icmp-blocks you can block specific ICMP messages. The icmp-blocks-inversion inverts the logic, as in the listed message types become allowed and the rest are blocked. This functionality can be used to hide network information since many scanning engines use ICMP. Let's test the blocking using the ping utility. Prohibit all types of ICMP messages (since nothing is listed in icmp-block, all messages become prohibited): sudo firewall-cmd --add-icmp-block-inversion Now let's try to ping the server: ping -c 3 166.1.227.252PING 166.1.227.252 (166.1.227.252) 56(84) bytes of data.From 166.1.227.252 icmp_seq=1 Destination Host ProhibitedFrom 166.1.227.252 icmp_seq=2 Destination Host ProhibitedFrom 166.1.227.252 icmp_seq=3 Destination Host Prohibited--- 166.1.227.252 ping statistics ---3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2004ms The machine does not respond to ping. This method is often used by providers to hide router addresses. However, it is clear from the errors that the packets on the target devices are being filtered by the firewall. To hide your computer, you need to use targets. A target is an action that needs to be done with the package if any of the rules are triggered. The most used are DROP, ACCEPT, REJECT. In the example above, the target was REJECT, i.e. returning the reason for the error. To drop a packet without sending anything, you need to use DROP: sudo firewall-cmd --set-target=DROP --permanentsudo firewall-cmd --reload Let's ping the server again: ping -c 3 166.1.227.252PING 166.1.227.252 (166.1.227.252) 56(84) bytes of data.--- 166.1.227.252 ping statistics ---3 packets transmitted, 0 received, 100% packet loss, time 2050ms Zones When working with firewalld, zones are often used. A machine may have multiple interfaces: one for Internet, another for LAN, and third for dmz. Different networks have different levels of trust, and traffic coming from them must be controlled by different firewall rules. To achieve this, firewalld uses zones, sets of rules that apply to different parts of the network. All the firewall rules we configured above were applied for the public zone (by default): sudo firewall-cmd --get-default-zone Firewalld initially contains several zones. However, you can create your own zones. Let's display a list of available zones: sudo firewall-cmd --get-zones The --zone option allows you to set and view rules for a specific zone (without it, everything is applied to the default zone). Let's look at the policies for the drop zone: sudo firewall-cmd --list-all --zone=drop In our case, the interface eth0, which provides access to the Internet, is in the public zone. This means that the policies of the public zone are applied to incoming traffic. To add the interface to another zone, use the --change-interface switch. Let's move our eth0 to the home zone: sudo firewall-cmd --change-interface=eth0 --zone=homesudo firewall-cmd --list-interfaces --zone=home Sometimes, you may need to configure traffic rules for a specific address. It's done like this: sudo firewall-cmd --zone=drop --add-source=192.168.3.1 Now check: sudo firewall-cmd --zone=drop --list-all Now, even if packets from the address 192.168.3.1 arrive on the eth0 interface, the rules will be applied not for the zone in which the interface is located, but for the zone we manually specified (drop).  NAT setup NAT stands for Network Address Translation. There are two types of NAT: source and destination. In the first case, the router replaces home IP addresses with its external ones, i.e. changing the sender's (source) address. In Linux, this is called masquerade. In the second case, the recipient address is replaced (port forwarding). For example, a packet arrives at the router port, and the router forwards the packet to some other port. Let's say you need to configure a firewall on a router. Enable masquerading: sudo firewall-cmd --add-masquerade Run --list-all: sudo firewall-cmd --list-all Enable port forwarding: sudo firewall-cmd --add-forward-port=port=3333:proto=tcp:toport=22sudo firewall-cmd --list-all You may also notice the source-ports option. Firewalld can allow specific outgoing ports, but this is rarely used since dynamic 5-digit ports are usually used as source ports. Rich rules We looked at how to use different firewalld rules for different network areas (interfaces, IP addresses). But sometimes you need to create very distinctive rules, like allowing connections from a specific address to a specific port, using such and such protocols, etc. Of course, you can create your own zone, but it may be better to use rich-rules. Rich-rules in firewalld have a different syntax which you can find in the manual: man firewalld.richlanguage It also provides many examples. And that's how you add a rich-rule manually: sudo firewall-cmd --add-rich-rule=’rule' Conclusion A properly functioning firewall greatly improves network security. In this article, we looked at the basics of working in firewalld, which are necessary for proper configuration. Firewalld allows you to easily divide your network into sections and set your own security policies for each section.
27 May 2024 · 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