problem:
I have a TCP server and client that each listen on port 9000. I have the server and client deployed on two different hosts where traffic can only pass through port 80 between them. I want the source port (9000) to be maintained when packets are sent between them (see the SNAT rule below) so that the PREROUTING rule can identify the packets with --source-port
.
approach:
I'm trying to setup iptables rules such that the server routes its traffic from port 9000 to port 80, and a complimentary rule for the client where the incoming traffic on port 80 is routed to 9000 locally.
I've come up with this script to apply the rules. I've tried this with a few variations and packets seem to get accepted by the server host, but not accepted by the PREROUTING (inbound) rule.
#!/bin/bash
apply_inbound_rules() {
# Allow incoming server traffic from port 80 to the TCP client
sudo iptables -t nat \
-I PREROUTING \
-p tcp --destination-port $PROXY_PORT \
-j REDIRECT --to-port $TCP_PORT
}
apply_outbound_rules() {
# Setup outgoing packets created by the TCP server
# to route through local port 80
# and received on port 80 on the client host
sudo iptables -t nat \
-I OUTPUT \
-p tcp --destination-port $TCP_PORT \
-j DNAT --to-destination :$PROXY_PORT
# To maintain the TCP_PORT
sudo iptables -t nat \
-I POSTROUTING \
-p tcp --destination-port $PROXY_PORT \
-j SNAT --to-source :$TCP_PORT
}
apply_inbound_rules
apply_outbound_rules
Does anyone have experience creating rules like this? It seems like it would be a common problem but I can't seem to figure it out.
--source-port
, then?MASQUERADE
instead ofSNAT
?iptables -t nat -I POSTROUTING -j MASQUERADE
?