Firewall

Debian, by default does not install a firewall wrapper such as firewalld or ufw. Rather only the kernel-based packet classification framework nftables is available to control the instance’s network communications.

While no wrapper is provided, Debian does recommend that a wrapper be installed and used. Two possible options that are commonly chosen are firewalld and ufw. firewalld may be more comfortable if your working in a primarily redhat-based environment.

Below is an example of setting UFW, the more popular option for Debian-based systems.

Installation

Install the ufw service.

sudo apt install ufw

/role_name/tasks/main.yml

- name: Install UFW firewall.
  apt:
    name: ufw
    state: latest

Default Configuration

ufw does not come pre-configured with a default firewall policy. Rather a basic policy must be configured and enabled. Run the following commands to build a basic firewall policy.

This policy will:

  • Block all inbound connections.
  • Allow all outbound connections.
  • Accept SSH connections.
sudo ufw default allow outgoing
sudo ufw default deny incoming
sudo ufw allow ssh

/role_name/tasks/main.yml

- name: Allow Outbound Communications.
  community.general.ufw:
    state: enabled
    direction: outgoing
    policy: allow

- name: Deny Inbound Communications.
  community.general.ufw:
    state: enabled
    direction: incoming
    policy: deny

- name: Allow SSH Communications.
  community.general.ufw:
    rule: allow
    name: OpenSSH

To enforce the new firewall policy, and enable UFW for the first time, run ufw enable.

ℹ️
Running the reverse: ufw disable will disable the firewall.
sudo ufw enable

You’ll be asked to confirm that you’d like the firewall enabled. Input Y when ready.

Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

/role_name/tasks/main.yml

- name: Enable Firewall.
  community.general.ufw:
    state: enabled

To view the currently enforced firewall policy.

ufw status

# Output
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)

I recommend looking at Ubuntu’s page for more information on how to add and remove rules in UFW.