How to block outgoing connections on Centos / RHEL

Firewalld can be used to block (and allow specific) outgoing connections by applying iptables rules via the –direct option. Below example will block all outgoing connections to external network but allow outgoing connections to local network / localhost.

To add firewall rules

Initial default rule to allow outgoing connections (node order of the rule after OUTPUT)

sudo firewall-cmd --permanent --direct --add-rule ipv4 filter OUTPUT 0 -m state --state ESTABLISHED,RELATED -j ACCEPT

Adding rule to allow connections to local network

sudo firewall-cmd --permanent --direct --add-rule ipv4 filter OUTPUT 1 -d 192.168.0.0/16 -j ACCEPT

Note

The -o option can be used to add rule for a specific network interface ipv4 filter OUTPUT 1 -o eno2 -d 192.168.0.0/16 -j ACCEPT

Add rule to allow outgoing network connections to NTP servers only (UDP port 123)

sudo firewall-cmd --permanent --direct --add-rule ipv4 filter OUTPUT 1 -d 127.0.0.1/32 -j ACCEPT

Add rule to allow outgoing network connections to NTP servers only (UDP port 123)

sudo firewall-cmd --permanent--direct --add-rule ipv4 filter OUTPUT 1 -p udp --dport 123 -j ACCEPT

Block all other outgoing connections

sudo firewall-cmd --permanent --direct --add-rule ipv4 filter OUTPUT 2 -d 0.0.0.0/0 -j DROP

Reload firewalld

sudo firewall-cmd --reload

To remove firewall rules

sudo firewall-cmd --permanent --direct --remove-rules ipv4 filter OUTPUT

Reload firewalld for changes to take effect.

sudo firewall-cmd --reload

Alternatively, you may manually remove the entries in the xml file created by firewalld which is located in /etc/firewalld/direct.xml and then reload firewalld