wireguard-setup/scripts/connect_basic.py

53 lines
1.7 KiB
Python

#!/usr/bin/env python3
import subprocess,os
newenv = os.environ.copy()
newenv["LD_PRELOAD"] = "/snacks/wireguard/bin/wireguard-resolve.so"
def default_devices():
with open("/proc/1/net/dev", "r") as f:
return f.read()
def vpn_devices():
with open("/proc/self/net/dev", "r") as f:
return f.read()
def wireguard():
try:
os.mkdir("/run/netns")
except FileExistsError:
pass
try:
os.symlink("/run/vpn/net", "/run/netns/vpn")
os.symlink("/proc/1/ns/net", "/run/netns/default")
except FileExistsError:
pass
with open("/proc/sys/net/ipv4/conf/all/forwarding", "w") as f:
f.write("1")
with open("/proc/sys/net/ipv6/conf/all/forwarding", "w") as f:
f.write("1")
with open("/proc/sys/net/ipv4/ping_group_range", "w") as f:
f.write("0 2147483647")
if "vpn" in vpn_devices():
subprocess.run(["ip", "link", "del", "dev", "vpn"])
if "vpn" in default_devices():
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "ip", "link", "del", "dev", "vpn"])
subprocess.run(["modprobe", "wireguard"])
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "ip", "link", "add", "dev", "vpn", "type", "wireguard"])
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "ip", "link", "set", "dev", "vpn", "netns", "vpn"])
subprocess.run(["nsenter", "--net=/run/vpn/net", "/snacks/wireguard/scripts/inner_basic.sh"], env=newenv)
try:
self_ns = os.readlink("/proc/self/ns/net")
vpn_ns = os.readlink("/run/vpn/net")
except Exception as e:
print(e)
else:
if self_ns == vpn_ns:
wireguard()
else:
print("This script should be called from the VPN network namespace.")