1. Check the firewalld status

Check whether firewalld is installed and running:

sudo firewall-cmd --state

If it is running, check the active zones:

sudo firewall-cmd --get-active-zones

Display the configuration of the active zone:

sudo firewall-cmd --list-all

If firewalld is not installed, install it using:

sudo apt update sudo apt install firewalld

Important: Installing or starting a firewall may affect existing network access. 

Review your current firewall configuration and ensure you have a recovery method before proceeding.

2. Identify your SSH port

The default SSH port is 22, unless it has been changed.

To check the SSH listening port, run:

sudo sshd -T | grep '^port '

Example output:

port 22

If your SSH service uses a custom port, use that port in the following steps instead of 22.

3. Allow SSH traffic

Before enabling or applying firewall restrictions, ensure that SSH is allowed in the appropriate firewall zone.

First, check the default zone:

sudo firewall-cmd --get-default-zone

For a server using the default SSH port, allow the SSH service permanently in the intended zone:


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

If SSH uses a custom port, replace 22 with your actual port:

sudo firewall-cmd --permanent --zone=public --add-port=2222/tcp

The above custom-port example assumes SSH is listening on port 2222.

Note: The public zone is an example. 

If your SSH interface belongs to another zone, apply the rule to the appropriate zone instead. 

Do not assume that every VPS uses the same zone or SSH configuration.

4. Enable firewalld

Once you have confirmed the SSH rules and reviewed the required application ports, enable the firewall:

sudo systemctl enable --now firewalld

Check the service status:

sudo systemctl status firewalld

Check whether the firewall is running:

sudo firewall-cmd --state

Expected output:

running

Warning: If the firewall is already active, avoid restarting or changing its configuration without reviewing the existing rules first.

5. Apply and verify the firewall rules

After configuring the required permanent rules, reload the firewall:

sudo firewall-cmd --reload

Check the active zones:

sudo firewall-cmd --get-active-zones

Review the rules for the relevant zone:

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

Check the permanent configuration:

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

Confirm that SSH and any required application services are allowed.

6. Test SSH connectivity

Keep your current SSH session open.

Open a new terminal window on your local computer and attempt to connect to the VPS again:

ssh root@YOUR_VPS_IP

If you are using a custom SSH port:

ssh -p 2222 root@YOUR_VPS_IP

Replace the example IP address and port with your actual VPS details.

Only consider the firewall configuration complete after confirming that you can establish a new SSH connection and that the required services remain accessible.