使用redsocks + iptables实现全局代理

redsocks是一款tcp -> 代理服务器的透明代理,使用它结合iptables,可以实现Linux下的全局代理。

1 安装

sudo apt-get install redsocks

2 配置

  • /etc/redsocks.conf
  • 修改redsocks下的local_ip, local_port,这两个是本地映射出的tcp端口
  • 修改redsocks下的ip, port, type,这三个是远程代理服务器的配置

3 iptable规则:redsocks.rules

# Transparent SOCKS proxy
# See: http://darkk.net.ru/redsocks/

*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:REDSOCKS - [0:0]

# Redirect all output through redsocks
-A OUTPUT -p tcp -j REDSOCKS

# Whitelist LANs and some other reserved addresses.
# https://en.wikipedia.org/wiki/Reserved_IP_addresses#Reserved_IPv4_addresses
-A REDSOCKS -d 0.0.0.0/8 -j RETURN
-A REDSOCKS -d 10.0.0.0/8 -j RETURN
-A REDSOCKS -d 127.0.0.0/8 -j RETURN
-A REDSOCKS -d 169.254.0.0/16 -j RETURN
-A REDSOCKS -d 172.16.0.0/12 -j RETURN
-A REDSOCKS -d 192.168.0.0/16 -j RETURN
-A REDSOCKS -d 224.0.0.0/4 -j RETURN
-A REDSOCKS -d 240.0.0.0/4 -j RETURN

# Redirect everything else to redsocks port
-A REDSOCKS -p tcp -j REDIRECT --to-ports 12345

COMMIT

4 应用

sudo iptables-restore ./redsocks.rules

5 恢复(假设没有其他nat规则)

sudo iptables -t nat -F

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *