IPTABLES forward all ports except ssh

6,512

Since the iptables rules are executed in order (the first match applies, the following rules are not even tested), you can do it as follows:

 iptables -t nat -A PREROUTING -i eth0 -d 192.168.0.2 -j DNAT --to 192.168.0.3
 iptables -t nat -A PREROUTING -i eth0 -d 192.168.0.2 -j DNAT --to 192.168.0.3
 iptables -A FORWARD -i eth0 -d 192.168.0.2 --dport 22 -j REJECT
 iptables -A FORWARD  -i eth0 -d 192.168.0.2 -j ACCEPT
 iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

having assumed that the pc on which you are doing this has IP address 192.168.0.2, otherwise change it accordingly. THe last rule is needed to assure connectivity of the pc with IP address 192.168.0.3.

Share:
6,512

Related videos on Youtube

Avery3R
Author by

Avery3R

Updated on September 18, 2022

Comments

  • Avery3R
    Avery3R over 1 year

    I have nat and packet routing working just fine, but I'd like to forward all ports except SSH to a static ip(192.168.0.3)

    What would be the correct iptables syntax to do this?

  • Avery3R
    Avery3R about 10 years
    is eth0 the WAN or LAN interface?
  • MariusMatutiae
    MariusMatutiae about 10 years
    @MMavipc I assumed eth0 to be the WAN interface
  • Avery3R
    Avery3R about 10 years
    Just for clarification, this will only forward the ports to 192.168.0.3 right? I have 192.168.0.0/16 NATed
  • MariusMatutiae
    MariusMatutiae about 10 years
    @MMavipc Right. If you have already natted 192.168.0.0/16, then you probably do not need the last iptables rule.
  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' over 8 years
    The first two commands appear to be identical; what am I missing?  Also, since the third command uses --dport, doesn't it need to say -p tcp (or -p udp)?
  • Rachel Frei
    Rachel Frei over 6 years
    it looks like these rules will drop port 22 rather than leave it un-NATted. The OP didn't specify what he wanted but it would seem like he wanted to leave the router accessible by SSH.