Randomize external port when doing NAT with iptables

6,721

SNAT accepts a --random option (from iptables-extensions manpage):

--random
       If  option --random is used then port mapping will be randomized
       (kernel >= 2.6.21).

So I'd try something like:

iptables -t nat -A POSTROUTING -o eth1 -j SNAT --to-source 193.49.142.107:2000-4000 --random
Share:
6,721

Related videos on Youtube

HaTiMuX
Author by

HaTiMuX

Updated on September 18, 2022

Comments

  • HaTiMuX
    HaTiMuX over 1 year

    I want to configure a NAT behavior different from the default one implemented by iptables.

    In this example:

    iptables -t nat -A POSTROUTING -o eth1 -j SNAT --to-source 193.49.142.107:2000-400
    

    The default behavior of NAT implemented by iptables is Endpoint independent. This means, all sessions initiated from the same host will have the same 'external' (IP, Port Number) even if there's a range of ports.

    I need to know what are the flags or options to be modified in order to have a different port number for each session.

    • Chad K
      Chad K almost 10 years
      You want each outbound connection to have a different port number, correct? What makes you think your system isn't doing that already?
    • HaTiMuX
      HaTiMuX almost 10 years
      I've already tested the rule by sinnifing packets and for 2 different sessions it's always the same port number that is affected.
    • Chad K
      Chad K almost 10 years
      What does sudo iptables -vnL -t nat show?
    • cuonglm
      cuonglm almost 10 years
      @HaTiMuX: How do you check "2 different sessions it's always the same port number"?
    • HaTiMuX
      HaTiMuX almost 10 years
      @Creek for the specific rule it shows ... to:175.45.14.88:90-100 which means there is a port ranger. I think --random does the work.
    • HaTiMuX
      HaTiMuX almost 10 years
      @Gnouc I'm using a python script in the receiving machine which is listening to the PREROUTING chain. When packets arrive I redirect them to my script using an iptable rule with the nfqueue option.
  • HaTiMuX
    HaTiMuX almost 10 years
    Thanks, I've tried it and it's working for this specific case.