Keep your Raspberry Pi secure with a firewall

Learn how to install and configure a firewall on your Raspberry Pi for enhanced security. …


Updated October 10, 2023

Need help with your Raspberry Pi?
Contact Me!

Do you love silly Raspberry Pi Projects?
Check out my this YouTube Channel!


Learn how to install and configure a firewall on your Raspberry Pi for enhanced security.

A firewall is an essential security tool for protecting your Raspberry Pi from unauthorized access or attacks. In this article, we’ll walk you through the process of installing and configuring a firewall on your Raspberry Pi using UFW (Uncomplicated Firewall), which is a user-friendly interface for managing iptables rules.

Installing UFW

First, make sure your Raspberry Pi is up to date:

sudo apt update && sudo apt upgrade

Then, install UFW using the following command:

sudo apt install ufw

Enabling UFW

After installation, enable UFW by running:

sudo ufw enable

UFW is now active and will start filtering incoming connections. By default, it denies all incoming traffic and allows all outgoing traffic. This means that your Raspberry Pi can communicate with the outside world, but no one else can access its services or ports unless you explicitly allow them.

Allowing Incoming Traffic

If you want to allow incoming traffic on a specific port, use the following command:

sudo ufw allow <port_number>

For example, if you’re running a web server on port 80, you would run:

sudo ufw allow 80

You can also specify the protocol (TCP or UDP) like this:

sudo ufw allow <port_number>/<tcp|udp>

To open a range of ports, use the following syntax:

sudo ufw allow <start_port>:<end_port>

For example, to open ports 80 and 443 (HTTP and HTTPS) you would run:

sudo ufw allow 80,443

Or, to open a range of UDP ports from 10000 to 2000:

sudo ufw allow 10000:2000/udp

Denying Incoming Traffic

If you want to block specific incoming traffic, use the deny command instead of allow:

sudo ufw deny <port_number>

For example, if you don’t want anyone connecting via SSH on port 22:

sudo ufw deny 22

Checking UFW Status

To check the status of your firewall and its rules, run:

sudo ufw status

This will show you a list of all active rules.

Disabling UFW

If you need to temporarily disable UFW for troubleshooting or maintenance purposes, use:

sudo ufw disable

And enable it again with sudo ufw enable when done.

Conclusion

By installing and configuring a firewall on your Raspberry Pi using UFW, you’ve taken an important step toward securing your device and its services. With this in place, your Raspberry Pi will only accept connections on the ports you specifically allow, making it much harder for hackers to gain unauthorized access or exploit vulnerabilities.