[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Dynamic port opening and forwarding?

On 30 Aug 2004, Oliver Schaper wrote:
> I want to open and forward a port on my gateway kinda dynamically.
> I.e. I want to open port 3898/TCP and forward it to
> As far as I got the manuals right this can be done using iptables.
> So I wrote a small batch file which is using 3 parameters, the IP adress and
> the port. This batch is to be called when I need it, so after the
> connection of my gateway is already established.

You might find using a pre-written helper script such as 'firehol' or
'shorewall' easier that trying to do this all by hand up front -- they
make it much easier to achieve your goal, unless your goal is to learn
iptables. :)

> Calling "./portfwd 3898 TCP" should do the trick.
> Here's my batch...
> iptables -A xtaccess -p $3 --dport $2 -j ACCEPT
> iptables -A portfwf -p $3 -m state --state NEW -d $1 --dport $2 -j ACCEPT
> But it doesn't seem to work, although there are no error messages at
> all. :/

If that is *all* your iptables rules then yes, nothing would happen.

You are not actually doing any sort of NAT in there, I fear.

What you want is something like this:

] iptables -t nat -A PREROUTING -p "$3" --dport "$2" \
      -j DNAT --to-destination "$1"

That will actually do the NAT for you, for any packets.

You could also make it a bit more restrictive by adding:
  '-m state --state NEW,ESTABLISHED,RELATED' to that command.

Then, write your allow rules:

] iptables -t filter -A FORWARD -p "$3" --dport "$2" \
      -d "$1" -m state --state NEW,ESTABLISHED,RELATED -j accept
] iptables -t filter -A FORWARD -p "$3" --sport "$2" \
      -s "$1" -m state --state ESTABLISHED,RELATED

You only need that final rule if you don't have a blanket outbound
accept statement in place, of course.

I saw that most programmers never mature above the "see jack run" level.
My pals at the [suppressed!] Comp Sci Dept scoff at the estimates I make, but
I never underestimate -- they always do. I think of the big picture, the 75%
that remains after the code "works".
        -- Erik Naggum

Reply to: