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?

MadHatter
  • 79,770
  • 20
  • 184
  • 232
  • I would suggest just doing it in the process. You can `LD_PRELOAD` an interceptor library that hooks `bind`, `recvmsg`, and `getsockname`. – David Schwartz Dec 06 '12 at 18:16

2 Answers2

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).

  • 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 Dec 06 '12 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! – Tsvetomir Dimitrov Dec 06 '12 at 16:09
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.

Eugene
  • 501
  • 1
  • 3
  • 11
  • 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. – Tsvetomir Dimitrov Dec 07 '12 at 07:29