1

Within my laptop PC, I set a systemd service that make a OpenVPN connection to my home, and let it automatically start on boot, so that I can access my home server anywhere.

The trouble is that when I'm home already, it still connects to VPN, and confuse the route table of the laptop, therefore I can't access the server when I'm at home.

Is there a way, I can let a systemd service start conditionally?

Thanks!

Leon
  • 169
  • 9
  • Have you checked the systemd unit/service/exec manpages? I'm not home so I won't do it for you but I know you can setup conditions, I've just never tried something this convoluted. – Ginnungagap Oct 22 '21 at 18:04

2 Answers2

0

I'm no networking expert, but I think it could be done if you use Ethernet at home and WiFi elsewhere. In that case you should be able to route your WiFi interface over your VPN connection.

  • Thanks! But I always use WiFi, even though at home. Furthermore, my laptop has NO lan interface. – Leon Dec 24 '21 at 11:16
0

I post my solution here, maybe it can help someone.

I code a script, that would try to query the MAC address of my home router, if success(meaning that I'm home), stop to connect the VPN. And then modify the systemd service file(vpn-to-home.service), add a line ExecStartPre=/usr/local/bin/stop-if-lan.sh.

The script stop-if-lan.sh:

#!/bin/bash
/usr/bin/ping -4n -c 1 -q -W 1 IP_OF_ROUTER > /dev/null
MAC_ADDRESS=`arp -n | awk '/IP_OF_ROUTER/{print $3;exit}'`

if [ "$MAC_ADDRESS" == "MAC_OF_ROUTER" ] ; then
#  echo "We are already at home."
   exit 1
fi
exit 0

The vpn-to-home.service of systemd:

[Unit]
Requisite=network-online.target
After=syslog.target network-online.target 

[Service]
Type=idle
RuntimeDirectory=openvpn-client
WorkingDirectory=/run/openvpn-client
PrivateTmp=true
CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE

ExecStartPre=/usr/local/bin/check-if-lan.sh

ExecStart=/usr/sbin/openvpn --config /etc/openvpn/client/client-to-home.ovpn
LimitNPROC=10
DeviceAllow=/dev/null rw
DeviceAllow=/dev/net/tun rw
ProtectSystem=true
ProtectHome=true
KillMode=process

[Install]
WantedBy=multi-user.target
Leon
  • 169
  • 9