Iptables – Forward traffic from one process only

forwardingiptables

I want to inspect and modify the http requests from one process sent to another. For that I have a proxy running on localhost port 8080/tcp. The process owner is root, and the application it sends to runs on localhost port 50000/tcp. The process spawns new sub-processes, that's why I'm chosing the above route. I can't use --pid-owner. How would the iptables command for this look like?

Or phrased differently:

Situation:

  • There is one process p2, that communicates using HTTP with another process p1.
  • p2 and p1 run on localhost
  • p1 runs on 50000/tcp
  • p2 -> p1

Goal:

  • Run the traffic through a proxy.
  • Proxy also runs on localhost.
  • Port 8080/tcp.
  • p2 -> proxy -> p1

Difficulties:

  • I don't have the option to specify a proxy in p2.
  • Everything runs on localhost

Best Answer

We need to intercept the P2 connection to localhost TCP/50000 and forward it to the PROXY listening on TCP/8080 - The PROXY has to be configured to forward the request to LOCALHOST TCP/5000.

For this to work we need to activate the forwarding of localhost ports to IPTABLES, changing following system parameter:

sysctl -w net.ipv4.conf.all.route_localnet=1

Afterwards this IPTABLES command should take the P2 connection to TCP/50000 and do a NAT to the PROXY listening on port TCP/8080:

iptables -t nat -A OUTPUT -m addrtype --src-type LOCAL --dst-type LOCAL -m owner --uid-owner 0 -p tcp --dport 50000 -j DNAT --to-destination 127.0.0.1:8080

This configuration may also work using an external PROXY (meaning not running on the same machine where P1 & P2 are running) changing the IP address 127.0.0.1 to the external one in:

--to-destination X.X.X.X:8080

Hope this helps.