Skip to content

Instantly share code, notes, and snippets.

@varfrog
Last active December 16, 2023 21:42
Show Gist options
  • Save varfrog/f61dbd624292ceae5f73c94081bf7b03 to your computer and use it in GitHub Desktop.
Save varfrog/f61dbd624292ceae5f73c94081bf7b03 to your computer and use it in GitHub Desktop.

Guest configuration

Enable packet forwarding:

In /etc/sysctl.conf uncomment the next line to enable packet forwarding for IPv4. net.ipv4.ip_forward=1:

Set a routing rule

Run ip addr show tun0 is the network interface that appears when a VPN is running. IP 192.168.0.105 is the host IP (in host: ip addr show enp5s0 | grep 'inet ')

sudo iptables -t nat -A POSTROUTING -o tun0 -s 192.168.0.105 -j MASQUERADE

For viewing and verifying if this is still applied (e.g. after reboot): sudo iptables -t nat -L -n -v

The output, e.g.:

Chain POSTROUTING (policy ACCEPT 682 packets, 128K bytes)
 pkts bytes target     prot opt in     out     source               destination         
   39  2340 MASQUERADE  all  --  *     tun0   192.168.0.105       0.0.0.0/0   

To optionally disallow other traffic,

# Allow established and related traffic for open connections
sudo iptables -A INPUT -i tun0 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Drop all other incoming traffic
sudo iptables -A INPUT -i tun0 -j DROP

Save the rules

sudo sh -c "iptables-save > /etc/iptables.rules"

Persist changes for reboot

sudo vim /usr/local/bin/iptables_restore.sh add:

#!/bin/bash

iptables-restore < /etc/iptables.rules
sudo chmod 750 /usr/local/bin/iptables_restore.sh
sudo vim /etc/systemd/system/restore-iptables.service

add:

[Unit]
Description=Restore IP Tables
After=network.target

[Service]
ExecStart=/usr/local/bin/iptables_restore.sh
Type=oneshot

[Install]
WantedBy=multi-user.target
sudo systemctl start restore-iptables
sudo systemctl enable restore-iptables

Note for AWS VPN Client:

It disables IP packet forwarding. I need to re-enable it after I launch it:

sudo sysctl net.ipv4.ip_forward=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment