wireguard-setup/scripts/connect.py

65 lines
2.4 KiB
Python
Raw Normal View History

2021-02-25 10:19:46 +00:00
#!/usr/bin/env python3
import subprocess,os
newenv = os.environ.copy()
2021-02-25 12:17:46 +00:00
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()
2021-02-25 10:19:46 +00:00
def wireguard():
try:
os.mkdir("/run/netns")
except FileExistsError:
pass
2021-02-25 12:17:46 +00:00
2021-02-25 10:19:46 +00:00
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")
2021-02-25 12:17:46 +00:00
if "veth-inner" in vpn_devices():
2021-02-25 10:19:46 +00:00
subprocess.run(["ip", "link", "del", "dev", "veth-inner"])
2021-02-25 12:17:46 +00:00
if "veth-outer" in vpn_devices():
2021-02-25 10:19:46 +00:00
subprocess.run(["ip", "link", "del", "dev", "veth-outer"])
2021-02-25 12:17:46 +00:00
if "vpn" in vpn_devices():
2021-02-25 10:19:46 +00:00
subprocess.run(["ip", "link", "del", "dev", "vpn"])
2021-02-25 12:17:46 +00:00
if "mynet0" not in vpn_devices():
subprocess.run(["ip", "link", "add", "name", "mynet0", "type", "bridge"])
if "veth-inner" in default_devices():
2021-02-25 10:19:46 +00:00
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "ip", "link", "del", "dev", "veth-inner"])
2021-02-25 12:17:46 +00:00
if "veth-outer" in default_devices():
2021-02-25 10:19:46 +00:00
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "ip", "link", "del", "dev", "veth-outer"])
2021-02-25 12:17:46 +00:00
if "vpn" in default_devices():
2021-02-25 10:19:46 +00:00
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"])
2021-02-25 12:17:46 +00:00
subprocess.run(["nsenter", "--net=/run/vpn/net", "/snacks/wireguard/scripts/inner.sh"], env=newenv)
subprocess.run(["nsenter", "--net=/proc/1/ns/net", "/snacks/wireguard/scripts/outer.sh"], env=newenv)
2021-02-25 10:19:46 +00:00
try:
2021-02-25 12:17:46 +00:00
self_ns = os.readlink("/proc/self/ns/net")
2021-02-25 10:19:46 +00:00
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.")