Configuration Installation#
Installation:
apt install ufw
After installing UFW, the default state is always inactive. IPv6 is supported by default, and the default rules for outbound traffic are ACCEPT, while the default rules for inbound and forwarding traffic are DROP. Usually, this is what we want. Here, we first open the ssh port, otherwise, after activating it, we will be locked out.
Run:
sudo ufw allow ssh
UFW will generate two rules for port 22, one for IPv4 and one for IPv6. If your ssh listening port is not 22, just allow the port number, for example, allow 22222. The difference is that allow ssh will specify TCP, while allow port will add both TCP and UDP rules.
At this time, enable ufw:
ufw enable
At this time, check the ufw status again:
ufw status verbose
You can see that ufw is already enabled, the default inbound is deny, all outbound traffic is allowed, and there is no forwarding.
View Routing#
iptables -t nat -vnL
Common Rule Commands#
View the current status of the firewall#
ufw status
Enable the firewall#
ufw enable
Disable the firewall#
ufw disable
View the firewall version#
ufw version
Allow external access to the host by default#
ufw default allow
Deny external access to the host by default#
ufw default deny
Allow access to port 53 from external sources#
ufw allow 53
Deny access to port 53 from external sources#
ufw deny 53
Allow a specific IP address to access all ports on the host#
ufw allow from 192.168.0.1
Allow a specific port using TCP protocol#
ufw allow 80/tcp
Allow a specific port using UDP protocol#
ufw allow 80/udp
Disallow a specific port using TCP protocol#
ufw delete allow 80/tcp
Disallow a specific port using UDP protocol#
ufw delete allow 80/udp
Deny all incoming connections and allow all outgoing connections#
ufw default allow outgoing
ufw default deny incoming
Most systems only need to open a few ports to accept incoming connections and close all remaining ports. Starting with a simple rule base, the ufw default command can be used to set the default response action for incoming and outgoing connections. ufw default also allows the use of the reject parameter.
Warning: Configuring default deny or reject rules without explicitly setting allow rules will lock you out of your server. Make sure to configure allow rules for SSH and other critical services before applying default deny or reject rules.
Advanced Rule Commands:#
In addition to port-based allow or deny, UFW also allows you to allow/deny based on IP addresses, subnets, and combinations of IP address/subnet/port.
Allow connections from a specific IP address#
ufw allow from 123.45.67.89
Allow connections from a specific subnet#
ufw allow from 123.45.67.89/24
Allow a combination of specific IP/port#
ufw allow from 123.45.67.89 to any port 22 proto tcp
proto tcp can be removed or changed to proto udp according to your needs, and all examples of allow can be changed to deny as needed.