Firewalld has replaced iptables as a default in many Linux distributions. It is now the default firewall in CentOS, Fedora, OpenSUSE, Red Hat Enterprise Linux, and SUSE Linux Enterprise. You can also install it on Debian and Ubuntu from their official package repositories.
Luckily firewall configuration with firewalld is very easy, especially for predefined services like http, https, ssh, etc.
View current configuration
It’s quite useful to look at the configuration before doing any changes and after each change to ensure changes were applied correctly. To view the active firewall configuration use the following command:
firewall-cmd --list-all
Note: Keep in mind that this command does not show the persisted configuration so on reboot this configuration may be different.
Permanent/temporary configuration
When adding firewall rules to a remote server it’s best to test the rules before you persist it to permanent configuration. If you lose access to the remote server you can just reboot to regain access. Once you’re happy with the firewall configuration you can persist the changes to disk using this command:
firewall-cmd --runtime-to-permanent
To make a permanent firewall change without this additional step, you need to add “–permanent” argument to the firewall change. Examples below use this so it’s easier.
Allow all incoming http connections
The predefined service for http port 80 is “http” so use the following to allow access to http:
firewall-cmd --zone=public --add-service=http --permanent
Allow all incoming https connections
The predefined service for https port 443 is “https” so use the following to allow access to https on port 443:
firewall-cmd --zone=public --add-service=https --permanent
Allow incoming ssh connections from an IP
It’s recommended to restrict ssh connections to particular set of IPs for security. Let’s say your home IP / office is “123.123.123.123”, you can allow SSH access to that IP using the following:
firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="123.123.123.123/32" port protocol="tcp" port="22" accept'
Once you added all the IPs you want to allow you should ensure the main ssh service is removed from the zone if present:
firewall-cmd --zone=public --remove-service=ssh --permanent
Allow all incoming ssh connections
It’s NOT recommended to allow your server to be accessed access by the world but this is done using the following:
firewall-cmd --zone=public --add-service=ssh --permanent