如何在Linux上设置透明代理
透明代理位于客户端和 Internet 之间,充当客户端的网关。它被称为“透明”,因为客户端不需要为代理配置任何内容。当不可能或不希望修改客户端配置但客户端流量仍然需要通过代理时,透明代理非常有用。
如果您需要在 Linux 上设置透明代理,最简单的方法之一是使用开源代理服务器软件 Squid。虽然 Squid 作为通用 Web 缓存代理服务器具有丰富的功能集,但本教程不会讨论所有这些功能。相反,它重点描述如何使用 Squid 配置透明代理。
在 Linux 上安装 Squid
对于 Ubuntu 或 Debian:
$ sudo apt-get install squid
对于 CentOS、RHEL 或 Fedora:
$ sudo yum install squid
配置鱿鱼
上述步骤将在您的系统上安装 Squid 版本 3 (squid3
),并在 /etc/squid3
中创建默认的 Squid 配置文件。 Squid 设置为开机自动启动。要将 Squid 配置为透明代理,请修改其配置文件,然后重新启动它,如下所示。
$ sudo vi /etc/squid3/squid.conf
acl localhost src 100.100.100.0/24 ::1
http_port 3128 transparent
cache_peer 100.100.100.10 parent 8000 0 no-query default
cache_effective_user proxy
cache_effective_group proxy
$ sudo /etc/init.d/squid3 restart
以acl
开头的行指定允许使用代理的客户端。在这种情况下,IP 地址属于 100.100.100.0/24
的 IP 地址将被添加到代理的白名单中。以 cache_peer
开头的行是可选的,仅当您的网络位于上游代理或防火墙后面时才需要。本质上,这一行将上游代理(即 100.100.100.10:8000
)声明为要连接的父代理,以便到达任何外部网络。
接下来,您需要设置 iptables
规则,以便任何 HTTP 流量(例如,发往端口 80
)都通过 Squid 路由。为此,您可以运行以下名为 proxy.sh
的脚本。
#!/bin/sh
# squid proxy's IP address (which is attached to eth0)
SQUID_SERVER=`ifconfig eth0 | sed -ne 's/.*inet addr:([^ ]*).*/1/p'`
# interface connected to WAN
INTERNET="eth0"
# interface connected to LAN
LAN_IN="eth1"
# Squid port
SQUID_PORT="3128"
# clean old firewall
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
# load iptables modules for NAT masquerade and IP conntrack
modprobe ip_conntrack
modprobe ip_conntrack_ftp
# define necessary redirection for incoming HTTP traffic (e.g., 80)
iptables -t nat -A PREROUTING -i $LAN_IN -p tcp --dport 80 -j REDIRECT --to-port $SQUID_PORT
# forward locally generated http traffic to Squid
iptables -t nat -A OUTPUT -p tcp --dport 80 -m owner --uid-owner proxy -j ACCEPT
iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-ports $SQUID_PORT
# forward the rest of non-HTTP traffic
iptables --table nat --append POSTROUTING --out-interface $INTERNET -j MASQUERADE
iptables --append FORWARD --in-interface $INTERNET -j ACCEPT
# enable IP forwarding for proxy
echo 1 > /proc/sys/net/ipv4/ip_forward
使用此脚本设置 iptables
规则后,您可以永久保存当前的 iptables
规则,这样您就不需要重新运行该脚本。
最后,那些希望使用透明代理的客户端应该指定透明代理的IP地址作为其默认网关。
如果您想对透明代理进行更高级的设置(例如网页过滤),请参阅本教程。