UFW firewall setup
mouse 2698 · person cloud · link
Last update
2023-11-20
2023
11-20
« — »

If you are using it on a VPS then you have to enable iptables NAT beforehand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
apt-get install ufw

# disable IPv6 rules
sed -r -i 's/IPV6=yes/IPV6=no/' /etc/default/ufw

# write rules in /lib/ufw/user.rules
ufw reset # reset to defaults
# set our defaults
ufw default allow outgoing
ufw default deny  incoming
ufw allow 22/tcp        comment ssh
ufw allow 80/tcp        comment http
ufw allow 443/tcp       comment https
ufw allow 1194/udp      comment openvpn
ufw allow 1100:1200/tcp # port range (proto required23)
ufw allow 53            # allow both tcp and udp (eg: DNS)
ufw allow from 1.2.3.4  # single host
ufw allow from 192.168.1.0/24 # subnet
ufw allow from 1.2.3.4 to any port 22 proto tcp

# block an IP if it has attempted to initiate 6 or more
# connections in the last 30 seconds
ufw limit 22/tcp

# show rules added before enabling firewall
ufw show added

# remove/insert rule
ufw status numbered
ufw delete <row_number>
ufw insert <row_number> <new rule>

# show rules
ufw show added
ufw show raw

# other reports
ufw show builtins
ufw show before-rules
ufw show user-rules
ufw show after-rules
ufw show logging-rules

# start/stop/status service
ufw enable
ufw disable
ufw status
ufw status verbose
ufw reload # reload cfg

# see logs
ufw logging low # off/low/medium/high/full
tail -f /var/log/ufw.log

# show blocked incoming ports messages from log/dmesg/journalctl
dmesg | grep UFW | sed -r 's/.*(IN=[^ ]+).*(PROTO=[^ ]+).*(DPT=[^ ]+) .*/\1 \2 \3/' | sort -u

Notes:

  1. The order of rules is critical in ufw/iptables as a packet will match the first rule, subsequent rules are ignored.
  2. If something is wrong with filtering/logs you can try to purge and reinstall uwf (especially after a distribution upgrade).

Source: CyberCiti, ArchLinux

See also: Lullabot