208 lines
5.6 KiB
Python
208 lines
5.6 KiB
Python
#!/usr/bin/env python3
|
|
"""LD FDPI Linux privileged helper.
|
|
|
|
JSON-lines protocol over /run/ld-fdpi/helper.sock.
|
|
Only allowlisted, parameter-free actions are accepted.
|
|
|
|
Phase 2: app-scoped QUIC guard through nftables cgroup matching.
|
|
"""
|
|
import grp
|
|
import json
|
|
import os
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
|
|
SOCKET = "/run/ld-fdpi/helper.sock"
|
|
GROUP = "ld-fdpi"
|
|
NFT_QUIC = "ld_fdpi_quic"
|
|
|
|
APP_NAMES = (
|
|
"chrome", "chromium", "chrome_crashpad", "discord", "firefox",
|
|
"brave", "opera", "vivaldi", "msedge", "telegram", "slack",
|
|
"signal", "element", "zoom", "steam", "spotify",
|
|
)
|
|
|
|
ACTIONS = {
|
|
"status",
|
|
"quic_on",
|
|
"quic_off",
|
|
"restore",
|
|
}
|
|
|
|
|
|
def peer_is_allowed(conn):
|
|
creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
|
|
_pid, uid, _gid = struct.unpack("3i", creds)
|
|
if uid == 0:
|
|
return True
|
|
try:
|
|
group = grp.getgrnam(GROUP)
|
|
except KeyError:
|
|
return False
|
|
return _uid_in_group(uid, group)
|
|
|
|
|
|
def _uid_in_group(uid, group):
|
|
try:
|
|
import pwd
|
|
user = pwd.getpwuid(uid)
|
|
except KeyError:
|
|
return False
|
|
return group.gr_gid == user.pw_gid or user.pw_name in group.gr_mem
|
|
|
|
|
|
def nft_available():
|
|
return os.path.exists("/usr/sbin/nft") or os.path.exists("/sbin/nft")
|
|
|
|
|
|
def nft(script):
|
|
proc = subprocess.run(
|
|
["nft", "-f", "-"],
|
|
input=script,
|
|
text=True,
|
|
capture_output=True,
|
|
check=False,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise RuntimeError((proc.stderr or proc.stdout).strip()[:500])
|
|
|
|
|
|
def nft_delete(table):
|
|
if nft_available():
|
|
subprocess.run(["nft", "delete", "table", "inet", table], check=False,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
|
|
def app_cgroup_ids():
|
|
"""Return cgroup v2 inode IDs for known desktop apps.
|
|
|
|
nftables `meta cgroup` matches the cgroup v2 inode, not the path string.
|
|
"""
|
|
ids = set()
|
|
root = "/sys/fs/cgroup"
|
|
for entry in os.scandir("/proc"):
|
|
if not entry.name.isdigit():
|
|
continue
|
|
pid = entry.name
|
|
try:
|
|
with open(f"/proc/{pid}/comm", encoding="utf-8", errors="replace") as fh:
|
|
comm = fh.read().strip().lower()
|
|
except OSError:
|
|
continue
|
|
if not any(name in comm for name in APP_NAMES):
|
|
continue
|
|
path = None
|
|
try:
|
|
with open(f"/proc/{pid}/cgroup", encoding="utf-8", errors="replace") as fh:
|
|
for line in fh:
|
|
if line.startswith("0::"):
|
|
path = line[3:].strip()
|
|
break
|
|
except OSError:
|
|
continue
|
|
if not path:
|
|
continue
|
|
full = os.path.join(root, path.lstrip("/"))
|
|
try:
|
|
ids.add(os.stat(full).st_ino)
|
|
except OSError:
|
|
continue
|
|
return sorted(ids)
|
|
|
|
|
|
def quic_on():
|
|
if not nft_available():
|
|
return {"ok": False, "error": "nft-not-installed"}
|
|
ids = app_cgroup_ids()
|
|
if not ids:
|
|
return {"ok": False, "error": "no-supported-apps-running"}
|
|
lines = [
|
|
f"table inet {NFT_QUIC} {{",
|
|
" chain output {",
|
|
" type filter hook output priority 0; policy accept;",
|
|
" oifname \"lo\" accept",
|
|
" meta nfproto ipv6 udp dport 443 drop",
|
|
]
|
|
for cgid in ids[:40]:
|
|
lines.append(f" meta cgroup {cgid} udp dport 443 drop")
|
|
lines.extend([
|
|
" }",
|
|
"}",
|
|
])
|
|
nft_delete(NFT_QUIC)
|
|
nft("\n".join(lines) + "\n")
|
|
return {"ok": True, "cgroups": len(ids), "table": NFT_QUIC}
|
|
|
|
|
|
def quic_off():
|
|
nft_delete(NFT_QUIC)
|
|
return {"ok": True}
|
|
|
|
|
|
def cleanup():
|
|
nft_delete(NFT_QUIC)
|
|
|
|
|
|
def handle(request):
|
|
action = str(request.get("action", ""))
|
|
if action not in ACTIONS:
|
|
return {"ok": False, "error": "action-not-allowed"}
|
|
if action == "status":
|
|
return {
|
|
"ok": True,
|
|
"nft": nft_available(),
|
|
"phase": 2,
|
|
}
|
|
if action == "quic_on":
|
|
return quic_on()
|
|
if action == "quic_off":
|
|
return quic_off()
|
|
if action == "restore":
|
|
cleanup()
|
|
return {"ok": True}
|
|
return {"ok": False, "error": "unsupported"}
|
|
|
|
|
|
def serve():
|
|
os.makedirs(os.path.dirname(SOCKET), exist_ok=True)
|
|
try:
|
|
os.unlink(SOCKET)
|
|
except FileNotFoundError:
|
|
pass
|
|
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
server.bind(SOCKET)
|
|
os.chmod(SOCKET, 0o660)
|
|
try:
|
|
gid = grp.getgrnam(GROUP).gr_gid
|
|
os.chown(SOCKET, 0, gid)
|
|
except KeyError:
|
|
pass
|
|
server.listen(8)
|
|
print(f"ld-fdpi-helper listening on {SOCKET}", file=sys.stderr, flush=True)
|
|
while True:
|
|
conn, _ = server.accept()
|
|
with conn:
|
|
try:
|
|
if not peer_is_allowed(conn):
|
|
conn.sendall(b'{"ok":false,"error":"permission-denied"}\n')
|
|
continue
|
|
conn.settimeout(5)
|
|
data = b""
|
|
while not data.endswith(b"\n") and len(data) < 4096:
|
|
chunk = conn.recv(4096)
|
|
if not chunk:
|
|
break
|
|
data += chunk
|
|
if not data:
|
|
continue
|
|
request = json.loads(data.decode("utf-8", "replace"))
|
|
response = handle(request)
|
|
except Exception as exc: # noqa: BLE001
|
|
response = {"ok": False, "error": f"bad-request: {exc}"}
|
|
conn.sendall((json.dumps(response) + "\n").encode())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
serve()
|