Total Pageviews

Sunday, 29 April 2012

根据端口设置路由

from


http://michael.gorven.za.net/blog/2008/08/15/routing-port-number


Due to a very restrictive firewall at the CHPC, I need to run a VPN to get access to things like email, Jabber and SSH. This however degrades my web browsing experience, since that gets tunnelled as well. I therefore wanted a setup where only ports which are blocked get tunnelled through the VPN, while everything else goes out normally.
The routing part was fairly straightforward, which consists of an iptables rule to mark certain packets, and an alternate routing table for these marked packets. I first created a name for the new table by adding the following to /etc/iproute2/rt_tables.
10  vpn
I then added a default route to the new table specifying the IP address of the VPN server and the VPN interface, and a rule to use this table for packets marked by iptables.
ip route add default via 10.8.0.3 dev tun0 table vpn
ip rule add fwmark 0x1 table vpn
The following iptables rule will mark packets destined to the listed port numbers. Note that this is for packets originating from the firewall host — if you want this to apply to packets forwarded for other hosts it must be in the PREROUTING chain.
iptables -t mangle -A OUTPUT -p tcp -m multiport --dports 22,995,587,5223 -j MARK --set-mark 0x1
The actual routing worked, but packets were being sent with the wrong source IP. I therefore needed to NAT packets going out on the VPN interface (the IP address is the local IP of the VPN connection).
iptables -t nat -A POSTROUTING -o tun0 -j SNAT --to 10.8.0.4
I could then see packets going out on the VPN interface with the correct source IP as well as the replies, but it still wasn’t working. I eventually discovered that rp_filter must be disabled in order for this to work.
echo 0 > /proc/sys/net/ipv4/conf/tun0/rp_filter