# Firewall  in LINUX - Ubuntu & CentOs

## WHAT IS FIREWALL?

A firewall is a network security device or software that acts as a barrier between a trusted internal network and untrusted external networks, such as the Internet. Its primary purpose is to monitor and control incoming and outgoing network traffic based on predefined security rules. Firewalls play a critical role in enhancing network security by enforcing policies that prevent unauthorized access, protect against cyber threats, and ensure the confidentiality, integrity, and availability of network resources.

## How Firewall Work?

A **firewall decides which network traffic is allowed to pass through and which traffic is deemed dangerous.** Essentially, it works by **filtering out the good from the bad,** or **the trusted from the untrusted.**

Firewalls are intended to secure private networks and the endpoint devices within them, known as network hosts. Network hosts are devices that ‘talk’ with other hosts on the network.

## What is a firewall in Linux?

In Linux, a firewall is a software-based security mechanism that controls incoming and outgoing network traffic on a system. It regulates the flow of network packets based on predefined rules, helping to protect the system from unauthorized access, malicious activities, and potential security threats.

## **Tools for using a firewall in Linux?**

These tools can help you configure, monitor, and manage firewall rules to enhance the security of your network.

### **iptables**:

`iptables` is the standard firewall management tool for Linux. It allows you to configure and manage firewall rules in a granular way. While it has a steeper learning curve compared to UFW and Firewall d, it provides more fine-grained control over network traffic.

### **Uncomplicated Firewall (UFW)**:

UFW is a user-friendly front for **tables** that simplifies the process of configuring firewall rules. It is designed to be easy to use and is great for users who are new to firewall management. UFW provides a simplified command-line interface for managing rules and supports application profiles.

### **Firewall d**:

`Firewall d` is another user-friendly firewall management tool that focuses on dynamically managing firewall rules. It is commonly used on systems running Red Hat-based distributions (like CentOS and Fedora). Firewalld uses zones and services to manage network access. It also supports runtime changes without disrupting active connections.

### **nftables:**

`nftables` is a modern replacement for `iptables` that offer better performance and more flexibility. It provides a consistent framework for packet filtering and network address translation. `nftables` is often used on newer Linux distributions.

## **How to set up a firewall on Ubuntu?**

firewall on Ubuntu is a good way to enhance the security of your system by controlling incoming and outgoing network traffic.

The default firewall management tool for Ubuntu is called `ufw` (Uncomplicated Firewall), which provides a simplified interface for managing `iptables`, the standard firewall management tool for Linux.

### Steps to install and use `ufw` to set up a firewall on Ubuntu:

### Step 1:

you can update it using the following command:

```plaintext
sudo apt update
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691592282000/cb410bd4-54fe-4ff9-bb0b-d0918a769090.png align="center")

### Step 2:

you can install it using the following command (In my case it is already Installed):

```plaintext
sudo apt install ufw
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691592479715/deabf0f3-e7cf-4f59-bc77-257a7f9b0e16.png align="center")

### step 3:

**Enable and start** ufw:

After installing `ufw`, you need to enable and start it:

```plaintext
sudo ufw enable
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691634836879/1728922c-d6ed-4d75-a169-4a7e243ccbfb.png align="center")

### step 4:

**Configure** `ufw` rules:

Check the status of the ufw

```plaintext
sudo ufw status
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691639206664/8ea19386-4fcb-433c-9702-75ce36db7504.png align="center")

You can then set up rules to allow or deny specific types of network traffic.

Allow SSH (replace `<port>` with the actual port number):

```plaintext
sudo ufw allow <port>/tcp
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691639326824/3a6102ac-32f0-4c5c-8472-3c50abb32247.png align="center")

Allow HTTP and HTTPS:

```plaintext
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691639433001/510b30f6-6461-401d-bc88-b7b955402c08.png align="center")

Now you can check the status of ufw:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691639515413/06ecc68c-1e20-4b91-9ec6-b10fadab149a.png align="center")

Allow specific port range:

```plaintext
sudo ufw allow 10000:10010/tcp
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691639781597/35fe368b-54a6-4b76-b12c-97f6fbe7ea42.png align="center")

Deny incoming traffic:

```plaintext
sudo ufw default deny incoming
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691640011452/bb488c04-c908-4b7f-8efd-b1aaa813ce94.png align="center")

Allow outgoing traffic:

```plaintext
sudo ufw default allow outgoing
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691640077740/b105a2db-bbf0-43b8-8902-6ad0f1e18282.png align="center")

### **Step 5:**

**Check and enable rules:**

Review the rules you've set up using:

```plaintext
sudo ufw status verbose
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691640143217/a6614932-11da-4743-9626-c138fd7a40d3.png align="center")

### **Step 6:**

**Additional settings:**

* If you're using a server and want to make sure you don't get locked out when enabling the firewall, you can first allow SSH connections and then enable the firewall:
    
    ```plaintext
    sudo ufw allow OpenSSH
    sudo ufw enable
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691640238765/4b173af1-5034-4761-b4a7-0411cde34aa9.png align="center")
    
* To disable the firewall, you can use:
    
    ```plaintext
    sudo ufw disable
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691640324240/297ba0ea-c70e-40e7-aaf4-5f8e19ca5f68.png align="center")

### How to set up a firewall on CentOS?

On CentOS, the default firewall management tool is `Firewalld`. It provides an interface for managing firewall rules and configurations in a dynamic and user-friendly way.

Steps to install and use `ufw` to set up a firewall on CentOS:

**Step 1.**

**Install** `firewalld`

you can install it using the following command:

```plaintext
sudo yum install firewalld
```

```plaintext
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.centos.org
 * extras: mirrors.centos.org
 * updates: mirrors.centos.org
Resolving Dependencies
--> Running transaction check
---> Package firewalld.noarch 0:0.8.3-11.el8_3.1 will be installed
--> Processing Dependency: firewalld-filesystem = 0.8.3-11.el8_3.1 for package: firewalld-0.8.3-11.el8_3.1.noarch
--> Processing Dependency: python3-firewall = 0.8.3-11.el8_3.1 for package: firewalld-0.8.3-11.el8_3.1.noarch
--> Running transaction check
---> Package firewalld-filesystem.noarch 0:0.8.3-11.el8_3.1 will be installed
---> Package python3-firewall.noarch 0:0.8.3-11.el8_3.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================================
 Package                        Arch              Version                       Repository                      Size
========================================================================================================================
Installing:
 firewalld                      noarch            0.8.3-11.el8_3.1              AppStream                      513 k
Installing dependencies:
 firewalld-filesystem           noarch            0.8.3-11.el8_3.1              AppStream                       76 k
 python3-firewall               noarch            0.8.3-11.el8_3.1              AppStream                      507 k

Transaction Summary
========================================================================================================================
Install  3 Packages

Total download size: 1.1 M
Installed size: 4.3 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): firewalld-filesystem-0.8.3-11.el8_3.1.noarch.rpm                                34 kB/s |  76 kB     00:02
(2/3): python3-firewall-0.8.3-11.el8_3.1.noarch.rpm                                    29 kB/s | 507 kB     00:17
(3/3): firewalld-0.8.3-11.el8_3.1.noarch.rpm                                           58 kB/s | 513 kB     00:08
------------------------------------------------------------------------------------------------------------------------
Total                                                                              12 kB/s | 1.1 MB     01:32
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Preparing        :                                                                                          1/1
  Installing       : firewalld-filesystem-0.8.3-11.el8_3.1.noarch                                            1/3
  Installing       : python3-firewall-0.8.3-11.el8_3.1.noarch                                                2/3
  Installing       : firewalld-0.8.3-11.el8_3.1.noarch                                                       3/3
  Running scriptlet: firewalld-0.8.3-11.el8_3.1.noarch                                                       3/3
  Verifying        : firewalld-0.8.3-11.el8_3.1.noarch                                                       1/3
  Verifying        : firewalld-filesystem-0.8.3-11.el8_3.1.noarch                                            2/3
  Verifying        : python3-firewall-0.8.3-11.el8_3.1.noarch                                                3/3

Installed:
  firewalld-0.8.3-11.el8_3.1.noarch                 firewalld-filesystem-0.8.3-11.el8_3.1.noarch
  python3-firewall-0.8.3-11.el8_3.1.noarch

Complete!
```

**Step 2.**

**Enable and start** `firewalld`**:**

After installing `firewalld`, you need to enable and start it:

```plaintext
sudo systemctl enable firewalld
sudo systemctl start firewalld
```

```plaintext

Created symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service → /usr/lib/systemd/system/firewalld.service.
Created symlink /etc/systemd/system/multi-user.target.wants/firewalld.service → /usr/lib/systemd/system/firewalld.service.
```

```plaintext
Job for firewalld.service failed because the control process exited with error code.
See "systemctl status firewalld.service" and "journalctl -xe" for details.
```

**Step 3.**

**Configure** `firewalld` **rules:**

You can then configure rules to allow or deny specific types of network traffic. Here are some common examples:

* Allow SSH (replace `<port>` with the actual port number):
    
    ```plaintext
    sudo firewall-cmd --add-service=ssh --permanent
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691729516194/6d0e6b81-f3b9-4520-a18a-5169a8164bba.png align="center")
    
* Allow HTTP and HTTPS:
    
    ```plaintext
    sudo firewall-cmd --add-service=http --permanent
    sudo firewall-cmd --add-service=https --permanent
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691729586882/996044a0-7907-440f-b9a8-e6a34de90cf5.png align="center")
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691729633005/fdb9c36a-6cf9-4575-a8c2-412378554fbd.png align="center")
    
* Allow a specific port:
    
    ```plaintext
    sudo firewall-cmd --add-port=<port>/tcp --permanent
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691729697148/b290fb35-f0a4-4fa8-b052-60a00a3539e4.png align="center")
    
* Reload the firewall to apply changes:
    
    ```plaintext
    sudo firewall-cmd --reload
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691729725294/d6152c7f-9f30-4d79-a19c-1c72a0bdbb37.png align="center")

**Step 4.**

**Additional settings:**

* To see the active zones and their associated rules:
    
    ```plaintext
    sudo firewall-cmd --list-all
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691645355053/56e650ab-87fa-4aad-973b-684d6bd61339.png align="center")
    
* To see available services:
    
    ```plaintext
    sudo firewall-cmd --get-services
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691647232560/5ce68666-5d1c-4e1d-9033-4a61b1b8cfdd.png align="center")

* To add a custom service:
    
    ```plaintext
    sudo firewall-cmd --add-service=<service-name> --permanent
    sudo firewall-cmd --reload
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691647728551/91ef2316-3e19-4462-89c5-8e0a85fe37cb.png align="center")

**Step 5.**

**Disabling** `firewalld`**:**

If you want to disable `firewalld` temporarily, you can use the following commands:

```plaintext
sudo systemctl stop firewalld
sudo systemctl disable firewalld
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691648036696/e777e202-a9d6-452e-9477-31c7198c6c8d.png align="center")

### Firewall As NGINX?

NGINX involves setting up rules to control incoming and outgoing traffic.NGINX can, however, be used to control and restrict access to certain resources based on IP addresses or other conditions.

to implement firewall rules using NGINX, here are some examples :

### **Install NGINX:**

Ensure that NGINX is installed on your server.

Nginx, you'll need to configure your firewall rules to allow traffic to the ports used by Nginx (typically ports 80 and 443 for HTTP and HTTPS). Here's how you can do it using the Uncomplicated Firewall (UFW) on an Ubuntu-based system:

1. **Check UFW Status**:
    
    Make sure UFW is installed and enabled. You can check the status using:
    
    ```plaintext
    sudo ufw status
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691642246336/17d6e4f4-0e86-492d-bba7-6ad316fa9de5.png align="center")
    
2. **Allow Nginx Ports**:
    
    If you haven't configured any rules yet, you can allow incoming traffic on ports 80 (HTTP) and 443 (HTTPS) for Nginx:
    
    ```plaintext
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691642473800/d4691c3b-536f-4dd6-818a-97df44576c31.png align="center")
    
3. **Enable UFW**:
    
    If UFW is not already enabled, you can enable it:
    
    ```plaintext
    sudo ufw enable
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691642529066/2945cdc0-cdda-4795-85ee-064eec4b8d7a.png align="center")
    
4. **Check Status**:
    
    Verify that the rules are correctly configured:
    
    ```plaintext
    sudo ufw status
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691642578550/aa3ba334-497a-43f4-b8ee-995ee7d1fced.png align="center")
    
5. The output should show that traffic to ports 80, 443, 8080, and 1000:10010 is allowed.
    
6. **Reload Nginx**:
    
    After configuring the firewall, you might need to reload Nginx to apply any changes:
    
    ```plaintext
    sudo systemctl reload nginx
    ```
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1691642696110/5ea3f324-36b8-4c9c-85d1-1d2c01e91aec.png align="center")

Remember, these instructions assume that you're using the default ports (80 and 443) for Nginx. If you've configured Nginx to use different ports, make sure to replace the port numbers in the commands above accordingly.

Additionally, if your server requires other services to be accessible, such as SSH for remote access, you'll need to configure the firewall to allow traffic to those ports as well. Always follow security best practices and limit access only to the necessary services.
