Compare commits

..

No commits in common. 'main' and 'v2.0.0' have entirely different histories.
main ... v2.0.0

@ -1,6 +0,0 @@
version: 2
updates:
- package-ecosystem: pip
directory: /
schedule:
interval: daily

@ -14,23 +14,9 @@ Requirements:
Installation:
a) With [pipx](https://github.com/pypa/pipx).
~~~ bash
pipx install git+https://github.com/dadevel/wg-netns.git@main
~~~
b) With `pip`.
~~~ bash
pip install --user git+https://github.com/dadevel/wg-netns.git@main
~~~
c) As standalone script.
~~~ bash
curl -o ~/.local/bin/wg-netns https://raw.githubusercontent.com/dadevel/wg-netns/main/wgnetns/main.py
chmod +x ~/.local/bin/wg-netns
git clone --depth 1 https://github.com/dadevel/wg-netns.git
sudo ./wg-netns/setup.sh
~~~
## Usage
@ -63,23 +49,17 @@ Minimal JSON example:
Full YAML example:
~~~ yaml
# name of the network namespace where the interface is moved into, if null the default namespace is used
# name of the network namespace
name: ns-example
# namespace where the interface is initialized, if null the default namespace is used
base_netns: null
# if false, the netns itself won't be created or deleted, just the interfaces inside it
managed: true
# list of dns servers, if empty dns servers from default netns will be used
dns-server: [10.10.10.1, 10.10.10.2]
# shell hooks, e.g. to set firewall rules, two formats are supported
pre-up: echo pre-up from managed netns
post-up:
- host-namespace: true
command: echo post-up from host netns
- host-namespace: false
command: echo post-up from managed netns
pre-down: echo pre-down from managed netns
post-down: echo post-down from managed netns
# shell hooks, e.g. to set firewall rules
pre-up: echo pre-up
post-up: echo post-up
pre-own: echo pre-down
post-down: echo post-down
# list of wireguard interfaces inside the netns
interfaces:
# interface name, required
@ -88,7 +68,6 @@ interfaces:
address:
- 10.10.11.172/32
- fc00:dead:beef:1::172/128
# can also be set via "wg set wg-site-a $key"
private-key: nFkQQjN+...
# optional settings
listen-port: 51821
@ -145,41 +124,37 @@ You can verify the success with a combination of `ip` and `wg`.
ip netns exec ns-example wg show
~~~
You can also spawn a shell inside the netns.
Or you can spawn a shell inside the netns.
~~~ bash
ip netns exec ns-example bash -i
~~~
### Systemd Service
You can find a `wg-quick@.service` equivalent at [wg-netns@.service](./extras/wg-netns@.service).
Place your profile in `/etc/wireguard/`, e.g. `example.json`, then start the service.
Or connect a container to it.
~~~ bash
curl -o /etc/systemd/system/wg-netns@.service https://raw.githubusercontent.com/dadevel/wg-netns/main/extras/wg-netns@.service
systemctl enable --now wg-netns@example.service
podman run -it --rm --network ns:/run/netns/ns-example alpine wget -O - https://ipinfo.io
~~~
If you are using SELinux, you have to change the SELinux context label, e.g. to `bin_t`, otherwise the service will not find the executable.
Or do whatever else you want.
### System Service
You can find a `wg-quick@.service` equivalent at [wg-netns@.service](./wg-netns@.service).
Place your profile in `/etc/wireguard/`, e.g. `example.json`, then start the service.
~~~ bash
chcon -t bin_t /root/.local/bin/wg-netns
systemctl start wg-netns@example.service
~~~
### Podman Integration
### Port Forwarding
A podman container can be easily attached to a network namespace created by `wg-netns`.
The example below starts a container connected to a netns named *ns-example*.
With `socat` you can forward TCP traffic from outside a network namespace to a port inside a network namespace.
~~~ bash
podman run -it --rm --network ns:/run/netns/ns-example docker.io/library/alpine wget -q -O - https://ipinfo.io
socat tcp-listen:$OUTSIDE_PORT,reuseaddr,fork "exec:ip netns exec $NETNS_NAME socat stdio 'tcp-connect:$INSIDE_PORT',nofork"
~~~
### Port Forwarding with Socat
[netns-publish](./extras/netns-publish.sh) is a small wrapper around `socat` that can forward TCP traffic from outside a network namespace to a port inside a network namespace.
Example: All connections to port 1234/tcp in the main/default netns are forwarded to port 5678/tcp in the *ns-example* namespace.
~~~ bash
@ -188,19 +163,7 @@ wg-netns up ns-example
echo 'Hello from ns-example!' > ./hello.txt
ip netns exec ns-example python3 -m http.server 5678
# terminal 2, setup port forwarding
./extras/netns-publish.sh 1234 ns-example 127.0.0.1:5678
socat tcp-listen:1234,reuseaddr,fork "exec:ip netns exec ns-example socat stdio 'tcp-connect:127.0.0.1:5678',nofork"
# terminal 3, test access
curl http://127.0.0.1:1234/hello.txt
~~~
### WireGuard with DynDNS
If your WireGuard server endpoint is a DynDNS domain you can use the [wg-resolve](./extras/wg-resolve/) script to periodically check the connectivity and re-resolve the endpoint if necessary.
### Firefox in Network Namespace
Start a dedicated Firefox profile with working audio inside the netns created by `wg-netns`.
~~~ bash
sudo ip netns exec ns-example sudo -u "$USER" "HOME=$HOME" "PULSE_SERVER=/run/user/$(id -u)/pulse/native" "PULSE_COOKIE=$HOME/.config/pulse/cookie" firefox -P vpn
~~~

@ -1,9 +0,0 @@
#!/bin/sh
set -eu
if [ $# -ne 3 ]; then
echo 'usage: netns-publish PUBLIC_PORT NETNS_NAME NETNS_ADDRESS:NETNS_PORT'
exit 1
fi
exec socat tcp-listen:"$1",reuseaddr,fork "exec:ip netns exec $2 socat stdio 'tcp-connect:$3',nofork"

@ -1,10 +0,0 @@
# network namespace name
WG_NAMESPACE=netns0
# local wireguard interface name
WG_INTERFACE=wg0
# server wireguard public key
WG_PEER=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# server wireguard interface ip
WG_GATEWAY=192.168.100.1
# server dyndns domain
WG_ENDPOINT=vpn.dyndns.example:51820

@ -1,12 +0,0 @@
#!/bin/sh
set -eu
# dependencies: cut, getent, ip, ping and wg
WG_ENDPOINT_DOMAIN="${WG_ENDPOINT%%:*}"
WG_ENDPOINT_PORT="${WG_ENDPOINT##*:}"
if ! ip netns exec "$WG_NAMESPACE" ping -q -c 1 -W "${WG_TIMEOUT:-5}" "$WG_GATEWAY"; then
echo 'probe failed, resolving endpoint'
ip netns exec "$WG_NAMESPACE" wg set "$WG_INTERFACE" peer "$WG_PEER" endpoint "$(getent hosts -- "$WG_ENDPOINT_DOMAIN" | cut -d ' ' -f 1):$WG_ENDPOINT_PORT"
fi

@ -1,10 +0,0 @@
[Unit]
Description=WireGuard Endpoint Resolver (%i)
Wants=network-online.target nss-lookup.target
After=network-online.target nss-lookup.target
[Service]
Type=oneshot
EnvironmentFile=%E/wireguard/%i.env
Environment=WG_ENDPOINT_RESOLUTION_RETRIES=infinity
ExecStart=/usr/local/lib/wg-resolve.sh

@ -1,9 +0,0 @@
[Unit]
Description=Minutely WireGuard Endpoint Resolver
[Timer]
OnCalendar=minutely
AccuracySec=5s
[Install]
WantedBy=timers.target

55
poetry.lock generated

@ -1,55 +0,0 @@
# This file is automatically @generated by Poetry 1.5.1 and should not be changed by hand.
[[package]]
name = "pyyaml"
version = "6.0.1"
description = "YAML parser and emitter for Python"
optional = false
python-versions = ">=3.6"
files = [
{file = "PyYAML-6.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a"},
{file = "PyYAML-6.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f"},
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"},
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"},
{file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"},
{file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"},
{file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"},
{file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"},
{file = "PyYAML-6.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab"},
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"},
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"},
{file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"},
{file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"},
{file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"},
{file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"},
{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"},
{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"},
{file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd"},
{file = "PyYAML-6.0.1-cp36-cp36m-win32.whl", hash = "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585"},
{file = "PyYAML-6.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa"},
{file = "PyYAML-6.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3"},
{file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27"},
{file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3"},
{file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c"},
{file = "PyYAML-6.0.1-cp37-cp37m-win32.whl", hash = "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba"},
{file = "PyYAML-6.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867"},
{file = "PyYAML-6.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595"},
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"},
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"},
{file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"},
{file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"},
{file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"},
{file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"},
{file = "PyYAML-6.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859"},
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"},
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"},
{file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"},
{file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"},
{file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"},
{file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"},
]
[metadata]
lock-version = "2.0"
python-versions = "^3.7"
content-hash = "26f0d3bbc0e7914fb97929a54b78c3c81fa915b86abdd44d69321cf5b462cd0d"

@ -1,19 +0,0 @@
[tool.poetry]
name = "wgnetns"
version = "2.3.4"
description = "wg-quick for network namespaces"
authors = ["dadevel <dadevel@disroot.org>"]
license = "MIT"
[tool.poetry.scripts]
wg-netns = "wgnetns.main:main"
[tool.poetry.dependencies]
python = "^3.7"
pyyaml = "^6.0"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

@ -0,0 +1,9 @@
#!/bin/sh
PS4='> '
set -eux
PREFIX="${PREFIX:-/usr/local}"
cd "$(dirname "$0")"
install -m 0755 -D ./wg-netns.py "$PREFIX/bin/wg-netns"
install -m 0644 -D ./wg-netns@.service "$PREFIX/lib/systemd/system/wg-netns@.service"

@ -4,7 +4,6 @@ from argparse import ArgumentParser, RawDescriptionHelpFormatter
from pathlib import Path
from typing import Any, Optional
import dataclasses
import getpass
import json
import os
import subprocess
@ -15,7 +14,6 @@ try:
YAML_SUPPORTED = True
except ModuleNotFoundError:
YAML_SUPPORTED = False
yaml = NotImplemented
WIREGUARD_DIR = Path('/etc/wireguard')
NETNS_DIR = Path('/etc/netns')
@ -23,18 +21,7 @@ VERBOSE = 0
SHELL = Path('/bin/sh')
def main():
try:
cli(sys.argv[1:])
sys.exit(0)
except Exception as e:
print(f'error: {e} ({e.__class__.__name__})', file=sys.stderr)
if VERBOSE:
raise
sys.exit(1)
def cli(args):
def main(args):
global WIREGUARD_DIR
global NETNS_DIR
global VERBOSE
@ -60,15 +47,6 @@ def cli(args):
parser.add_argument('-f', '--force', action='store_true', help='ignore errors')
parser.add_argument('profile', type=lambda x: Path(x).expanduser(), metavar='PROFILE', help='name or path of profile')
parser = subparsers.add_parser('list', help='list network namespaces')
parser = subparsers.add_parser('switch', help='open shell in namespace')
parser.add_argument('netns', metavar='NETNS', help='network namespace name')
parser = subparsers.add_parser('exec', help='run command in namespace')
parser.add_argument('netns', metavar='NETNS', help='network namespace name')
parser.add_argument('command', nargs='+', help='command')
opts = entrypoint.parse_args(args)
try:
@ -79,9 +57,8 @@ def cli(args):
except Exception as e:
raise RuntimeError(f'failed to load environment variable: {e} (e.__class__.__name__)') from e
namespace = Namespace.from_profile(opts.profile)
if opts.action == 'up':
_conditional_elevate()
namespace = Namespace.from_profile(opts.profile)
try:
namespace.setup()
except KeyboardInterrupt:
@ -90,33 +67,16 @@ def cli(args):
namespace.teardown(check=False)
raise
elif opts.action == 'down':
_conditional_elevate()
namespace = Namespace.from_profile(opts.profile)
namespace.teardown(check=not opts.force)
elif opts.action == 'list':
output = ip('-json', 'netns', capture=True)
if not output:
return
data = json.loads(output)
print('\n'.join(item['name'] for item in data))
elif opts.action == 'switch':
os.execvp('sudo', ['ip', 'ip', 'netns', 'exec', opts.netns, 'sudo', '-u', getpass.getuser(), '-D', Path.cwd().as_posix(), os.environ['SHELL'], '-i'])
elif opts.action == 'exec':
os.execvp('sudo', ['ip', 'ip', 'netns', 'exec', opts.netns, 'sudo', '-u', getpass.getuser(), '-D', Path.cwd().as_posix(), *opts.command])
else:
raise RuntimeError('congratulations, you reached unreachable code')
def _conditional_elevate() -> None:
if os.getuid() != 0 and os.isatty(sys.stdin.fileno()):
os.execvp('sudo', [sys.argv[0], *sys.argv])
@dataclasses.dataclass
class Peer:
name: str
public_key: str
preshared_key: Optional[str] = None
name: Optional[str] = None
endpoint: Optional[str] = None
persistent_keepalive: int = 0
allowed_ips: list[str] = dataclasses.field(default_factory=list)
@ -127,7 +87,7 @@ class Peer:
data = {key.replace('-', '_'): value for key, value in data.items()}
return cls(**data)
def setup(self, interface: Interface, namespace: str|None) -> Peer:
def setup(self, interface: Interface, namespace: Namespace) -> Peer:
options = [
'peer', self.public_key,
'preshared-key', '/dev/stdin' if self.preshared_key else '/dev/null',
@ -137,16 +97,15 @@ class Peer:
options.extend(('endpoint', self.endpoint))
if self.allowed_ips:
options.extend(('allowed-ips', ','.join(self.allowed_ips)))
wg('set', interface.name, *options, stdin=self.preshared_key, netns=namespace)
wg('set', interface.name, *options, stdin=self.preshared_key, netns=namespace.name)
return self
@dataclasses.dataclass
class Interface:
name: str
base_netns: str|None = None
private_key: Optional[str] = None
public_key: Optional[str] = None
public_key: str
private_key: str
address: list[str] = dataclasses.field(default_factory=list)
listen_port: int = 0
fwmark: int = 0
@ -154,118 +113,64 @@ class Interface:
peers: list[Peer] = dataclasses.field(default_factory=list)
@classmethod
def from_dict(cls, data: dict[str, Any], base_netns: str|None = None) -> Interface:
def from_dict(cls, data: dict[str, Any]) -> Interface:
peers = data.pop('peers', list())
peers = [Peer.from_dict({key.replace('-', '_'): value for key, value in peer.items()}) for peer in peers]
return cls(**data, peers=peers, base_netns=base_netns)
return cls(**data, peers=peers)
def setup(self, namespace: Namespace) -> Interface:
self._create()
self._configure_wireguard()
self._create(namespace)
self._configure_wireguard(namespace)
for peer in self.peers:
peer.setup(self, self.base_netns)
self._assign_namespace(namespace.name)
self._assign_addresses(namespace.name)
self._bring_up(namespace.name)
self._create_routes(namespace.name)
peer.setup(self, namespace)
self._assign_addresses(namespace)
self._bring_up(namespace)
self._create_routes(namespace)
return self
def _create(self) -> None:
ip('link', 'add', self.name, 'type', 'wireguard', netns=self.base_netns)
def _create(self, namespace: Namespace) -> None:
ip('link', 'add', self.name, 'type', 'wireguard')
ip('link', 'set', self.name, 'netns', namespace.name)
def _configure_wireguard(self) -> None:
wg('set', self.name, 'listen-port', self.listen_port, netns=self.base_netns)
wg('set', self.name, 'fwmark', self.fwmark, netns=self.base_netns)
if self.private_key:
wg('set', self.name, 'private-key', '/dev/stdin', stdin=self.private_key, netns=self.base_netns)
def _configure_wireguard(self, namespace: Namespace) -> None:
wg('set', self.name, 'listen-port', self.listen_port, netns=namespace.name)
wg('set', self.name, 'fwmark', self.fwmark, netns=namespace.name)
wg('set', self.name, 'private-key', '/dev/stdin', stdin=self.private_key, netns=namespace.name)
def _assign_namespace(self, namespace: str|None) -> None:
ip('link', 'set', self.name, 'netns', namespace if namespace else '1', netns=self.base_netns)
def _assign_addresses(self, namespace: str|None) -> None:
def _assign_addresses(self, namespace: Namespace) -> None:
for address in self.address:
ip('-6' if ':' in address else '-4', 'address', 'add', address, 'dev', self.name, netns=namespace)
ip('-n', namespace.name, '-6' if ':' in address else '-4', 'address', 'add', address, 'dev', self.name)
def _bring_up(self, namespace: str|None) -> None:
ip('link', 'set', 'dev', self.name, 'mtu', self.mtu, 'up', netns=namespace)
def _bring_up(self, namespace: Namespace) -> None:
ip('-n', namespace.name, 'link', 'set', 'dev', self.name, 'mtu', self.mtu, 'up')
def _create_routes(self, namespace: str|None):
def _create_routes(self, namespace: Namespace):
for peer in self.peers:
networks = peer.routes if peer.routes is not None else peer.allowed_ips
for network in networks:
ip('-6' if ':' in network else '-4', 'route', 'add', network, 'dev', self.name, netns=namespace)
ip('-n', namespace.name, '-6' if ':' in network else '-4', 'route', 'add', network, 'dev', self.name)
def teardown(self, namespace: Namespace, check=True) -> Interface:
if self.exists(namespace):
ip('link', 'set', self.name, 'down', check=check, netns=namespace.name)
ip('link', 'delete', self.name, check=check, netns=namespace.name)
ip('-n', namespace.name, 'link', 'set', self.name, 'down', check=check)
ip('-n', namespace.name, 'link', 'delete', self.name, check=check)
return self
def exists(self, namespace: Namespace) -> bool:
try:
ip('link', 'show', self.name, capture=True, netns=namespace.name)
ip('-n', namespace.name, 'link', 'show', self.name, capture=True)
return True
except Exception:
return False
@dataclasses.dataclass
class ScriptletItem:
command: str
host_namespace: bool = False
@classmethod
def from_str(cls, data: str) -> ScriptletItem:
return cls(command=data)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ScriptletItem:
data = {key.replace('-', '_'): value for key, value in data.items()}
host_namespace = bool(data.pop('host_namespace', None))
return cls(**data, host_namespace=host_namespace)
def run(self, netns: str|None):
if self.host_namespace or not netns:
host_eval(self.command)
else:
ip_netns_eval(self.command, netns=netns)
@dataclasses.dataclass
class Scriptlet:
items: list[ScriptletItem] = dataclasses.field(default_factory=list)
@classmethod
def from_value(cls, data) -> Scriptlet:
if isinstance(data, list):
return cls.from_list(data)
elif isinstance(data, str):
return cls.from_singleton(data)
else:
raise RuntimeError(f'unsupported scriptlet type: {data.__class__.__name__}')
@classmethod
def from_list(cls, data: list[Any]) -> Scriptlet:
items = [ScriptletItem.from_dict(item) for item in data]
return cls(items=items)
@classmethod
def from_singleton(cls, data) -> Scriptlet:
item = ScriptletItem.from_str(data)
return cls(items=[item])
def run(self, netns: str|None):
for item in self.items:
item.run(netns=netns)
@dataclasses.dataclass
class Namespace:
name: str|None
pre_up: Optional[Scriptlet] = None
post_up: Optional[Scriptlet] = None
pre_down: Optional[Scriptlet] = None
post_down: Optional[Scriptlet] = None
name: str
pre_up: Optional[str] = None
post_up: Optional[str] = None
pre_down: Optional[str] = None
post_down: Optional[str] = None
managed: bool = True
dns_server: list[str] = dataclasses.field(default_factory=list)
interfaces: list[Interface] = dataclasses.field(default_factory=list)
@ -275,7 +180,7 @@ class Namespace:
try:
return cls.from_dict(cls._read_profile(cls._find_profile(path)))
except Exception as e:
raise RuntimeError(f'failed to load profile: {e}') from e
raise RuntimeError('failed to load profile') from e
@staticmethod
def _find_profile(profile: Path) -> Path:
@ -301,35 +206,32 @@ class Namespace:
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Namespace:
data = {key.replace('-', '_'): value for key, value in data.items()}
scriptlets = {key: data.pop(key, None) for key in ['pre_up', 'post_up', 'pre_down', 'post_down']}
scriptlets = {key: Scriptlet.from_value(value) for key, value in scriptlets.items() if value is not None}
interfaces = data.pop('interfaces', list())
base_netns = data.pop('base_netns', None)
interfaces = [Interface.from_dict({key.replace('-', '_'): value for key, value in interface.items()}, base_netns=base_netns) for interface in interfaces]
return cls(**data, **scriptlets, interfaces=interfaces) # type: ignore
interfaces = [Interface.from_dict({key.replace('-', '_'): value for key, value in interface.items()}) for interface in interfaces]
return cls(**data, interfaces=interfaces)
def setup(self) -> Namespace:
if self.managed and self.name:
if self.pre_up:
ip_netns_eval(self.pre_up, netns=self.name)
if self.managed:
self._create()
self._write_resolvconf()
if self.pre_up:
self.pre_up.run(netns=self.name)
for interface in self.interfaces:
interface.setup(self)
if self.post_up:
self.post_up.run(netns=self.name)
ip_netns_eval(self.post_up, netns=self.name)
return self
def teardown(self, check=True) -> Namespace:
if self.pre_down:
self.pre_down.run(netns=self.name)
ip_netns_eval(self.pre_down, netns=self.name)
for interface in self.interfaces:
interface.teardown(self, check=check)
if self.post_down:
self.post_down.run(netns=self.name)
if self.managed and self.exists():
self._delete(check)
self._delete_resolvconf()
if self.post_down:
ip_netns_eval(self.post_down, netns=self.name)
return self
def exists(self) -> bool:
@ -338,14 +240,13 @@ class Namespace:
def _create(self) -> None:
ip('netns', 'add', self.name)
ip('link', 'set', 'dev', 'lo', 'up', netns=self.name)
ip('-n', self.name, 'link', 'set', 'dev', 'lo', 'up')
def _delete(self, check=True) -> None:
ip('netns', 'delete', self.name, check=check)
@property
def _resolvconf_path(self) -> Path:
assert self.name
return NETNS_DIR/self.name/'resolv.conf'
def _write_resolvconf(self) -> None:
@ -363,30 +264,23 @@ class Namespace:
pass
def wg(*args, netns: str|None = None, stdin: str|None = None, check=True, capture=False) -> str:
if netns:
return ip_netns_exec('wg', *args, netns=netns, stdin=stdin, check=check, capture=capture)
else:
return run('wg', *args, stdin=stdin, check=check, capture=capture)
def wg(*args, netns: str = None, stdin: str = None, check=True, capture=False) -> str:
return ip_netns_exec('wg', *args, netns=netns, stdin=stdin, check=check, capture=capture)
def ip_netns_eval(*args, netns: str, stdin: str|None = None, check=True, capture=False) -> str:
def ip_netns_eval(*args, netns: str = None, stdin: str = None, check=True, capture=False) -> str:
return ip_netns_exec(SHELL, '-c', *args, netns=netns, stdin=stdin, check=check, capture=capture)
def ip_netns_exec(*args, netns: str, stdin: str|None = None, check=True, capture=False) -> str:
def ip_netns_exec(*args, netns: str = None, stdin: str = None, check=True, capture=False) -> str:
return ip('netns', 'exec', netns, *args, stdin=stdin, check=check, capture=capture)
def ip(*args, stdin: str|None = None, netns: str|None =None, check=True, capture=False) -> str:
return run('ip', *(['-n', netns] if netns else []), *args, stdin=stdin, check=check, capture=capture)
def ip(*args, stdin: str = None, check=True, capture=False) -> str:
return run('ip', *args, stdin=stdin, check=check, capture=capture)
def host_eval(*args, stdin: str|None = None, check=True, capture=False) -> str:
return run(SHELL, '-c', *args, stdin=stdin, check=check, capture=capture)
def run(*args, stdin: str|None = None, check=True, capture=False) -> str:
def run(*args, stdin: str = None, check=True, capture=False) -> str:
args = [str(item) if item is not None else '' for item in args]
if VERBOSE:
print('>', ' '.join(args), file=sys.stderr)
@ -398,4 +292,11 @@ def run(*args, stdin: str|None = None, check=True, capture=False) -> str:
if __name__ == '__main__':
main()
try:
main(sys.argv[1:])
sys.exit(0)
except Exception as e:
print(f'error: {e} ({e.__class__.__name__})', file=sys.stderr)
if VERBOSE:
raise
sys.exit(1)

@ -13,22 +13,6 @@ RemainAfterExit=yes
WorkingDirectory=%E/wireguard
ConfigurationDirectory=wireguard
ConfigurationDirectoryMode=0700
CapabilityBoundingSet=CAP_NET_ADMIN CAP_SYS_ADMIN
LimitNOFILE=4096
LimitNPROC=512
LockPersonality=true
MemoryDenyWriteExecute=true
NoNewPrivileges=true
ProtectClock=true
ProtectHostname=true
RemoveIPC=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK
RestrictNamespaces=mnt net
RestrictRealtime=true
RestrictSUIDSGID=true
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
Loading…
Cancel
Save