Skip to content

Instantly share code, notes, and snippets.

@wido
Created November 6, 2018 17:50
Show Gist options
  • Save wido/33164fea6a7d8ec8f595c0d63424748b to your computer and use it in GitHub Desktop.
Save wido/33164fea6a7d8ec8f595c0d63424748b to your computer and use it in GitHub Desktop.
iptables TCP and UDP proxy
#!/bin/bash
#
# Author: Wido den Hollander <[email protected]>
#
# Proxy all TCP and UDP IPv4 traffic from 192.168.100.230 to 10.0.100.50
#
# This can be used as a (temporary) proxy when you want to renumber a machine and want
# to make sure it's still available on it's old address
#
sysctl -w net.ipv4.ip_forward=1
INTERFACE="eth0"
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X
iptables -t nat -A POSTROUTING -m conntrack --ctstate NEW -m conntrack --ctstate DNAT
iptables -t filter -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# 192.168.100.230 -> 10.0.100.50
iptables -t nat -A PREROUTING -i ${INTERFACE} --dst 192.168.100.230 -p tcp -j DNAT --to 10.0.100.50
iptables -t nat -A PREROUTING -i ${INTERFACE} --dst 192.168.100.230 -p udp -j DNAT --to 10.0.100.50
iptables -t nat -A POSTROUTING -m conntrack --ctstate DNAT --dst 10.0.100.50 -p tcp -j MASQUERADE
iptables -t nat -A POSTROUTING -m conntrack --ctstate DNAT --dst 10.0.100.50 -p udp -j MASQUERADE
iptables -t mangle -A PREROUTING -i ${INTERFACE} --dst 192.168.100.230 -m conntrack --ctstate NEW,DNAT -p tcp -j CONNMARK --set-mark 1
iptables -t mangle -A PREROUTING -i ${INTERFACE} --dst 192.168.100.230 -m conntrack --ctstate NEW,DNAT -p udp -j CONNMARK --set-mark 1
iptables -t mangle -A PREROUTING --src 10.0.100.50 -m conntrack --ctstate DNAT -p tcp -j CONNMARK --restore-mark
iptables -t mangle -A PREROUTING --src 10.0.100.50 -m conntrack --ctstate DNAT -p udp -j CONNMARK --restore-mark
iptables -t filter -A FORWARD -i ${INTERFACE} --dst 192.168.100.230 -p tcp -j ACCEPT
iptables -t filter -A FORWARD -i ${INTERFACE} --dst 192.168.100.230 -p udp -j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment