diff --git a/Makefile b/Makefile index f6b166e..ef7587a 100644 --- a/Makefile +++ b/Makefile @@ -36,6 +36,7 @@ install_basic: systemd scripts bin cp scripts/inner_basic.sh /snacks/wireguard/scripts/inner_basic.sh cp scripts/is_root_namespace.py /snacks/wireguard/scripts/is_root_namespace.py cp scripts/dns.nft /snacks/wireguard/scripts/dns.nft + cp scripts/create_conf.py /snacks/wireguard/scripts/create_conf.py cat scripts/vpn_prompt.sh >> /etc/zsh/zshrc cp bin/vpn /usr/local/bin/vpn setcap cap_sys_admin,cap_sys_ptrace=ep /usr/local/bin/vpn diff --git a/scripts/connect_basic.py b/scripts/connect_basic.py index e5567a8..e5df64a 100644 --- a/scripts/connect_basic.py +++ b/scripts/connect_basic.py @@ -66,6 +66,9 @@ def wireguard(): "vpn", ] ) + subprocess.run( + ["nsenter", "--net=/proc/1/ns/net", "/snacks/wireguard/scripts/create_conf.py"], + ) subprocess.run( ["/snacks/wireguard/scripts/inner_basic.sh"], ) diff --git a/scripts/create_conf.py b/scripts/create_conf.py new file mode 100644 index 0000000..395155b --- /dev/null +++ b/scripts/create_conf.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +import pydantic +from typing import Optional +import socket + + +class Config(pydantic.BaseModel): + public_key: str + host: str + port: int + private_key: str + + +def write_wg(config: Config): + wg_conf = ( + "[Interface]\n" + f"privatekey = {config.private_key}\n\n" + "[Peer]\n" + f"publickey = {config.public_key}\n" + f"endpoint = {config.host}:{config.port}\n" + "persistentkeepalive = 20\n" + "allowedips = 0.0.0.0/0, ::/0\n" + ) + + try: + with open("/run/vpnclient/wg.conf", mode="w", encoding="utf-8") as f: + f.write(wg_conf) + except IOError: + pass + + +def get_config() -> Optional[Config]: + with open("/snacks/wireguard/wg.json", "r", encoding="utf-8") as f: + config = Config.parse_raw(f.read()) + config.host = socket.gethostbyname(config.host) + return config + + +write_wg(get_config()) diff --git a/systemd/vpnclient-wg-basic.service b/systemd/vpnclient-wg-basic.service index c73a23d..5aaa3b1 100644 --- a/systemd/vpnclient-wg-basic.service +++ b/systemd/vpnclient-wg-basic.service @@ -12,6 +12,8 @@ EnvironmentFile=/snacks/wireguard/env ExecStart=/snacks/wireguard/scripts/connect_basic.py NetworkNamespacePath=/run/vpn/net RemainAfterExit=true +RuntimeDirectory=vpnclient +RuntimeDirectoryMode=0600 [Install] WantedBy=multi-user.target