How to Configure NAT Masquerading in Firewalld on CentOS 7: Converting iptables -j MASQUERADE Rule


4 views

In traditional iptables, we'd use this rule for NAT masquerading:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

Firewalld uses its own rich language for rules. The equivalent masquerading configuration requires two steps:

# Add the source network to trusted zone
sudo firewall-cmd --permanent --zone=trusted --add-source=10.8.0.0/24

# Enable masquerade on the public interface
sudo firewall-cmd --permanent --zone=public --add-masquerade

After applying these changes, verify them with:

sudo firewall-cmd --zone=public --query-masquerade
sudo firewall-cmd --zone=trusted --list-sources

For those who prefer working closer to iptables syntax, firewalld allows direct rules:

sudo firewall-cmd --permanent --direct --add-rule ipv4 nat POSTROUTING 0 -s 10.8.0.0/24 -o eth0 -j MASQUERADE

Remember to reload firewalld after making permanent changes:

sudo firewall-cmd --reload

If your network interface changes (e.g., from eth0 to ens3), update accordingly:

sudo firewall-cmd --permanent --zone=public --change-interface=ens3

For IPv6 networks, simply change ipv4 to ipv6 in direct rules:

sudo firewall-cmd --permanent --direct --add-rule ipv6 nat POSTROUTING 0 -s fd00:dead:beef::/64 -o eth0 -j MASQUERADE

When migrating from iptables to firewalld, many administrators need to replicate NAT functionality. The specific iptables rule:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

can be achieved in firewalld through its rich rules and zones configuration.

Here's how to implement this in firewalld:

# Add masquerading to the public zone (or your desired zone)
firewall-cmd --permanent --zone=public --add-masquerade

# Add source-based routing for the specific subnet
firewall-cmd --permanent --zone=public \
--add-rich-rule='rule family="ipv4" source address="10.8.0.0/24" masquerade'

# Reload firewalld to apply changes
firewall-cmd --reload

To verify your configuration:

# Check masquerading status
firewall-cmd --query-masquerade

# List rich rules
firewall-cmd --list-rich-rules

For more complex setups, consider creating a dedicated zone:

# Create new zone
firewall-cmd --permanent --new-zone=vpn_zone

# Set target to ACCEPT
firewall-cmd --permanent --zone=vpn_zone --set-target=ACCEPT

# Add masquerade and source address
firewall-cmd --permanent --zone=vpn_zone --add-masquerade
firewall-cmd --permanent --zone=vpn_zone \
--add-source=10.8.0.0/24

# Apply changes
firewall-cmd --reload

Remember to use the --permanent flag for rules that should persist after reboot. For temporary testing, you can omit it and add later.

If connectivity issues persist:

# Check kernel IP forwarding
sysctl net.ipv4.ip_forward

# Temporary enable if needed
sysctl -w net.ipv4.ip_forward=1

# Make permanent by editing
# /etc/sysctl.conf or /etc/sysctl.d/99-sysctl.conf