Score:1

Prevent OpenVPN systemd service from starting at home

gd flag

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!

Ginnungagap avatar
gu flag
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.
Score:0
gd flag

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
Score:0
cn flag

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.

Leon avatar
gd flag
Thanks! But I always use WiFi, even though at home. Furthermore, my laptop has NO lan interface.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.