Skip to content

Instantly share code, notes, and snippets.

@kingluo
Last active July 12, 2024 08:43
Show Gist options
  • Save kingluo/8944c1435c3c93fd7bccaca3f4f810ba to your computer and use it in GitHub Desktop.
Save kingluo/8944c1435c3c93fd7bccaca3f4f810ba to your computer and use it in GitHub Desktop.
transparent socks5 proxy
ipset_name="myset"
hosts=("httpbin.org")
interval=3 #secs
while true; do
new_iplist=()
for host in ${hosts[@]}; do
for ip in $(dig +noall +answer +multiline $host | awk '{print $NF}' | sort); do
new_iplist+=($ip)
done
echo "check $host: ${new_iplist[@]}"
done
iplist=$(ipset list $ipset_name | awk 'BEGIN{flag=0}{if(flag==1) print $0; if ($0 ~ /^Members:/) { flag=1 }}')
# remove non-exists ip addresses
for ipp in ${iplist[@]}; do
exists=0
for ip in ${new_iplist[@]}; do
if [[ $ipp == $ip ]]; then
exists=1
break
fi
done
if [[ $exists == 0 ]]; then
echo "del $ip"
ipset del $ipset_name $ip
fi
done
# add new ip addresses
for ip in ${new_iplist[@]}; do
exists=0
for ipp in ${iplist[@]}; do
if [[ $ipp == $ip ]]; then
exists=1
break
fi
done
if [[ $exists == 0 ]]; then
echo "add $ip"
ipset add $ipset_name $ip
fi
done
sleep $interval
done
@kingluo
Copy link
Author

kingluo commented Jul 12, 2024

# setup ssh socks5 server as demo
ssh -o ServerAliveInterval=60 -N -D 127.0.0.1:30000 <username>@<ssh server> -p 20022 &

# compile and run tcpsocks
cd /opt
git clone https://github.com/vi/tcpsocks
cd tcpsocks
make
./tcpsocks 0.0.0.0 12345 REDIRECT REDIRECT 127.0.0.1 30000

# create an ipset
ipset create myset hash:net

# setup iptables rules
iptables -t nat -A QQQ -p tcp -m set --match-set myset dst -j REDIRECT --to-ports 12345
iptables -t nat -I OUTPUT 1 -j QQQ
iptables -t nat -I PREROUTING 1 -j QQQ

# watch domains
./watch_dns_and_update_ipset.sh &

# check if it works
curl -i http://httpbin.org/anything
HTTP/1.1 200 OK
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment