0

I need to change the outgoing port number of all UDP packets originating from a local process. For example:

local machine
udp dest:192.168.10.1/255.255.255.0 port 2222

should become (before leaving the local machine):

udp dest:192.168.10.1/255.255.255.0 port 3333

What I tried is this iptables rule:

iptables -t nat -A OUTPUT -d 192.168.10.1/255.255.255.0 -p udp --dport 2222 -j DNAT  --to-destination :3333

However it changes also the destination IP address. From another question in serverfault I saw that according to netfilter documentation ( http://www.netfilter.org/documentation/HOWTO/NAT-HOWTO.txt, section 6.3.7) iptables can't do this.

My question is how can I accomplish this task in Linux? Maybe there is another tool which can do the job?

1
  • I would suggest just doing it in the process. You can LD_PRELOAD an interceptor library that hooks bind, recvmsg, and getsockname. Commented Dec 6, 2012 at 18:16

2 Answers 2

1

I can't think of any tool that would do that out of the box. This is quite rare scenario, as you can't create correct two-way NAT mapping if you only change port. Do you really need just one-way traffic ?

However you can always write your own netfilter module (it's not that difficult) and alter packet headers in any way you want.

1
  • The main point was to change the destination port only. If I don't touch the source port, the connection will work fine. You are right that there is no such tool, so after measuring the alternatives I agree that custom netfilter module is the way to go. Commented Dec 7, 2012 at 7:29
1

You might be able to accomplish this with Divert Sockets, though I've never used it for this particular purpose, and haven't tried it on a modern kernel.

Here's the project page for the linux port. Basically, this adds a job to iptables that allows you to redirect packets into user space and modify before sending them back out on the wire (or dropping them completely).

2
  • 1
    That might work, but as I understand it requires programming skills too, and I'd recommends writing netfilter module instead, as packet processing will be much faster then.
    – Eugene
    Commented Dec 6, 2012 at 15:32
  • Yes, I agree with Eugene. I considered both diverted sockets and netfilter module. However non-programming solution is preferred. My colleagues suggest a workaround to redirect to localhost and then masquerade. I'll keep you posted on the final solution. Thanks for the comments! Commented Dec 6, 2012 at 16:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .