If you are opening your Raspberry Pi to the internet then security should be a concern/part of your project design. So today I’m going to look at configuring a software firewall called UFW.
Installing a firewall on the Raspberry Pi (Raspbian) is accomplished easily via the terminal and the following line:
sudo apt install ufw
The above installs the firewall. Before enabling it though, it is recommend to think about what ports you need to have open to access your Raspberry Pi. I’ve bolded your at this point as what ports you need depends on what you are doing on your Pi.
Turning On The Firewall
After installing UFW it needs turning on using the line:
sudo ufw enable
However, before enabling the firewall I would recommend allowing some ports (just in case).
Allowing A Port
Ports are very important, different services uses different ports and it is worth knowing what some of them are. Popular ports include:
- Port 80 – HTTP (for serving web pages)
- Port 443 – HTTPS (for serving secure web pages)
- Port 22 – SSH (needed if you SSH to your Pi)
More information on ports can be found at: https://en.wikipedia.org/wiki/Port_(computer_networking)
Allowing a port is done via:
sudo ufw allow Port_Number
For example sudo ufw allow 443 allows connections to port 443 (HTTPS).
Denying A Port
Just as it is important to allow ports, it is also important to deny ports. Denying a port stops connections to the port, so make sure you don’t deny access to a port you need access to (i.e. if you SSH to your Pi do not deny port 22).
Denying a port is very similar to allowing a port:
sudo ufw deny Port_Number
For example sudo ufw deny 443 would deny 443 (HTTPS).
Viewing Status Of Firewall
To view the status of your firewall (e.g. what is allowed, denyed or limited) enter:
sudo ufw status
UFW will then list all the ports it is allowing/denying/limiting. Note that the (v6) is the IPv6 port. An internet connection generally uses IPv4 but at some point IPv6 should become the standard. I write “at some point” because the transition from IPv4 to IPv6 is a long process. For more information see: https://en.wikipedia.org/wiki/IPv6
Limiting is a great function if you want to allow a port but also want a little security on the port. Limiting allows the port but if multiple connections (6 or more) are attempted in a time frame (30 seconds) then UFW denies the connections. Note: Limiting currently only works on IPv4.
sudo ufw limit ssh/tcp
The above will limit access to ssh.
To enable logging (recommended) enter:
sudo ufw logging on
UFW stores the log under /var/log/ufw.log , if your working on a project and having issues connecting then I recommend viewing the logs to see if your project is using an unexpected port (in which case you may need to allow the port).