VPN: read only the VPN files the Controller writes (#1037)

* VPN: read only the VPN files the Controller writes

controller.yaml's vpn.config_file and vpn.auth_file were joined to the
config directory as-is. The tunnel runs as root, so an absolute or ../
path would have it read (and send to the VPN server) any file, and the
Controller API would return any file's text as the VPN config.

Both now accept only vpn/wireguard.conf, vpn/openvpn.ovpn, and
vpn/openvpn-auth.txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* VPN: refuse a VPN file which links outside the vpn directory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* VPN: read each VPN file once, never through a symlink

The check resolved the path, then the file was opened again later: by
root OpenVPN for the login (--auth-nocache re-reads it). The wrolpi user,
who owns the library, could swap the file for a symlink in between.

read_vpn_file() opens with O_NOFOLLOW and reads once. OpenVPN gets a
0600 copy of the login in the run directory, removed when the tunnel
goes down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-30 15:05:37 -07:00 • committed by GitHub
parent 04ddc7c63c
commit b1334c834b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 156 additions and 16 deletions

View file

@ -21,10 +21,10 @@ 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}
WIREGUARD_CONFIG = tunnel.WIREGUARD_CONFIG
OPENVPN_CONFIG = tunnel.OPENVPN_CONFIG
OPENVPN_AUTH = tunnel.OPENVPN_AUTH
CONFIG_FILES = tunnel.CONFIG_FILES
MAX_CONFIG_BYTES = 256 * 1024
# The tunnel writes its status every 15 seconds; older than this, it is not running.
@ -59,7 +59,10 @@ def read_vpn_config() -> tuple[str, str] | None:
if not config_file:
return None
try:
text = (get_config_directory() / config_file).read_text()
text = tunnel.read_vpn_file(get_config_directory(), config_file, CONFIG_FILES.values())
except tunnel.VPNConfigError as e:
logger.warning(f'Ignoring the VPN config in controller.yaml: {e}')
return None
except FileNotFoundError:
return None
return tunnel.config_kind(config_file), text

View file

@ -166,6 +166,16 @@ class TestSettings:
assert not (drive / vpn.OPENVPN_AUTH).exists()
@pytest.mark.parametrize('config_file', ['../outside.conf', 'vpn/../../outside.conf', 'vpn/other.ovpn'])
def test_reads_only_the_files_wrolpi_writes(self, drive, config_file):
"""The API returns the config's text, so a hand-edited controller.yaml must not point it at other files."""
(drive.parent / 'outside.conf').write_text(WIREGUARD)
(drive / 'vpn').mkdir(parents=True, exist_ok=True)
(drive / 'vpn/other.ovpn').write_text(OPENVPN)
vpn._save_settings(config_file=config_file)
assert vpn.read_vpn_config() is None
class TestEndpoints:
def test_need_resolving(self, drive, resolver):

View file

@ -318,7 +318,7 @@ class TestPlan:
(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.auth_text == 'user\npass\n'
assert plan.endpoints == [Endpoint('198.51.100.7', 1194, 'udp')]
def test_fixed_port_must_be_a_port(self, media):
@ -329,6 +329,62 @@ class TestPlan:
with pytest.raises(VPNConfigError, match='not a port'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
@pytest.mark.parametrize('config_file', [
'/etc/wireguard/wg0.conf',
'../../outside.conf',
'vpn/../../outside.conf',
'vpn/other.conf',
])
def test_config_must_be_one_wrolpi_writes(self, media, config_file):
"""The tunnel runs as root, so controller.yaml may only name the files the Controller writes."""
(media / 'outside.conf').write_text(WIREGUARD)
(media / 'config/vpn/other.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file=config_file)
with pytest.raises(VPNConfigError, match='not a VPN file'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
def test_config_symlink_must_stay_in_vpn_directory(self, media):
(media / 'outside.conf').write_text(WIREGUARD)
(media / 'config/vpn/wireguard.conf').symlink_to(media / 'outside.conf')
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
with pytest.raises(VPNConfigError, match='not a VPN file'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
@pytest.mark.parametrize('name', ['wireguard.conf', 'openvpn-auth.txt'])
def test_vpn_files_are_never_symlinks(self, media, name):
"""Even one pointing inside vpn/: it could be re-pointed after it was checked. The Controller writes regular
files."""
(media / 'config/vpn/real').write_text(WIREGUARD if name == 'wireguard.conf' else 'user\npass\n')
(media / 'config/vpn' / name).symlink_to(media / 'config/vpn/real')
if name == 'wireguard.conf':
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
else:
(media / 'config/vpn/openvpn.ovpn').write_text('remote 198.51.100.7 1194\nauth-user-pass\n')
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn', auth_file='vpn/openvpn-auth.txt')
with pytest.raises(VPNConfigError, match='symlink'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
def test_vpn_directory_may_be_a_symlink(self, media, tmp_path):
"""The config directory may be reached through a mount point or a symlink; only escaping `vpn/` is refused."""
real = tmp_path / 'real-config'
real.mkdir()
(media / 'config').rename(real / 'config')
(media / 'config').symlink_to(real / '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')
assert tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR).kind == 'wireguard'
@pytest.mark.parametrize('auth_file', ['/etc/shadow', '../secret.txt', 'vpn/wireguard.conf'])
def test_openvpn_login_must_be_the_one_wrolpi_writes(self, media, auth_file):
text = 'remote 198.51.100.7 1194\nauth-user-pass\n'
(media / 'config/vpn/openvpn.ovpn').write_text(text)
(media / 'config/secret.txt').write_text('root\nsecret\n')
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn', auth_file=auth_file)
with pytest.raises(VPNConfigError, match='not a VPN file'):
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'):
@ -511,6 +567,42 @@ class TestTunnel:
assert status['state'] == 'connected'
assert status['addresses'] == ['10.8.0.6/24']
def test_openvpn_reads_a_private_copy_of_its_login(self, media, tmp_path, fake_system, monkeypatch):
"""Root OpenVPN never opens the login in the library (the wrolpi user could swap it for a symlink after it was
checked, and --auth-nocache re-reads it): it gets a copy, only root can read, in the run directory."""
(media / 'config/vpn/openvpn.ovpn').write_text('client\nremote 198.51.100.7 1194\nauth-user-pass\n')
(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')
t = self.make_tunnel(media, tmp_path)
class FakeOpenVPN:
def __init__(self, cmd):
self.cmd = cmd
self.connected = __import__('threading').Event()
fake_system.links.add('vpn0')
self.dns = []
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
login = Path(cmd[cmd.index('--auth-user-pass') + 1])
assert login.parent == tunnel.RUN_DIR
assert login.read_text() == 'user\npass\n'
assert stat.S_IMODE(login.stat().st_mode) == 0o600
t.down()
assert not login.exists()
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)."""

View file

@ -19,6 +19,7 @@ Controller imports it to share the parsing and the defaults.
"""
import argparse
import dataclasses
import errno
import hashlib
import ipaddress
import json
@ -56,6 +57,13 @@ VPN_DEFAULTS = {
# Fetched through the tunnel to show the address peers see. None disables the check.
'public_ip_url': 'https://api.ipify.org',
}
# The only VPN files the Controller writes, relative to the config directory. The tunnel runs as root, so the
# `config_file` and `auth_file` settings may name no other file.
WIREGUARD_CONFIG = 'vpn/wireguard.conf'
OPENVPN_CONFIG = 'vpn/openvpn.ovpn'
OPENVPN_AUTH = 'vpn/openvpn-auth.txt'
CONFIG_FILES = {'wireguard': WIREGUARD_CONFIG, 'openvpn': OPENVPN_CONFIG}
PORT_FORWARDING_MODES = ('none', 'fixed', 'natpmp')
TUNNEL_INTERFACE = 'vpn0'
@ -73,6 +81,7 @@ STATUS_FILE = 'status.json'
WROL_MODE_FLAG = '.wrol_mode'
ENDPOINTS_FILE = 'endpoints.json'
OPENVPN_CONFIG_FILE = 'openvpn.ovpn'
OPENVPN_AUTH_FILE = 'openvpn-auth.txt'
LOOP_SECONDS = 15
# WireGuard re-handshakes every two minutes while traffic flows.
@ -808,7 +817,8 @@ class Plan:
"""What the tunnel should be, from the settings and the config."""
kind: str
config_path: pathlib.Path
auth_path: pathlib.Path | None
# OpenVPN's username and password lines, or None.
auth_text: str | None
endpoints: list[Endpoint]
hosts: dict[str, list[str]]
settings: dict
@ -818,6 +828,24 @@ class Plan:
openvpn_dns: list[str] = dataclasses.field(default_factory=list)
def read_vpn_file(config_directory: pathlib.Path, name: str, allowed) -> str:
"""The text of a VPN file named in controller.yaml, which must be one of the `allowed` files WROLPi writes.
Read once, and never through a symlink: the library belongs to the wrolpi user, who could re-point one after it
was checked. (The config and vpn directories may be symlinks.) Raises FileNotFoundError when it is missing."""
if name not in allowed:
raise VPNConfigError(f'{name} is not a VPN file WROLPi writes')
path = config_directory / name
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
except OSError as e:
if e.errno == errno.ELOOP:
raise VPNConfigError(f'{name} is a symlink, not a VPN file WROLPi writes')
raise
with os.fdopen(fd) as f:
return f.read()
def make_plan(settings: dict, config_directory: pathlib.Path, run_dir: pathlib.Path) -> Plan | None:
"""None when the VPN is disabled."""
if not settings.get('enabled'):
@ -829,11 +857,11 @@ def make_plan(settings: dict, config_directory: pathlib.Path, run_dir: pathlib.P
config_path = config_directory / settings['config_file']
kind = config_kind(config_path.name)
try:
text = config_path.read_text()
text = read_vpn_file(config_directory, settings['config_file'], CONFIG_FILES.values())
except FileNotFoundError:
raise VPNConfigError(f'The VPN config {settings["config_file"]} is missing')
hosts = read_endpoint_hosts(run_dir, text)
auth_path, auth_text = None, ''
auth_text = None
if kind == 'wireguard':
wireguard = parse_wireguard(text)
endpoints = endpoints_of(wireguard.remotes(), hosts)
@ -843,12 +871,14 @@ def make_plan(settings: dict, config_directory: pathlib.Path, run_dir: pathlib.P
endpoints = endpoints_of(openvpn.remotes, hosts)
plan_kwargs = {'openvpn_text': sanitize_openvpn(openvpn, hosts), 'openvpn_dns': openvpn.dns}
if openvpn.wants_auth:
if not settings.get('auth_file') or not (config_directory / settings['auth_file']).is_file():
if not settings.get('auth_file'):
raise VPNConfigError('This OpenVPN config needs a username and password')
auth_path = config_directory / settings['auth_file']
auth_text = auth_path.read_text()
fingerprint = config_sha256(json.dumps([settings, text, auth_text, hosts], sort_keys=True, default=str))
return Plan(kind, config_path, auth_path, endpoints, hosts, settings, fingerprint, **plan_kwargs)
try:
auth_text = read_vpn_file(config_directory, settings['auth_file'], (OPENVPN_AUTH,))
except FileNotFoundError:
raise VPNConfigError('This OpenVPN config needs a username and password')
fingerprint = config_sha256(json.dumps([settings, text, auth_text or '', hosts], sort_keys=True, default=str))
return Plan(kind, config_path, auth_text, endpoints, hosts, settings, fingerprint, **plan_kwargs)
class Tunnel:
@ -986,8 +1016,11 @@ class Tunnel:
cmd = ['openvpn', '--config', str(config), '--script-security', '1', '--dev', TUNNEL_INTERFACE,
'--dev-type', 'tun', '--disable-dco', '--route-noexec', '--persist-tun', '--persist-key',
'--auth-nocache', '--verb', '3']
if plan.auth_path:
cmd.extend(['--auth-user-pass', str(plan.auth_path)])
if plan.auth_text is not None:
# A copy only root can read: OpenVPN re-reads it (--auth-nocache), and never opens the library's.
auth = self.run_dir / OPENVPN_AUTH_FILE
write_private(auth, plan.auth_text)
cmd.extend(['--auth-user-pass', str(auth)])
self.openvpn = OpenVPNProcess(cmd)
deadline = time.monotonic() + OPENVPN_CONNECT_SECONDS
while not self.openvpn.connected.wait(1):
@ -1002,6 +1035,8 @@ class Tunnel:
if self.openvpn:
self.openvpn.stop()
self.openvpn = None
# The login's copy is kept only while OpenVPN may need it.
(self.run_dir / OPENVPN_AUTH_FILE).unlink(missing_ok=True)
if self.plan or self.routes:
run_quietly('ip', 'link', 'del', TUNNEL_INTERFACE)
for family, destination in self.routes: