Alejandro Muñoz Fernández

UFW Firewall for a Raspberry Pi Server

Recipe to configure the UFW firewall allowing access from outside the home.

1. Default policy: deny all traffic

For security reasons, ideally, both incoming and outgoing traffic should be denied by default, and then only what is needed should be opened.

$ sudo ufw default deny incoming
$ sudo ufw default deny outgoing

2. Allowed traffic

2.1. DNS Outgoing

Essential for the Raspberry Pi to resolve domain names.

$ sudo ufw allow out 53/udp
$ sudo ufw allow out 53/tcp

2.2. NTP

Access to NTP servers to synchronize the system date and time:

$ sudo ufw allow out 123/udp

2.3. Web browsing

Allows outgoing connections from the Raspberry Pi to external web servers:

$ sudo ufw allow out 80/tcp
$ sudo ufw allow out 443/tcp

2.4. FTP Servers

They are rarely used anymore, but just in case (note: active mode requires port 20):

$ sudo ufw allow out 20/tcp
$ sudo ufw allow out 21/tcp

2.5. SSH Servers

Access to the Raspberry Pi’s SSH server only from the local network:

$ sudo ufw allow in from 192.168.1.0/24 to any port 22 proto tcp

Access from the Raspberry Pi to any external SSH server on the internet:

$ sudo ufw allow out 22/tcp

2.6. Samba Servers

To share files on the local network. Only traffic within the LAN is allowed:

$ sudo ufw allow in from 192.168.1.0/24 to any port 137 proto udp
$ sudo ufw allow in from 192.168.1.0/24 to any port 138 proto udp
$ sudo ufw allow in from 192.168.1.0/24 to any port 139 proto tcp
$ sudo ufw allow in from 192.168.1.0/24 to any port 445 proto tcp

$ sudo ufw allow out to 192.168.1.0/24 port 137 proto udp
$ sudo ufw allow out to 192.168.1.0/24 port 138 proto udp
$ sudo ufw allow out to 192.168.1.0/24 port 139 proto tcp
$ sudo ufw allow out to 192.168.1.0/24 port 445 proto tcp

2.7. mDNS

Allows resolution of .local names using Avahi / Bonjour. It uses port 5353 and the multicast address 224.0.0.251:

$ sudo ufw allow in proto udp to 224.0.0.251 port 5353
$ sudo ufw allow out proto udp to 224.0.0.251 port 5353

2.8. RDC (Remote Desktop Connection)

Remote desktop access via the RDP protocol, limited to the local network:

$ sudo ufw allow in from 192.168.1.0/24 to any port 3389 proto tcp

2.9. DHCP (Optional, if using dynamic IP)

If your Raspberry Pi does not have a static IP and relies on a DHCP server to obtain one:

$ sudo ufw allow out 67/udp
$ sudo ufw allow in 68/udp

2.10. Ping / ICMP (Optional)

Allows network diagnostics by sending pings from the Raspberry Pi and responding to pings received from the LAN:

$ sudo ufw allow out proto icmp
$ sudo ufw allow in from 192.168.1.0/24 proto icmp

3. Enable the firewall

$ sudo ufw enable

4. Verify status

To check that all rules have been applied correctly:

$ sudo ufw status verbose