How to configure DNAT rules in firewalld?

Solution Verified - Updated -

Environment

  • Red Hat Enterprise Linux (RHEL) 7.
  • Red Hat Enterprise Linux (RHEL) 8.
  • Red Hat Enterprise Linux (RHEL) 9.
  • firewalld

Issue

  • How to configure DNAT rules in firewalld to forward public IP/Port traffic to private IP?

Resolution

  • Configure a firewalld rich rule to forwards traffic to the web server:
# firewall-cmd --permanent --add-rich-rule='rule family="ipv4" destination address="192.0.2.1" forward-port port="443" protocol="tcp" to-port="443" to-addr="192.51.100.20"'

The rich rule forwards TCP traffic from port 443 on the web server’s public IP address 192.0.2.1 to port 443 of the web server’s private IP address 192.51.100.20.

  • Reload the firewall configuration files:
# firewall-cmd --reload

Root Cause

If a web server uses a private IP address range and is not directly accessible from the internet, you can set a DNAT rule to redirect incoming traffic to this server.

Diagnostic Steps

  • To list added rich rules in Firewalld:
# firewall-cmd --list-all

public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens192
  sources: 
  services: cockpit dhcpv6-client ssh
  ports: 
  protocols: 
  forward: no
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 
    rule family="ipv4" destination address="192.0.2.1" forward-port port="443" protocol="tcp" to-port="443" to-addr="192.51.100.20"    <<<<----

  • Check whether forwarding is working or not using telnet from the source server:
##Source Server##

# telnet 192.0.2.1 443

Trying 192.0.2.1...
Connected to 192.0.2.1.
Escape character is '^]'.


# ss | grep 192.0.2.1           
tcp    ESTAB      0      0      <Source_IPaddress>:43334                192.0.2.1:https                
##Destination Server##

# netstat -neopa | grep 443
tcp        0      0 192.51.100.20:443         <Source_IPaddress>:43334     ESTABLISHED 0          86359      6327/<Program_name>              off (0.00/0/0)


# ss | grep 192.51.100.20
tcp   ESTAB       0      0      192.51.100.20:pcsync-https              <Source_IPaddress>:43334       

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments