Block and Unblock an IPv4 IP Address using firewalld on Linux

Shahriar Shovon

Supported OS

  • All

Categories

Share this post with your friends

You can block a host with a specific IPv4 address with firewalld firewall program. The firewalld program can be managed by the firewall-cmd command. By default the firewall-cmd command don't have any specific options to block an IP address. But we can use firewalld rich rules. Let's see how it's done.

Blocking an IPv4 Address with firewall-cmd command:

Suppose you want to block a host with the IPv4 address 192.168.17.112, so it can't connect to your computer. You can do that with the following command. sudo firewall-cmd --add-rich-rule='rule family=ipv4 source address=192.168.17.112 reject' --permanent success The rich rule has been added permanently. Now we have to reload the firewalld program configuration for the changes to take effect. To do that, run the following command. sudo firewall-cmd --reload success Now you can verify that the rule has been added and it's active with the following command. sudo firewall-cmd --list-all public (default, active) interfaces: eno16777760 sources: services: dhcpv6-client ftp nfs ssh ports: masquerade: no forward-ports: icmp-blocks: rich rules: rule family="ipv4" source address="192.168.17.112" reject Now you can try to ping from the host with the IPv4 address 192.168.17.112, and the request now should be denied by the server.

Unblocking the IPv4 address:

You can also unblock the blocked IPv4 address with the firewall-cmd command with the following command. sudo firewall-cmd --remove-rich-rule='rule family=ipv4 source address=192.168.17.112 reject' --permanent success Now reload the firewalld program with the following command. sudo firewall-cmd --reload success Now you should be able to ping from the host with the IPv4 address 192.168.17.112.

FAQ:

Do I have to use the same rule I added with --add-rich-rule option to remove with --remove-rich-rule?

Yes.

How do I remember several days or months after what rules I added while removing a rich rule?

You can get a list of active rich rules with firewall-cmd --list-all command. Just copy and paste the rich rule as shown in the list.

References:

access.redhat.com Tested on: CentOS 7