Files
Athena-Deck/network/reconnect.py
T

116 lines
4.5 KiB
Python

"""Refresh only the native Deck peer endpoint after stale handshakes.
Never creates interfaces, changes routes/listeners, enables a disabled tunnel,
reads other VPN configurations, or prints credentials. Run by a systemd timer.
"""
import argparse
import json
import os
from pathlib import Path
import socket
import subprocess
import time
from network.config import parse_config
INTERFACE = 'wgdeck0'
STALE_SECONDS = 135
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8',
'WG_DNS_RESOLUTION_RETRIES': '0'}
def safe_path(path):
path = Path(path)
for value in (path, path.resolve()):
if 'vpn.auth' in value.parts or 'vpn' in value.parts or str(value).startswith('/mnt/nvme-storage/appdata/OpenVPN-KIT'):
raise ValueError('Excluded path')
return path
def command(args):
result = subprocess.run(args, capture_output=True, text=True, timeout=10, env=ENV)
if result.returncode:
raise ValueError('Native WireGuard action unavailable')
return result.stdout.strip()
def native_status(control):
with socket.socket(socket.AF_UNIX) as sock:
sock.settimeout(5)
sock.connect(str(control))
sock.sendall(b'{"action":"status"}\n')
with sock.makefile('rb') as stream:
data = json.loads(stream.readline(32769))
if data.get('error'):
raise ValueError('Native network helper unavailable')
return data
def enabled(root):
path = safe_path(root / 'enabled.json')
return path.is_file() and json.loads(path.read_text()) is True
def peer_handshake(peer):
for line in command(['wg', 'show', INTERFACE, 'latest-handshakes']).splitlines():
fields = line.split()
if len(fields) == 2 and fields[0] == peer:
return int(fields[1])
return None
def refresh(root=Path('/var/lib/athena-deck-network'),
control=Path('/run/athena-deck-network/control.sock'), now=None):
root = safe_path(root)
if not enabled(root):
return dict(state='disabled', endpoint_refreshed=False)
status = native_status(control)
if status.get('backend') != 'native-systemd' or status.get('interface') != INTERFACE:
raise ValueError('Unexpected native backend')
if status.get('enabled') is not True or status.get('configured') is not True:
return dict(state='disabled', endpoint_refreshed=False)
path = safe_path(root / 'config.json')
saved = path.read_bytes()
config = parse_config(json.loads(saved), native=True)
peer = config['peer']['PublicKey']
latest = peer_handshake(peer)
if latest is None:
return dict(state='peer_changed_or_missing', endpoint_refreshed=False)
age = (time.time() if now is None else now) - latest if latest else None
if age is not None and 0 <= age <= STALE_SECONDS:
return dict(state='connected', handshake_age_seconds=int(age), endpoint_refreshed=False)
# Recheck persisted intent and peer identity immediately before the narrow update.
# `wg set ... endpoint` cannot create an interface, alter keys/routes or reset it.
if not enabled(root) or path.read_bytes() != saved or peer_handshake(peer) is None:
return dict(state='configuration_changed', endpoint_refreshed=False)
command(['wg', 'set', INTERFACE, 'peer', peer, 'endpoint', config['peer']['Endpoint']])
return dict(state='endpoint_refreshed_waiting_for_handshake', endpoint_refreshed=True,
handshake_age_seconds=int(age) if age is not None else None)
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--state', type=Path, default=Path('/var/lib/athena-deck-network'))
parser.add_argument('--control', type=Path, default=Path('/run/athena-deck-network/control.sock'))
parser.add_argument('--status-file', type=Path, default=Path('/run/athena-deck-network/reconnect-status.json'))
options = parser.parse_args(argv)
code = 0
try:
value = refresh(options.state, options.control)
except Exception as error:
# Do not log exception strings, command arguments, peer identifiers or config values.
value = dict(state='retry_next_interval', endpoint_refreshed=False, error_type=type(error).__name__)
code = 1
value['checked_at'] = time.time()
target = safe_path(options.status_file)
temporary = target.with_suffix('.tmp')
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream)
temporary.replace(target)
print(json.dumps(value))
return code
if __name__ == '__main__':
raise SystemExit(main())