Linux

How to Block Inbound and Outbound Ports Using UFW on Ubuntu Server

UFW (Uncomplicated Firewall) is a user-friendly firewall management tool for Ubuntu that allows administrators to easily control incoming (IN) and outgoing (OUT) network traffic using simple commands.

Blocking Inbound Ports (IN)

Block a Specific Inbound Port

sudo ufw deny 25

Block Multiple Inbound Ports

sudo ufw deny 25,465,587/tcp

Block a Port by Protocol

sudo ufw deny 3306/tcp

Blocking Outbound Ports (OUT) – Highly Recommended

Blocking outbound ports helps prevent spam, data exfiltration, and malware activity on compromised servers.

Block SMTP Outbound Ports

sudo ufw deny out 25
sudo ufw deny out 465
sudo ufw deny out 587

Block Outbound Traffic by Protocol

sudo ufw deny out 25/tcp

Allow Essential Services

sudo ufw allow 22        # SSH
sudo ufw allow 80        # HTTP
sudo ufw allow 443       # HTTPS

Managing UFW Rules

Check Firewall Status

sudo ufw status numbered

Remove a Rule by Number

sudo ufw delete 3

Reload UFW Rules

sudo ufw reload

Enable UFW (If Not Enabled)

sudo ufw enable

UFW Best Practices for Web Servers

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80
sudo ufw allow 443

Then block SMTP outbound ports if email services are not required.

Thanks for visit my website