I opened to vpn interfaces with
openvpn --config vpn1.ovpn
openvpn --config vpn2.ovpn
and I want to send all from my laptop by one of the vpns.
I prevented the vpns from changing my default gateway with pull-filter ignore redirect-gateway
.
Now I need to distribute traffik between two vpn interfaces, tun0
and tun1
.
The following code does not work:
#!/bin/sh /etc/rc.common
START=99
# Define your VPN server IP addresses and ports
VPN_SERVER1="146.70.116.194"
VPN_SERVER2="103.108.231.98"
VPN_PORT1=443
VPN_PORT2=443
start() {
echo "Starting VPN Load Balancer..."
# Flush existing rules
echo "Flushing existing rules..."
ip rule flush
ip route flush table vpn0
ip route flush table vpn1
# Add default routes to the custom routing tables
echo "Adding default routes..."
ip route add default dev tun0 table vpn0
ip route add default dev tun1 table vpn1
# Add rules to select the appropriate routing table based on mark
echo "Adding ip rule..."
ip rule add fwmark 1 table vpn0
ip rule add fwmark 2 table vpn1
# Use iptables to mark packets and route them, excluding VPN server IPs and loopback traffic
echo "Configuring iptables..."
iptables -t mangle -F PREROUTING
iptables -t mangle -A PREROUTING -i lo -j RETURN
iptables -t mangle -A PREROUTING -d $VPN_SERVER1 -p tcp --dport $VPN_PORT1 -j RETURN
iptables -t mangle -A PREROUTING -d $VPN_SERVER2 -p tcp --dport $VPN_PORT2 -j RETURN
# Log new connections for debugging
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -j LOG --log-prefix "NEW_CONN: "
# Mark new connections randomly and ensure packets for existing connections stay consistent
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -m statistic --mode random --probability 0.5 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -j MARK --set-mark 2
# Save the mark for established connections
iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -j CONNMARK --save-mark
iptables -t mangle -A PREROUTING -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark
# Ensure correct routing for the marked packets
ip route flush cache
echo "VPN Load Balancer started."
}
stop() {
echo "Stopping VPN Load Balancer..."
# Remove the rules and routes when stopping the script
ip rule del fwmark 1 table vpn0
ip rule del fwmark 2 table vpn1
ip route del default dev tun0 table vpn0
ip route del default dev tun1 table vpn1
iptables -t mangle -F PREROUTING
ip route flush cache
echo "VPN Load Balancer stopped."
}
case "$1" in
start)
start
;;
stop)
stop
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
Can you advice?
-m mark ! --mark 1
match additionally in the-j MARK --set-mark 2
rule?