Score:0

How can I redirect established connections with iptables?

cv flag

I am trying to create iptables rules to redirect all traffic destined for port 1986 to port 9 to provoke a “connection refused” using the following rule:

iptables -t nat -I PREROUTING -p tcp -m tcp --dport 1986 -j DNAT --to-destination :9

This works great for new connections, but the problem is that established connections seem to skip this rule and are not refused.

I have tried adding a NOTRACK rule in the raw table to try and avoid connection state tracking, but this has no effect:


iptables -t raw -I PREROUTING -p tcp --dport 1986 -m state --state ESTABLISHED,RELATED,NEW,INVALID -j NOTRACK

Adding state to the nat rule doesn't work either:

iptables -t nat -I PREROUTING -p tcp --dport 1986 -m state --state ESTABLISHED,RELATED,NEW,INVALID -j DNAT --to-destination :9

How can I use iptables to provoke a ‘connection refused’ error for packets sent on established connections?

pt flag
I don't think you'll ever be able to provoke a "connection refused" message for an existing connection because the connection has already been established. A "connection refused" response only happens when the initial TCP SYN packet is rejected (the sender receives a TCP RST in response to the initial packet). Once the connection has been established, you can only kill it or cause it to time out.
Score:0
us flag

The DNAT rule creates an entry to conntrack table when the connection is established with TCP 3-way handshake.

The notrack rule seems to disable creation of new conntrack entries. However, it does not prevent using existing conntrack entries.

Since the connection is already established, there is already an entry in the conntrack table, and the kernel uses that to forward the traffic.

You should use conntrack tool to delete the flows from conntrack table. For example:

conntrack -D -s 192.168.1.10 -d 192.168.100.20 -p tcp --dport 1986

After issuing this command, the connection is re-added to the conntrack using the new DNAT rules in iptables. Then the new destination server will refuse the connection. I am not sure what exactly the new destination server will send back, maybe TCP RST.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.