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

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
Ubuntu

How to Set Up a Firewall with UFW on Ubuntu

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. 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.  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. 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. Updating System Packages The following code is to be written in terminal to update system packages of Ubuntu: sudo apt-get updatesudo apt-get upgrade 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.) 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 updatesudo 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 httpsudo ufw allow https Or: sudo ufw allow 80/tcpsudo 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.100sudo 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.1sudo 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: 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. 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. 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. 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. 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. 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. 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. 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. 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. 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.
02 April 2024 · 10 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