Configure OpenVPN Client Custom Routes
In this article, we will discuss how to configure custom routes for an OpenVPN client when the server is not yours and you cannot change its configuration. Specifically, we will cover how to use route-up, route-pre-down, and scripts to achieve this.
Understanding OpenVPN Custom Routes
When connecting to a remote network using OpenVPN, it's often necessary to configure custom routes for proper traffic routing. Custom routes allow you to specify which traffic should be sent through the VPN and which should be sent through the regular internet connection. By default, OpenVPN will route all traffic through the VPN, but this can be changed using custom routes.
route-up and route-pre-down scripts
OpenVPN supports the use of scripts to specify custom routes. These scripts can be executed at different stages of the connection process:
route-up: executed after the connection is established and the VPN gateway is availableroute-pre-down: executed just before the connection is closed
These scripts can be used to add/remove custom routes during the connection process. For example, you can use a route-up script to add a route for a specific subnet and then remove it using a route-pre-down script when the connection is closed.
Configuring Custom Routes
To configure custom routes for an OpenVPN client, you'll need to create and configure the aforementioned scripts. These scripts should be written in a shell scripting language (e.g., bash) and should use the appropriate tools (e.g., ip command) to add/remove routes.
Here's an example of a route-up script that adds a route for the 192.168.100.0/24 subnet:
#!/bin/bash
ip route add 192.168.100.0/24 via $5The $5 variable contains the IP address of the VPN gateway. This script should be saved as route-up.sh and placed in the client directory of your OpenVPN configuration.
Here's an example of a route-pre-down script that removes the route added by the route-up script:
#!/bin/bash
ip route del 192.168.100.0/24 via $5This script should be saved as route-pre-down.sh and placed in the client directory of your OpenVPN configuration.
Once the scripts have been created, they need to be configured in the OpenVPN client configuration. To do this, add the following lines to your client.ovpn file:
script-security 2
up route-up.sh
down route-pre-down.shThese lines configure the OpenVPN client to use the specified scripts and set the script-security level to 2 (allowing execution of scripts).
- Custom routes can be configured for an OpenVPN client using
route-upandroute-pre-downscripts - These scripts should be written in a shell scripting language and use the appropriate tools to add/remove routes
- The scripts should be placed in the
clientdirectory of your OpenVPN configuration and configured in yourclient.ovpnfile