Making OpenVPN work with Squid Proxy in AWS EC2 / VPS
Key Terms
Squid Proxy
A free and open source forward proxy used mainly for forwarding HTTP and Web traffic
OpenVPN
A open sourced Virtual Private Network software used for connecting to private networks over public internet
Context
We want to allow users connected to one private network (VPC A) to connect to instances in another private network (VPC B) without connecting to both VPNs at the same time.
Enter Squid Proxy.
We mount a always-logged-in, VPN Client on this Squid proxy instance with authentication such that this proxy instance is secure and able to be used by users with access to VPC A.
Problem
When a remote instance in VPC A connects to VPC B through the use of OpenVPN, the default gateway routes get overwritten when the OpenVPN server in VPC B pushes its routes to the OpenVPN Client.
This meant that the original SSH session that was created to remotely control the instance in VPC A is now being dropped and the instance has no known route to get back to the VPC A.
Solution
OpenVPN client profiles provide additional script triggers such as up
and down
to allow scripts to be ran at the point of connection initialization or disconnection.
We use this triggers to run the following ip rule and routing scripts.
To add to profile:
up /etc/openvpn/scripts/script_route
To create script script_route
sudo ip rule add from $(ip route get 1 | grep -Po '(?<=src )(\S+)') table 128 # subnet ipsudo ip rule add to <insert VPC A's address range with subnet mask> table 128 # for accessing the rest of the VPC and unlocking DNS serversudo ip route add table 128 to $(ip route get 1 | grep -Po '(?<=src )(\S+)')/32 dev $(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)') # self /32 ipsudo ip route add table 128 default via $(ip -4 route ls | grep default | grep -Po '(?<=via )(\S+)') # add old default gateway
This way, the routes taken by the instance will go through two different gateways when it sees traffic going from the instance to a different ip subnet range. This is important to maintain connections and control from the VPC A as in this case the connection to it can become orphaned when connections reach the Squid Proxy instance but there is no route back to where it was connecting from (another VPC A VPN assigned ip address)
Please feel free to ask questions for more clarification!