snakevpn 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyvpn/__init__.py +3 -0
- pyvpn/__main__.py +3 -0
- pyvpn/apps/__init__.py +7 -0
- pyvpn/apps/cgroups.py +77 -0
- pyvpn/apps/launcher.py +72 -0
- pyvpn/apps/manager.py +59 -0
- pyvpn/apps/netns.py +36 -0
- pyvpn/apps/proc_connector.py +82 -0
- pyvpn/apps/selectors.py +138 -0
- pyvpn/apps/watcher.py +134 -0
- pyvpn/audit/__init__.py +52 -0
- pyvpn/cli/__init__.py +400 -0
- pyvpn/cli/install.py +151 -0
- pyvpn/cli/output.py +116 -0
- pyvpn/config/__init__.py +40 -0
- pyvpn/config/errors.py +22 -0
- pyvpn/config/loader.py +83 -0
- pyvpn/config/migrations.py +49 -0
- pyvpn/config/models.py +236 -0
- pyvpn/constants.py +50 -0
- pyvpn/daemon/__init__.py +1 -0
- pyvpn/daemon/api.py +109 -0
- pyvpn/daemon/client.py +173 -0
- pyvpn/daemon/core.py +487 -0
- pyvpn/daemon/persistence.py +107 -0
- pyvpn/daemon/planner.py +94 -0
- pyvpn/daemon/reconciler.py +541 -0
- pyvpn/daemon/server.py +223 -0
- pyvpn/dns/__init__.py +1 -0
- pyvpn/dns/aliases.py +78 -0
- pyvpn/dns/service.py +526 -0
- pyvpn/dns/upstream.py +195 -0
- pyvpn/match/__init__.py +69 -0
- pyvpn/match/asn.py +127 -0
- pyvpn/match/opts.py +277 -0
- pyvpn/match/pattern.py +595 -0
- pyvpn/match/policy.py +305 -0
- pyvpn/match/route.py +502 -0
- pyvpn/match/ruleset.py +331 -0
- pyvpn/platform/__init__.py +1 -0
- pyvpn/platform/base.py +33 -0
- pyvpn/platform/linux/__init__.py +1 -0
- pyvpn/platform/linux/dns.py +25 -0
- pyvpn/platform/linux/netlink.py +353 -0
- pyvpn/py.typed +0 -0
- pyvpn/routing/__init__.py +1 -0
- pyvpn/routing/plan.py +113 -0
- pyvpn/rulefile/__init__.py +21 -0
- pyvpn/rulefile/commands.py +172 -0
- pyvpn/rulefile/file.py +274 -0
- pyvpn/services.py +61 -0
- pyvpn/state.py +84 -0
- pyvpn/targets/__init__.py +16 -0
- pyvpn/targets/probes.py +58 -0
- pyvpn/targets/resolver.py +30 -0
- pyvpn/targets/watcher.py +102 -0
- snakevpn-0.0.1.dist-info/METADATA +156 -0
- snakevpn-0.0.1.dist-info/RECORD +61 -0
- snakevpn-0.0.1.dist-info/WHEEL +4 -0
- snakevpn-0.0.1.dist-info/entry_points.txt +2 -0
- snakevpn-0.0.1.dist-info/licenses/LICENSE +674 -0
pyvpn/__init__.py
ADDED
pyvpn/__main__.py
ADDED
pyvpn/apps/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Linux process selection, cgroup management and launch helpers."""
|
|
2
|
+
|
|
3
|
+
from pyvpn.apps.cgroups import CgroupManager
|
|
4
|
+
from pyvpn.apps.manager import AppManager
|
|
5
|
+
from pyvpn.apps.selectors import ProcessInfo, SelectorMatcher, read_process
|
|
6
|
+
|
|
7
|
+
__all__ = ["AppManager", "CgroupManager", "ProcessInfo", "SelectorMatcher", "read_process"]
|
pyvpn/apps/cgroups.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Safe cgroup v2 operations for pyvpn policy processes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from pyvpn.constants import CGROUP_ROOT, MAX_POLICIES, policy_cgroup
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CgroupError(RuntimeError):
|
|
11
|
+
"""A cgroup operation could not be completed."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CgroupManager:
|
|
15
|
+
"""Manage ``pyvpn.slice/p-<id>`` beneath a cgroup v2 mount.
|
|
16
|
+
|
|
17
|
+
``root`` is the cgroup2 mount (or a temporary directory in tests). The
|
|
18
|
+
manager never mounts or changes the host's cgroup hierarchy itself.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, root: str | Path = "/sys/fs/cgroup") -> None:
|
|
22
|
+
self.root = Path(root)
|
|
23
|
+
self.slice = self.root / CGROUP_ROOT
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def _validate(policy_id: int) -> None:
|
|
27
|
+
if not 1 <= policy_id <= MAX_POLICIES:
|
|
28
|
+
raise ValueError(f"policy id must be in 1..{MAX_POLICIES}")
|
|
29
|
+
|
|
30
|
+
def create(self, policy_id: int) -> Path:
|
|
31
|
+
self._validate(policy_id)
|
|
32
|
+
if not (self.root / "cgroup.controllers").exists() and self.root == Path("/sys/fs/cgroup"):
|
|
33
|
+
raise CgroupError("cgroup v2 is not mounted at /sys/fs/cgroup")
|
|
34
|
+
self.slice.mkdir(parents=True, exist_ok=True)
|
|
35
|
+
path = self.root / policy_cgroup(policy_id)
|
|
36
|
+
path.mkdir(exist_ok=True)
|
|
37
|
+
return path
|
|
38
|
+
|
|
39
|
+
def place_pid(self, pid: int, policy_id: int) -> Path:
|
|
40
|
+
if pid <= 0:
|
|
41
|
+
raise ValueError("pid must be positive")
|
|
42
|
+
path = self.create(policy_id)
|
|
43
|
+
procs = path / "cgroup.procs"
|
|
44
|
+
try:
|
|
45
|
+
procs.write_text(f"{pid}\n", encoding="ascii")
|
|
46
|
+
except OSError as exc:
|
|
47
|
+
raise CgroupError(f"cannot place pid {pid} in {path}: {exc}") from exc
|
|
48
|
+
return path
|
|
49
|
+
|
|
50
|
+
def path_for(self, policy_id: int) -> Path:
|
|
51
|
+
self._validate(policy_id)
|
|
52
|
+
return self.root / policy_cgroup(policy_id)
|
|
53
|
+
|
|
54
|
+
def remove(self, policy_id: int) -> None:
|
|
55
|
+
path = self.path_for(policy_id)
|
|
56
|
+
try:
|
|
57
|
+
path.rmdir()
|
|
58
|
+
except FileNotFoundError:
|
|
59
|
+
return
|
|
60
|
+
except OSError as exc:
|
|
61
|
+
raise CgroupError(f"cannot remove non-empty cgroup {path}: {exc}") from exc
|
|
62
|
+
|
|
63
|
+
def remove_all(self) -> None:
|
|
64
|
+
if not self.slice.exists():
|
|
65
|
+
return
|
|
66
|
+
for child in sorted(self.slice.glob("p-*")):
|
|
67
|
+
try:
|
|
68
|
+
child.rmdir()
|
|
69
|
+
except OSError as exc:
|
|
70
|
+
raise CgroupError(f"cannot remove cgroup {child}: {exc}") from exc
|
|
71
|
+
try:
|
|
72
|
+
self.slice.rmdir()
|
|
73
|
+
except OSError as exc:
|
|
74
|
+
raise CgroupError(f"cannot remove cgroup slice {self.slice}: {exc}") from exc
|
|
75
|
+
|
|
76
|
+
def cgroup_path(self, policy_id: int) -> str:
|
|
77
|
+
return policy_cgroup(policy_id)
|
pyvpn/apps/launcher.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Unprivileged ``pyvpn run`` daemon hand-off and exec helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import socket
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Literal, NoReturn
|
|
11
|
+
|
|
12
|
+
from pyvpn.constants import SOCKET_PATH
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DaemonUnavailable(RuntimeError):
|
|
16
|
+
"""The pyvpn daemon could not accept the placement request."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def request_place_pid(
|
|
20
|
+
policy: str | int,
|
|
21
|
+
*,
|
|
22
|
+
pid: int | None = None,
|
|
23
|
+
socket_path: str | Path = SOCKET_PATH,
|
|
24
|
+
timeout: float = 2.0,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Ask the daemon to place this process in the requested policy cgroup."""
|
|
27
|
+
process_id = os.getpid() if pid is None else pid
|
|
28
|
+
if process_id != os.getpid():
|
|
29
|
+
raise ValueError("an unprivileged launcher may only place its own PID")
|
|
30
|
+
request = {"id": 1, "method": "place_pid", "params": {"pid": process_id, "policy": policy}}
|
|
31
|
+
try:
|
|
32
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
|
|
33
|
+
client.settimeout(timeout)
|
|
34
|
+
client.connect(str(socket_path))
|
|
35
|
+
client.sendall((json.dumps(request, separators=(",", ":")) + "\n").encode())
|
|
36
|
+
stream = client.makefile("rb")
|
|
37
|
+
response = stream.readline(64 * 1024 + 1)
|
|
38
|
+
except OSError as exc:
|
|
39
|
+
raise DaemonUnavailable(f"cannot contact pyvpn daemon: {exc}") from exc
|
|
40
|
+
if not response or len(response) > 64 * 1024:
|
|
41
|
+
raise DaemonUnavailable("daemon returned an empty or oversized response")
|
|
42
|
+
try:
|
|
43
|
+
result = json.loads(response)
|
|
44
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
45
|
+
raise DaemonUnavailable("daemon returned an invalid response") from exc
|
|
46
|
+
if result.get("id") != 1 or result.get("ok") is not True:
|
|
47
|
+
error = result.get("error") or {}
|
|
48
|
+
raise DaemonUnavailable(str(error.get("message", "daemon rejected placement")))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run(
|
|
52
|
+
policy: str | int,
|
|
53
|
+
command: Sequence[str],
|
|
54
|
+
*,
|
|
55
|
+
socket_path: str | Path = SOCKET_PATH,
|
|
56
|
+
isolation: Literal["none", "netns"] = "none",
|
|
57
|
+
) -> NoReturn:
|
|
58
|
+
"""Place this process, then replace it with ``command`` via execvp."""
|
|
59
|
+
if not command:
|
|
60
|
+
raise ValueError("a command is required")
|
|
61
|
+
if isolation == "netns":
|
|
62
|
+
# Refuse rather than run unisolated: the unprivileged launcher cannot
|
|
63
|
+
# create a namespace, and the daemon does not yet prepare one (veth,
|
|
64
|
+
# routes) and confirm it is ready before exec.
|
|
65
|
+
from pyvpn.apps.netns import NetworkNamespaceUnavailable
|
|
66
|
+
|
|
67
|
+
raise NetworkNamespaceUnavailable(
|
|
68
|
+
"isolation: netns is not supported yet; the daemon must prepare the namespace"
|
|
69
|
+
)
|
|
70
|
+
request_place_pid(policy, socket_path=socket_path)
|
|
71
|
+
os.execvp(command[0], list(command))
|
|
72
|
+
raise AssertionError("execvp returned")
|
pyvpn/apps/manager.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Real app manager implementing the daemon's Phase 0 app contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Sequence
|
|
6
|
+
|
|
7
|
+
from pyvpn.apps.cgroups import CgroupManager
|
|
8
|
+
from pyvpn.config.models import AppGroup, Policy
|
|
9
|
+
from pyvpn.constants import policy_cgroup
|
|
10
|
+
from pyvpn.state import AppBinding
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AppManager:
|
|
14
|
+
"""Create policy cgroups and expose bindings to the daemon reconcile loop."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, cgroups: CgroupManager) -> None:
|
|
17
|
+
self.cgroups = cgroups
|
|
18
|
+
self._bindings: dict[int, AppBinding] = {}
|
|
19
|
+
|
|
20
|
+
async def bind(self, policy_id: int, policy: Policy, groups: Sequence[AppGroup]) -> AppBinding:
|
|
21
|
+
if not policy.apps:
|
|
22
|
+
binding = AppBinding(policy_id, any_process=bool(policy.domains))
|
|
23
|
+
else:
|
|
24
|
+
self.cgroups.create(policy_id)
|
|
25
|
+
group_map = {group.name: group.apps for group in groups}
|
|
26
|
+
uids: set[int] = set()
|
|
27
|
+
for ref in policy.apps:
|
|
28
|
+
selectors = (
|
|
29
|
+
group_map.get(ref.removeprefix("group:"), ())
|
|
30
|
+
if isinstance(ref, str)
|
|
31
|
+
else (ref,)
|
|
32
|
+
)
|
|
33
|
+
uids.update(selector.uid for selector in selectors if selector.uid is not None)
|
|
34
|
+
if policy.exclude_apps:
|
|
35
|
+
# A raw UID match would also catch excluded apps. Leave those
|
|
36
|
+
# processes to the exclusion-aware watcher, which places them
|
|
37
|
+
# in the policy cgroup individually.
|
|
38
|
+
uids.clear()
|
|
39
|
+
binding = AppBinding(
|
|
40
|
+
policy_id,
|
|
41
|
+
cgroup_paths=(policy_cgroup(policy_id),),
|
|
42
|
+
uids=tuple(sorted(uids)),
|
|
43
|
+
)
|
|
44
|
+
self._bindings[policy_id] = binding
|
|
45
|
+
return binding
|
|
46
|
+
|
|
47
|
+
async def unbind(self, policy_id: int) -> None:
|
|
48
|
+
self._bindings.pop(policy_id, None)
|
|
49
|
+
self.cgroups.remove(policy_id)
|
|
50
|
+
|
|
51
|
+
async def place_pid(self, pid: int, policy_id: int) -> None:
|
|
52
|
+
self.cgroups.place_pid(pid, policy_id)
|
|
53
|
+
|
|
54
|
+
def bindings(self) -> AsyncIterator[AppBinding]:
|
|
55
|
+
async def generate() -> AsyncIterator[AppBinding]:
|
|
56
|
+
for binding in tuple(self._bindings.values()):
|
|
57
|
+
yield binding
|
|
58
|
+
|
|
59
|
+
return generate()
|
pyvpn/apps/netns.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Small Linux network-namespace exec helper for isolated policies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import NoReturn
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NetworkNamespaceUnavailable(RuntimeError):
|
|
11
|
+
"""Network namespace isolation is unavailable on this kernel/runtime."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def enter_network_namespace() -> None:
|
|
15
|
+
"""Create a private network namespace for the calling process."""
|
|
16
|
+
unshare = getattr(os, "unshare", None)
|
|
17
|
+
if not callable(unshare):
|
|
18
|
+
raise NetworkNamespaceUnavailable("os.unshare is unavailable on this platform")
|
|
19
|
+
clone_newnet = getattr(os, "CLONE_NEWNET", 0x40000000)
|
|
20
|
+
try:
|
|
21
|
+
unshare(clone_newnet)
|
|
22
|
+
except OSError as exc:
|
|
23
|
+
raise NetworkNamespaceUnavailable(f"cannot create network namespace: {exc}") from exc
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def exec_isolated(command: Sequence[str]) -> NoReturn:
|
|
27
|
+
"""Enter a new network namespace and replace the process with command.
|
|
28
|
+
|
|
29
|
+
Namespace interface setup and routing remain the daemon's responsibility;
|
|
30
|
+
this helper intentionally does not configure host networking.
|
|
31
|
+
"""
|
|
32
|
+
if not command:
|
|
33
|
+
raise ValueError("a command is required")
|
|
34
|
+
enter_network_namespace()
|
|
35
|
+
os.execvp(command[0], list(command))
|
|
36
|
+
raise AssertionError("execvp returned")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Linux proc-connector subscription for PROC_EVENT_EXEC notifications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import socket
|
|
8
|
+
import struct
|
|
9
|
+
from collections.abc import AsyncIterator
|
|
10
|
+
|
|
11
|
+
# Linux netlink connector constants and message layout.
|
|
12
|
+
_NETLINK_CONNECTOR = 11
|
|
13
|
+
_NLMSG_DONE = 3
|
|
14
|
+
_NLMSG_ERROR = 2
|
|
15
|
+
_NLM_F_REQUEST = 1
|
|
16
|
+
_CN_IDX_PROC = 1
|
|
17
|
+
_CN_VAL_PROC = 1
|
|
18
|
+
_PROC_CN_MCAST_LISTEN = 1
|
|
19
|
+
_PROC_EVENT_EXEC = 0x00000002
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _listen_message() -> bytes:
|
|
23
|
+
# nlmsghdr + cn_msg + proc_cn_mcast_op
|
|
24
|
+
payload = struct.pack("=IIIIHH", _CN_IDX_PROC, _CN_VAL_PROC, 0, 0, 4, 0)
|
|
25
|
+
payload += struct.pack("=I", _PROC_CN_MCAST_LISTEN)
|
|
26
|
+
length = 16 + len(payload)
|
|
27
|
+
return struct.pack("=IHHII", length, _NLMSG_DONE, _NLM_F_REQUEST, 1, 0) + payload
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _exec_pid(datagram: bytes) -> int | None:
|
|
31
|
+
"""Extract the exec event's tgid from a netlink connector datagram."""
|
|
32
|
+
offset = 0
|
|
33
|
+
while offset + 16 <= len(datagram):
|
|
34
|
+
length, kind, _flags, _seq, _pid = struct.unpack_from("=IHHII", datagram, offset)
|
|
35
|
+
if length < 16 or offset + length > len(datagram):
|
|
36
|
+
return None
|
|
37
|
+
if kind == _NLMSG_ERROR:
|
|
38
|
+
raise OSError("proc connector reported a netlink error")
|
|
39
|
+
# connector header: idx, val, seq, ack, len, flags; event header:
|
|
40
|
+
# what, cpu, timestamp. EXEC data starts with process pid, tgid.
|
|
41
|
+
start = offset + 16
|
|
42
|
+
if length >= 16 + 20 + 16 + 8:
|
|
43
|
+
what = struct.unpack_from("=I", datagram, start + 20)[0]
|
|
44
|
+
if what == _PROC_EVENT_EXEC:
|
|
45
|
+
return int(struct.unpack_from("=I", datagram, start + 20 + 16 + 4)[0])
|
|
46
|
+
offset += (length + 3) & ~3
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ProcExecEvents:
|
|
51
|
+
"""A live PROC_EVENT_EXEC subscription.
|
|
52
|
+
|
|
53
|
+
The netlink socket is subscribed when ``open()`` returns, so the kernel
|
|
54
|
+
queues exec events from that moment on, even before iteration starts.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, sock: socket.socket) -> None:
|
|
58
|
+
self._sock = sock
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
async def open(cls) -> ProcExecEvents:
|
|
62
|
+
"""Subscribe to exec events. Requires Linux proc-connector access."""
|
|
63
|
+
sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, _NETLINK_CONNECTOR)
|
|
64
|
+
try:
|
|
65
|
+
sock.setblocking(False)
|
|
66
|
+
sock.bind((os.getpid(), _CN_IDX_PROC))
|
|
67
|
+
await asyncio.get_running_loop().sock_sendall(sock, _listen_message())
|
|
68
|
+
except BaseException:
|
|
69
|
+
sock.close()
|
|
70
|
+
raise
|
|
71
|
+
return cls(sock)
|
|
72
|
+
|
|
73
|
+
async def __aiter__(self) -> AsyncIterator[int]:
|
|
74
|
+
loop = asyncio.get_running_loop()
|
|
75
|
+
while True:
|
|
76
|
+
data = await loop.sock_recv(self._sock, 65536)
|
|
77
|
+
pid = _exec_pid(data)
|
|
78
|
+
if pid is not None:
|
|
79
|
+
yield pid
|
|
80
|
+
|
|
81
|
+
def close(self) -> None:
|
|
82
|
+
self._sock.close()
|
pyvpn/apps/selectors.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Process metadata extraction and configuration selector matching."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import pwd
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from pyvpn.config.models import AppGroup, AppSelector, Policy
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class ProcessInfo:
|
|
16
|
+
pid: int
|
|
17
|
+
exe: str | None = None
|
|
18
|
+
name: str | None = None
|
|
19
|
+
uid: int | None = None
|
|
20
|
+
user: str | None = None
|
|
21
|
+
cgroup: str = ""
|
|
22
|
+
flatpak: str | None = None
|
|
23
|
+
snap: str | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_exe(link: Path) -> str | None:
|
|
27
|
+
"""The process's executable path as the kernel reports it.
|
|
28
|
+
|
|
29
|
+
Read with ``readlink``, not resolved: the target lives in the process's
|
|
30
|
+
mount namespace (a Flatpak's ``/app/bin/...``) and may be gone after an
|
|
31
|
+
upgrade (``... (deleted)``), and neither must hide the process. Raises
|
|
32
|
+
``FileNotFoundError`` for exited processes and kernel threads; returns
|
|
33
|
+
None when the link is not readable (e.g. permission).
|
|
34
|
+
"""
|
|
35
|
+
try:
|
|
36
|
+
target = os.readlink(link)
|
|
37
|
+
except FileNotFoundError:
|
|
38
|
+
raise
|
|
39
|
+
except OSError:
|
|
40
|
+
return None
|
|
41
|
+
return target.removesuffix(" (deleted)")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def read_process(pid: int, proc_root: str | Path = "/proc") -> ProcessInfo | None:
|
|
45
|
+
"""Read process metadata; return None when it exited or is inaccessible."""
|
|
46
|
+
if pid <= 0:
|
|
47
|
+
return None
|
|
48
|
+
base = Path(proc_root) / str(pid)
|
|
49
|
+
try:
|
|
50
|
+
exe = _read_exe(base / "exe")
|
|
51
|
+
name = (base / "comm").read_text(encoding="utf-8").strip()
|
|
52
|
+
status = (base / "status").read_text(encoding="utf-8")
|
|
53
|
+
cgroup = (base / "cgroup").read_text(encoding="utf-8")
|
|
54
|
+
except (OSError, UnicodeError):
|
|
55
|
+
return None
|
|
56
|
+
uid_line = next((line for line in status.splitlines() if line.startswith("Uid:")), None)
|
|
57
|
+
if uid_line is None:
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
uid = int(uid_line.split()[1])
|
|
61
|
+
user = pwd.getpwuid(uid).pw_name
|
|
62
|
+
except (ValueError, IndexError, KeyError):
|
|
63
|
+
user = None
|
|
64
|
+
try:
|
|
65
|
+
uid = int(uid_line.split()[1])
|
|
66
|
+
except (ValueError, IndexError):
|
|
67
|
+
return None
|
|
68
|
+
paths = [line.split(":", 2)[-1] for line in cgroup.splitlines() if ":" in line]
|
|
69
|
+
joined = "\n".join(paths)
|
|
70
|
+
flatpak = None
|
|
71
|
+
snap = None
|
|
72
|
+
for component in joined.split("/"):
|
|
73
|
+
if component.startswith("app-flatpak-"):
|
|
74
|
+
flatpak = component.removeprefix("app-flatpak-").split(".scope", 1)[0]
|
|
75
|
+
elif component.startswith("snap."):
|
|
76
|
+
bits = component.split(".")
|
|
77
|
+
if len(bits) >= 3:
|
|
78
|
+
snap = bits[1]
|
|
79
|
+
return ProcessInfo(pid, exe, name, uid, user, joined, flatpak, snap)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class SelectorMatcher:
|
|
83
|
+
"""Expand groups and match process metadata against policies."""
|
|
84
|
+
|
|
85
|
+
def __init__(self, groups: Iterable[AppGroup] = ()) -> None:
|
|
86
|
+
self.groups = {group.name: group.apps for group in groups}
|
|
87
|
+
|
|
88
|
+
def expand(self, refs: Iterable[AppSelector | str]) -> tuple[AppSelector, ...]:
|
|
89
|
+
expanded: list[AppSelector] = []
|
|
90
|
+
for ref in refs:
|
|
91
|
+
if isinstance(ref, AppSelector):
|
|
92
|
+
expanded.append(ref)
|
|
93
|
+
elif ref.startswith("group:"):
|
|
94
|
+
name = ref.removeprefix("group:")
|
|
95
|
+
if name not in self.groups:
|
|
96
|
+
raise ValueError(f"unknown app group {name!r}")
|
|
97
|
+
expanded.extend(self.groups[name])
|
|
98
|
+
else:
|
|
99
|
+
raise ValueError(f"invalid app reference {ref!r}")
|
|
100
|
+
return tuple(expanded)
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def matches(selector: AppSelector, process: ProcessInfo) -> bool:
|
|
104
|
+
field: str
|
|
105
|
+
expected: object
|
|
106
|
+
field, expected = next(iter(selector.model_dump(exclude_none=True).items()))
|
|
107
|
+
if field == "exe":
|
|
108
|
+
return process.exe == expected
|
|
109
|
+
if field == "name":
|
|
110
|
+
return process.name == expected
|
|
111
|
+
if field == "uid":
|
|
112
|
+
return process.uid == expected
|
|
113
|
+
if field == "user":
|
|
114
|
+
return process.user == expected
|
|
115
|
+
if field == "flatpak":
|
|
116
|
+
return process.flatpak == expected or (
|
|
117
|
+
process.flatpak is not None and process.flatpak.startswith(f"{expected}-")
|
|
118
|
+
)
|
|
119
|
+
if field == "snap":
|
|
120
|
+
return process.snap == expected
|
|
121
|
+
if field == "unit":
|
|
122
|
+
unit = str(expected)
|
|
123
|
+
return any(
|
|
124
|
+
part == unit or part.endswith("/" + unit) for part in process.cgroup.splitlines()
|
|
125
|
+
)
|
|
126
|
+
return False
|
|
127
|
+
|
|
128
|
+
def matches_policy(self, policy: Policy, process: ProcessInfo) -> bool:
|
|
129
|
+
excluded = self.expand(policy.exclude_apps)
|
|
130
|
+
if any(self.matches(selector, process) for selector in excluded):
|
|
131
|
+
return False
|
|
132
|
+
return any(self.matches(selector, process) for selector in self.expand(policy.apps))
|
|
133
|
+
|
|
134
|
+
def matching_policy(self, policies: Iterable[Policy], process: ProcessInfo) -> int | None:
|
|
135
|
+
for policy_id, policy in enumerate(policies, start=1):
|
|
136
|
+
if self.matches_policy(policy, process):
|
|
137
|
+
return policy_id
|
|
138
|
+
return None
|
pyvpn/apps/watcher.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Process execution watcher with an initial procfs reconciliation scan.
|
|
2
|
+
|
|
3
|
+
The watcher accepts an event source so its matching and placement behaviour is
|
|
4
|
+
fully testable without opening privileged netlink sockets.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import errno
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Iterable
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
|
|
16
|
+
from pyvpn.apps.cgroups import CgroupError
|
|
17
|
+
from pyvpn.apps.selectors import SelectorMatcher, read_process
|
|
18
|
+
from pyvpn.config.models import AppGroup, Policy
|
|
19
|
+
from pyvpn.constants import policy_cgroup
|
|
20
|
+
|
|
21
|
+
log = logging.getLogger(__name__)
|
|
22
|
+
Place = Callable[[int, int], Awaitable[None]]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Subscription(Protocol):
|
|
26
|
+
"""An open process-event subscription (``ProcExecEvents``)."""
|
|
27
|
+
|
|
28
|
+
def __aiter__(self) -> AsyncIterator[int]: ...
|
|
29
|
+
|
|
30
|
+
def close(self) -> None: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProcessWatcher:
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
policies: Iterable[Policy],
|
|
37
|
+
place_pid: Place,
|
|
38
|
+
*,
|
|
39
|
+
groups: Iterable[AppGroup] = (),
|
|
40
|
+
proc_root: str | Path = "/proc",
|
|
41
|
+
) -> None:
|
|
42
|
+
self.policies = tuple(policies)
|
|
43
|
+
self.place_pid = place_pid
|
|
44
|
+
self.matcher = SelectorMatcher(groups)
|
|
45
|
+
self.proc_root = Path(proc_root)
|
|
46
|
+
self._stopped = asyncio.Event()
|
|
47
|
+
|
|
48
|
+
async def handle_exec(self, pid: int) -> int | None:
|
|
49
|
+
"""Place ``pid`` in its policy cgroup; return the matching policy id.
|
|
50
|
+
|
|
51
|
+
Placement is decided from the process's current cgroup, not from a
|
|
52
|
+
cache of PIDs, so a reused PID is always re-evaluated. A process that
|
|
53
|
+
exits before it can be placed is skipped; other placement failures
|
|
54
|
+
are logged and the watcher keeps running.
|
|
55
|
+
"""
|
|
56
|
+
policy_id, _ = await self._place(pid)
|
|
57
|
+
return policy_id
|
|
58
|
+
|
|
59
|
+
async def _place(self, pid: int) -> tuple[int | None, bool]:
|
|
60
|
+
"""Return the matching policy id and whether ``pid`` was moved."""
|
|
61
|
+
process = read_process(pid, self.proc_root)
|
|
62
|
+
if process is None:
|
|
63
|
+
return None, False
|
|
64
|
+
policy_id = self.matcher.matching_policy(self.policies, process)
|
|
65
|
+
if policy_id is None or _in_cgroup(process.cgroup, policy_cgroup(policy_id)):
|
|
66
|
+
return policy_id, False
|
|
67
|
+
try:
|
|
68
|
+
await self.place_pid(pid, policy_id)
|
|
69
|
+
except (CgroupError, OSError):
|
|
70
|
+
if not (self.proc_root / str(pid)).exists():
|
|
71
|
+
log.debug("process %s exited before cgroup placement", pid)
|
|
72
|
+
else:
|
|
73
|
+
log.exception("cannot place process %s in policy %s", pid, policy_id)
|
|
74
|
+
return policy_id, False
|
|
75
|
+
return policy_id, True
|
|
76
|
+
|
|
77
|
+
async def scan(self) -> int:
|
|
78
|
+
"""Place already-running matching processes; return number moved."""
|
|
79
|
+
try:
|
|
80
|
+
pids = sorted(
|
|
81
|
+
int(entry.name) for entry in self.proc_root.iterdir() if entry.name.isdecimal()
|
|
82
|
+
)
|
|
83
|
+
except OSError:
|
|
84
|
+
return 0
|
|
85
|
+
moved = 0
|
|
86
|
+
for pid in pids:
|
|
87
|
+
_, was_moved = await self._place(pid)
|
|
88
|
+
moved += was_moved
|
|
89
|
+
return moved
|
|
90
|
+
|
|
91
|
+
async def run(self, events: AsyncIterable[int]) -> None:
|
|
92
|
+
"""Scan ``/proc``, then place processes from ``events``.
|
|
93
|
+
|
|
94
|
+
``events`` must already be subscribed when this is called, so that a
|
|
95
|
+
process started during the scan is queued as an event, not missed.
|
|
96
|
+
"""
|
|
97
|
+
await self.scan()
|
|
98
|
+
async for pid in events:
|
|
99
|
+
if self._stopped.is_set():
|
|
100
|
+
break
|
|
101
|
+
await self._place(pid)
|
|
102
|
+
|
|
103
|
+
async def run_proc_connector(self) -> None:
|
|
104
|
+
"""Subscribe to Linux PROC_EVENT_EXEC events, then scan and watch."""
|
|
105
|
+
from pyvpn.apps.proc_connector import ProcExecEvents
|
|
106
|
+
|
|
107
|
+
await self.run_subscribed(ProcExecEvents.open)
|
|
108
|
+
|
|
109
|
+
async def run_subscribed(self, subscribe: Callable[[], Awaitable[Subscription]]) -> None:
|
|
110
|
+
"""Watch events from ``subscribe()``, recovering from buffer overruns.
|
|
111
|
+
|
|
112
|
+
When the kernel drops events because the socket buffer overflowed
|
|
113
|
+
(``ENOBUFS``), the subscription is reopened and ``/proc`` rescanned,
|
|
114
|
+
so processes whose events were lost are still placed.
|
|
115
|
+
"""
|
|
116
|
+
while not self._stopped.is_set():
|
|
117
|
+
events = await subscribe()
|
|
118
|
+
try:
|
|
119
|
+
await self.run(events)
|
|
120
|
+
return
|
|
121
|
+
except OSError as exc:
|
|
122
|
+
if exc.errno != errno.ENOBUFS:
|
|
123
|
+
raise
|
|
124
|
+
log.warning("process events overran the socket buffer; resubscribing")
|
|
125
|
+
finally:
|
|
126
|
+
events.close()
|
|
127
|
+
|
|
128
|
+
def stop(self) -> None:
|
|
129
|
+
self._stopped.set()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _in_cgroup(cgroups: str, path: str) -> bool:
|
|
133
|
+
"""Whether any of the process's cgroup paths is ``path``."""
|
|
134
|
+
return any(line.strip("/") == path for line in cgroups.splitlines())
|
pyvpn/audit/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Describe DNS policy configuration and stub readiness for the daemon's audit."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from importlib.util import find_spec
|
|
5
|
+
|
|
6
|
+
from pyvpn.dns.upstream import upstream_endpoint
|
|
7
|
+
from pyvpn.state import PolicyPlan
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class DnsAudit:
|
|
12
|
+
stub_listening: bool
|
|
13
|
+
upstream_interface: str | None
|
|
14
|
+
upstream_problem: str | None
|
|
15
|
+
firefox_canary: bool
|
|
16
|
+
requested_packet_blocks: tuple[str, ...]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def audit_dns(plan: PolicyPlan, *, listening: bool) -> DnsAudit:
|
|
20
|
+
leak = plan.leak
|
|
21
|
+
enabled = leak.dns_via_target and plan.dns_stub_port is not None
|
|
22
|
+
interface = None
|
|
23
|
+
if not enabled:
|
|
24
|
+
problem = "No per-policy DNS stub configured"
|
|
25
|
+
elif not listening:
|
|
26
|
+
problem = "Per-policy DNS stub is not listening"
|
|
27
|
+
elif plan.route != "dev" or not plan.interface:
|
|
28
|
+
problem = "No active target interface"
|
|
29
|
+
elif leak.dns_protocol == "doh" and find_spec("aiohttp") is None:
|
|
30
|
+
problem = "DNS over HTTPS requires the snakevpn[doh] extra"
|
|
31
|
+
else:
|
|
32
|
+
try:
|
|
33
|
+
upstream_endpoint(leak.dns_server, leak.dns_protocol)
|
|
34
|
+
except ValueError:
|
|
35
|
+
problem = "Invalid DNS upstream address"
|
|
36
|
+
else:
|
|
37
|
+
problem = None
|
|
38
|
+
interface = plan.interface
|
|
39
|
+
|
|
40
|
+
packet_blocks = (
|
|
41
|
+
("DoH", leak.block_doh),
|
|
42
|
+
("DoT", leak.block_dot),
|
|
43
|
+
("QUIC", leak.block_quic),
|
|
44
|
+
("IPv6", leak.ipv6 == "block"),
|
|
45
|
+
)
|
|
46
|
+
return DnsAudit(
|
|
47
|
+
stub_listening=enabled and listening,
|
|
48
|
+
upstream_interface=interface,
|
|
49
|
+
upstream_problem=problem,
|
|
50
|
+
firefox_canary=enabled and listening and leak.block_doh,
|
|
51
|
+
requested_packet_blocks=tuple(name for name, requested in packet_blocks if requested),
|
|
52
|
+
)
|