wireguard-setup/scripts/connect_basic.py

84 lines
1.9 KiB
Python
Raw Normal View History

2024-02-07 21:55:12 +00:00
#!/usr/bin/env python3
2024-02-09 18:57:33 +00:00
import subprocess
import os
2024-02-07 21:55:12 +00:00
2024-02-09 18:49:10 +00:00
2024-02-07 21:55:12 +00:00
def default_devices():
with open("/proc/1/net/dev", "r") as f:
return f.read()
2024-02-09 18:49:10 +00:00
2024-02-07 21:55:12 +00:00
def vpn_devices():
with open("/proc/self/net/dev", "r") as f:
return f.read()
2024-02-09 18:49:10 +00:00
2024-02-07 21:55:12 +00:00
def wireguard():
try:
os.mkdir("/run/netns")
except FileExistsError:
pass
2024-02-09 18:49:10 +00:00
2024-02-07 21:55:12 +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")
if "vpn" in vpn_devices():
subprocess.run(["ip", "link", "del", "dev", "vpn"])
if "vpn" in default_devices():
2024-02-09 18:49:10 +00:00
subprocess.run(
["nsenter", "--net=/proc/1/ns/net", "ip", "link", "del", "dev", "vpn"]
)
2024-02-07 21:55:12 +00:00
subprocess.run(["modprobe", "wireguard"])
2024-02-09 18:49:10 +00:00
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"],
)
2024-02-07 21:55:12 +00:00
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.")