Skip to content

Instantly share code, notes, and snippets.

@skobkin
Last active January 16, 2024 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skobkin/c1fe5fdda777075f741a62b34ea9f223 to your computer and use it in GitHub Desktop.
Save skobkin/c1fe5fdda777075f741a62b34ea9f223 to your computer and use it in GitHub Desktop.
add-routes.sh
#!/bin/bash
# This script adds routes to listed resources via pre-defined gateway or alternatively takes gateway address
# from first argument.
# Usage:
# ./add-routes.sh
# or to override gateway:
# ./add-routes.sh 234.234.234.234
GATEWAY=${1:-"123.123.123.123"}
ADDRESSES="123.123.123.123 123.123.123.123 \
123.123.123.123 123.123.123.123"
# To route everything
#ADDRESSES="0.0.0.0"
echo "Adding routes:"
for TARGET in $ADDRESSES; do
echo " -> $TARGET via $GATEWAY"
sudo ip route add $TARGET via $GATEWAY
done
@skobkin
Copy link
Author

skobkin commented Jan 16, 2024

To configure a VM for routing we need to edit /etc/sysctl.conf and uncomment the following line:

# net.ipv4.ip_forward=1

Then run sysctl -p from root.

After that we should connect to our VPN and check out which interface it creates.

Suppose that ppp0 is our VPN interface and enp1s0 is our "physical" interface which can interact with the host OS.

Then we should set our firewall in the following way:

# run from root or using sudo
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
iptables -A FORWARD -i ppp0 -o enp1s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i enp1s0 -o ppp0 -j ACCEPT

Then you can use add-routes.sh on the host OS using VM ip address as a gateway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment