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.
Related videos on Youtube
Author by
Avery3R
Updated on September 18, 2022Comments
-
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 about 10 yearsis eth0 the WAN or LAN interface?
-
MariusMatutiae about 10 years@MMavipc I assumed eth0 to be the WAN interface
-
Avery3R about 10 yearsJust for clarification, this will only forward the ports to 192.168.0.3 right? I have 192.168.0.0/16 NATed
-
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' over 8 yearsThe 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 over 6 yearsit 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.