753 lines
37 KiB
Python
753 lines
37 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import zlib
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import amneziawg_config
|
|
from amneziawg_config import (
|
|
ConfigError,
|
|
decode_vpn_link,
|
|
extract_vpn_config,
|
|
prepare,
|
|
probe_address,
|
|
rekey_after_time,
|
|
render_settings,
|
|
transport_implementation,
|
|
validate_config,
|
|
write_private,
|
|
)
|
|
|
|
|
|
BASE_CONFIG = """[Interface]
|
|
PrivateKey = private
|
|
Address = 10.8.0.2/32
|
|
DNS = $PRIMARY_DNS,$SECONDARY_DNS
|
|
Jc = 5
|
|
S3 = 12
|
|
S4 = 12
|
|
HeaderProtectionKey = header
|
|
ContentPaddingAddition = 8-16
|
|
|
|
[Peer]
|
|
PublicKey = public
|
|
AllowedIPs = 0.0.0.0/0
|
|
Endpoint = vpn.example.com:51820
|
|
"""
|
|
|
|
|
|
def vpn_data(*entries):
|
|
return {
|
|
"defaultContainer": entries[0][0],
|
|
"dns1": "1.1.1.1",
|
|
"dns2": "8.8.8.8",
|
|
"containers": [
|
|
{
|
|
"container": container,
|
|
key: {
|
|
"last_config": json.dumps(
|
|
{"config": config, "mtu": "1280", "port": 41111}
|
|
)
|
|
},
|
|
}
|
|
for container, key, config in entries
|
|
],
|
|
}
|
|
|
|
|
|
def encode_vpn(data, compressed=True):
|
|
raw = json.dumps(data).encode()
|
|
if compressed:
|
|
raw = len(raw).to_bytes(4, "big") + zlib.compress(raw)
|
|
encoded = base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
|
return f"vpn://{encoded}"
|
|
|
|
|
|
class AmneziaWgConfigTests(unittest.TestCase):
|
|
def secret_settings(self, path, **public):
|
|
return {
|
|
"addresses": ["10.8.0.2/32"],
|
|
"privateKey": "private",
|
|
"obfuscation": public,
|
|
"obfuscationFile": str(path),
|
|
"peers": [{"publicKey": "public", "allowedIPs": ["0.0.0.0/0"]}],
|
|
}
|
|
|
|
def test_partial_obfuscation_all_fields(self):
|
|
secret = {
|
|
"jc": 0, "jmin": 10, "jmax": 20,
|
|
"s1": 60, "s2": 90, "s3": 12, "s4": 16,
|
|
"h1": "100-200", "h2": 300, "h3": "400", "h4": "(off)",
|
|
"i1": "<b 0x1234>", "i2": "second", "i3": "third",
|
|
"i4": "fourth", "i5": "fifth", "headerProtectionKey": "header-secret",
|
|
"contentPaddingAddition": "8-16", "rekeyAfterTime": 120,
|
|
"rekeyTimeout": "5", "rejectAfterTime": "(off)",
|
|
"keepaliveTimeout": "10-20", "maxHandshakeAttempts": 10,
|
|
"randomTrailers": True, "disableCookies": False,
|
|
}
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "secret.json"
|
|
path.write_text(json.dumps(secret))
|
|
settings = self.secret_settings(path)
|
|
config = prepare({"kind": "settings", "settings": settings})
|
|
for key, value in secret.items():
|
|
rendered = ("on" if value else "off") if type(value) is bool else str(value)
|
|
self.assertIn(f"{key[0].upper() + key[1:]} = {rendered}\n", config)
|
|
self.assertIn("MTU = 1280", config)
|
|
self.assertEqual(transport_implementation(config), "userspace")
|
|
settings["mtu"] = 1312
|
|
self.assertIn("MTU = 1312", prepare({"kind": "settings", "settings": settings}))
|
|
self.assertEqual(settings["obfuscation"], {})
|
|
|
|
def test_partial_obfuscation_merge_and_rotation(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "secret.json"
|
|
settings = self.secret_settings(path, s1=60, s2=90, i1=None)
|
|
for secret in ({}, {"i1": None, "s1": None}, {"i1": "first"}, {"i1": "rotated"}):
|
|
with self.subTest(secret=secret):
|
|
path.write_text(json.dumps(secret))
|
|
config = render_settings(settings)
|
|
self.assertIn("S1 = 60", config)
|
|
self.assertIn("S2 = 90", config)
|
|
if secret.get("i1"):
|
|
self.assertIn(f"I1 = {secret['i1']}\n", config)
|
|
else:
|
|
self.assertNotIn("I1 =", config)
|
|
self.assertIsNone(settings["obfuscation"]["i1"])
|
|
|
|
def test_partial_obfuscation_conflicts(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "secret.json"
|
|
for secret, public in [
|
|
({"i1": "same"}, {"i1": "same"}),
|
|
({"jc": 0}, {"jc": 0}),
|
|
({"randomTrailers": False}, {"randomTrailers": False}),
|
|
({"headerProtectionKey": "secret"}, {"headerProtectionKey": "inline"}),
|
|
({"headerProtectionKey": "secret"}, {"headerProtectionKeyFile": "/missing"}),
|
|
]:
|
|
with self.subTest(public=public):
|
|
path.write_text(json.dumps(secret))
|
|
with self.assertRaisesRegex(ConfigError, "multiple sources"):
|
|
render_settings(self.secret_settings(path, **public))
|
|
|
|
def test_partial_obfuscation_rejects_invalid_values(self):
|
|
invalid = {
|
|
"jc": [-1, True, "5", 1.5, [], {}],
|
|
"h1": [-1, False, "1 - 2", "off", "1-2-3", "1\n", 1.5],
|
|
"randomTrailers": [0, 1, "on", "false", [], {}],
|
|
"i1": ["", " ", 42, True, [], {}, "secret\nPostUp = command",
|
|
"secret\rPostUp = command", "secret\u2028PostUp = command",
|
|
"secret\n", "secret\x00"],
|
|
"headerProtectionKey": ["", 42, "secret\nPostUp = command"],
|
|
}
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "secret.json"
|
|
for key, values in invalid.items():
|
|
for value in values:
|
|
with self.subTest(key=key, value=value):
|
|
path.write_text(json.dumps({key: value}))
|
|
with self.assertRaisesRegex(ConfigError, "invalid value"):
|
|
render_settings(self.secret_settings(path))
|
|
|
|
def test_partial_obfuscation_safe_cli_failures_preserve_output(self):
|
|
inputs = [
|
|
b'{"i1": "SECRET",}', b'{"i1": "SECRET", "i1": null}',
|
|
b'{"SECRET": null}', b'{"headerProtectionKeyFile": "SECRET"}',
|
|
b'{"privateKey": "SECRET"}', b'{"peers": []}', b'{"mtu": 1280}',
|
|
b'{"i1": "SECRET\\nPostUp = command"}', b'{"jc": NaN}',
|
|
b'{"i1": "SECRET\\ud800"}',
|
|
b'{"jc": Infinity}', b'{"i1": "SECRET\xff"}',
|
|
b'[]', b'null', b'"SECRET"', b'',
|
|
b'[' * 2000 + b'"SECRET"' + b']' * 2000,
|
|
]
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
path = directory / "secret.json"
|
|
output = directory / "runtime" / "awg.conf"
|
|
manifest = directory / "manifest.json"
|
|
manifest.write_text(json.dumps({"kind": "settings", "settings": self.secret_settings(path)}))
|
|
write_private(str(output), "previous config")
|
|
for data in inputs + [None]:
|
|
with self.subTest(data=data[:60] if data else data):
|
|
if data is None:
|
|
path.unlink()
|
|
else:
|
|
path.write_bytes(data)
|
|
result = subprocess.run(
|
|
[sys.executable, str(Path(__file__).with_name("amneziawg_config.py")),
|
|
"--manifest", str(manifest), "--output", str(output)],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertNotEqual(result.returncode, 0)
|
|
self.assertNotIn("SECRET", result.stderr + result.stdout)
|
|
self.assertNotIn("Traceback", result.stderr)
|
|
self.assertEqual(output.read_text(), "previous config")
|
|
self.assertEqual(output.stat().st_mode & 0o777, 0o600)
|
|
self.assertEqual(output.parent.stat().st_mode & 0o777, 0o700)
|
|
self.assertEqual(list(output.parent.iterdir()), [output])
|
|
|
|
def test_partial_obfuscation_unreadable_and_oversized(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "secret.json"
|
|
path.write_text('{"i1": "SECRET"}')
|
|
with patch("amneziawg_config.MAX_INPUT_BYTES", 4):
|
|
with self.assertRaisesRegex(ConfigError, "exceeds"):
|
|
render_settings(self.secret_settings(path))
|
|
with patch("amneziawg_config._read_limited", side_effect=PermissionError("SECRET")):
|
|
with self.assertRaisesRegex(ConfigError, "^cannot read or decode obfuscationFile$"):
|
|
render_settings(self.secret_settings(path))
|
|
|
|
def test_qcompress_vpn_link(self):
|
|
data = decode_vpn_link(encode_vpn(vpn_data(("amnezia-awg", "awg", BASE_CONFIG))))
|
|
config = extract_vpn_config(data)
|
|
self.assertIn("DNS = 1.1.1.1,8.8.8.8", config)
|
|
self.assertIn("MTU = 1280", config)
|
|
self.assertIn("ListenPort = 41111", config)
|
|
self.assertIn("HeaderProtectionKey = header", config)
|
|
|
|
def test_uncompressed_vpn_link(self):
|
|
data = decode_vpn_link(
|
|
encode_vpn(vpn_data(("amnezia-awg2", "amnezia-awg", BASE_CONFIG)), False)
|
|
)
|
|
self.assertIn("[Peer]", extract_vpn_config(data))
|
|
|
|
def test_uncompressed_direct_conf_vpn_link(self):
|
|
direct = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1,8.8.8.8")
|
|
link = "vpn://" + base64.urlsafe_b64encode(direct.encode()).decode()
|
|
data = decode_vpn_link(link)
|
|
config = extract_vpn_config(data)
|
|
self.assertIn("[Interface]", config)
|
|
self.assertIn("[Peer]", config)
|
|
self.assertIn("MTU = 1280", config)
|
|
|
|
def test_awg3_vpn_mtu_fallback_preserves_explicit_values(self):
|
|
data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG))
|
|
last = json.loads(data["containers"][0]["awg"]["last_config"])
|
|
del last["mtu"]
|
|
data["containers"][0]["awg"]["last_config"] = last
|
|
self.assertIn("MTU = 1280", extract_vpn_config(data))
|
|
|
|
explicit = BASE_CONFIG.replace("Address =", "MTU = 1312\nAddress =")
|
|
data = vpn_data(("amnezia-awg3", "awg", explicit))
|
|
last = json.loads(data["containers"][0]["awg"]["last_config"])
|
|
del last["mtu"]
|
|
data["containers"][0]["awg"]["last_config"] = last
|
|
config = extract_vpn_config(data)
|
|
self.assertIn("MTU = 1312", config)
|
|
self.assertNotIn("MTU = 1280", config)
|
|
|
|
def test_legacy_vpn_without_mtu_keeps_awg_quick_default(self):
|
|
legacy = BASE_CONFIG.replace("HeaderProtectionKey = header\n", "").replace(
|
|
"ContentPaddingAddition = 8-16\n", ""
|
|
)
|
|
data = vpn_data(("amnezia-awg", "awg", legacy))
|
|
last = json.loads(data["containers"][0]["awg"]["last_config"])
|
|
del last["mtu"]
|
|
data["containers"][0]["awg"]["last_config"] = last
|
|
self.assertNotIn("MTU =", extract_vpn_config(data))
|
|
|
|
def test_legacy_direct_last_config_shape(self):
|
|
data = vpn_data(("amnezia-awg", "awg", BASE_CONFIG))
|
|
last_config = data["containers"][0]["awg"]["last_config"]
|
|
data["containers"] = [
|
|
{"container": "amnezia-awg", "last_config": last_config}
|
|
]
|
|
self.assertIn("MTU = 1280", extract_vpn_config(data))
|
|
|
|
def test_awg3_fields_are_restored_from_last_config(self):
|
|
data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG))
|
|
last = json.loads(data["containers"][0]["awg"]["last_config"])
|
|
last.update(
|
|
{
|
|
"HeaderProtectionKey": "json-header",
|
|
"content_padding_addition": "20-40",
|
|
"RekeyAfterTime": "100-120",
|
|
"MaxHandshakeAttempts": "15-20",
|
|
"S4": 48,
|
|
}
|
|
)
|
|
data["containers"][0]["awg"]["last_config"] = last
|
|
config = extract_vpn_config(data)
|
|
self.assertIn("HeaderProtectionKey = json-header", config)
|
|
self.assertIn("ContentPaddingAddition = 20-40", config)
|
|
self.assertIn("RekeyAfterTime = 100-120", config)
|
|
self.assertIn("MaxHandshakeAttempts = 15-20", config)
|
|
self.assertIn("S4 = 48", config)
|
|
|
|
def test_awg3_boolean_fields_are_restored_from_last_config(self):
|
|
data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG))
|
|
last = json.loads(data["containers"][0]["awg"]["last_config"])
|
|
last.update({"RandomTrailers": "on", "DisableCookies": True})
|
|
data["containers"][0]["awg"]["last_config"] = last
|
|
config = extract_vpn_config(data)
|
|
self.assertIn("RandomTrailers = on", config)
|
|
self.assertIn("DisableCookies = on", config)
|
|
|
|
def test_explicit_container_resolves_ambiguity(self):
|
|
data = vpn_data(
|
|
("amnezia-awg", "awg", BASE_CONFIG),
|
|
("amnezia-awg2", "awg", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")),
|
|
)
|
|
data["defaultContainer"] = "not-awg"
|
|
with self.assertRaisesRegex(ConfigError, "multiple AmneziaWG"):
|
|
extract_vpn_config(data)
|
|
selected = extract_vpn_config(data, "amnezia-awg2")
|
|
self.assertIn("10.9.0.2", selected)
|
|
|
|
def test_default_protocol_key_resolves_ambiguity(self):
|
|
data = vpn_data(
|
|
("client-a", "awg", BASE_CONFIG),
|
|
("client-b", "amnezia-awg2", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")),
|
|
)
|
|
data["defaultContainer"] = "awg"
|
|
self.assertIn("10.8.0.2", extract_vpn_config(data))
|
|
|
|
def test_api_backed_short_key_is_rejected(self):
|
|
with self.assertRaisesRegex(ConfigError, "API-backed"):
|
|
decode_vpn_link("vpn://short-key")
|
|
|
|
def test_qcompress_length_is_checked(self):
|
|
raw = json.dumps(vpn_data(("amnezia-awg", "awg", BASE_CONFIG))).encode()
|
|
payload = (len(raw) + 1).to_bytes(4, "big") + zlib.compress(raw)
|
|
link = "vpn://" + base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
|
with self.assertRaisesRegex(ConfigError, "length header"):
|
|
decode_vpn_link(link)
|
|
|
|
def test_decompression_limit_is_enforced(self):
|
|
raw = b"{" + b" " * (8 * 1024 * 1024) + b"}"
|
|
payload = len(raw).to_bytes(4, "big") + zlib.compress(raw)
|
|
link = "vpn://" + base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
|
with self.assertRaisesRegex(ConfigError, "exceeds"):
|
|
decode_vpn_link(link)
|
|
|
|
def test_missing_and_malformed_candidates_fail_cleanly(self):
|
|
with self.assertRaisesRegex(ConfigError, "no containers"):
|
|
extract_vpn_config({})
|
|
with self.assertRaisesRegex(ConfigError, "no AmneziaWG"):
|
|
extract_vpn_config({"containers": [{"container": "xray"}]})
|
|
unresolved = vpn_data(("amnezia-awg", "awg", BASE_CONFIG))
|
|
del unresolved["dns2"]
|
|
with self.assertRaisesRegex(ConfigError, "unresolved DNS"):
|
|
extract_vpn_config(unresolved)
|
|
|
|
def test_hooks_rejected_by_default_and_allowed_explicitly(self):
|
|
hooked = BASE_CONFIG.replace("Address =", "PostUp = touch /root/pwned\nAddress =")
|
|
with self.assertRaisesRegex(ConfigError, "privileged"):
|
|
validate_config(hooked)
|
|
validate_config(hooked, allow_hooks=True)
|
|
|
|
def test_hooks_hidden_from_python_line_splitting_rejected(self):
|
|
# Each is one line to awg-quick, whose key comes out as PostUp; splitlines()
|
|
# would cut it before the "=", or a later rewrite would turn it into two lines.
|
|
for hidden in (
|
|
"PostUp \f= touch /root/pwned",
|
|
"PostUp \v= touch /root/pwned",
|
|
"PostUp \x1c= touch /root/pwned",
|
|
"PostUp \u2028= touch /root/pwned",
|
|
"PostUp \r= touch /root/pwned",
|
|
"Post\0Up = touch /root/pwned",
|
|
"MTU = 1280\fPostUp = touch /root/pwned",
|
|
):
|
|
with self.subTest(hidden=hidden), self.assertRaises(ConfigError):
|
|
validate_config(BASE_CONFIG.replace("Address =", f"{hidden}\nAddress ="))
|
|
# A line without "=" is still a PostUp to awg-quick.
|
|
with self.assertRaisesRegex(ConfigError, "privileged"):
|
|
validate_config(BASE_CONFIG.replace("Address =", "PostUp\nAddress ="))
|
|
validate_config(BASE_CONFIG.replace("\n", "\r\n"))
|
|
|
|
def test_shared_directory_refuses_symlinks_and_fifos(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
secret = directory / "secret.conf"
|
|
secret.write_text(BASE_CONFIG)
|
|
spool = directory / "spool"
|
|
spool.mkdir()
|
|
(spool / "link.conf").symlink_to(secret)
|
|
os.mkfifo(spool / "fifo.conf")
|
|
(spool / "plain.conf").write_text(BASE_CONFIG)
|
|
# Private: a declared secret may well be a symlink (sops, agenix).
|
|
spool.chmod(0o700)
|
|
self.assertEqual(amneziawg_config._read_limited(str(spool / "link.conf")), BASE_CONFIG)
|
|
# Group-writable, as the runtime spool is.
|
|
spool.chmod(0o770)
|
|
with self.assertRaises(OSError):
|
|
amneziawg_config._read_limited(str(spool / "link.conf"))
|
|
with self.assertRaisesRegex(ConfigError, "not a regular file"):
|
|
amneziawg_config._read_limited(str(spool / "fifo.conf"))
|
|
self.assertEqual(amneziawg_config._read_limited(str(spool / "plain.conf")), BASE_CONFIG)
|
|
|
|
def test_global_render_from_the_spool_drops_a_privileged_listen_port(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
spool = directory / "spool"
|
|
spool.mkdir()
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
|
|
"Address =", "ListenPort = 53\nAddress ="
|
|
)
|
|
(spool / "g.conf").write_text(config)
|
|
out = directory / "out.conf"
|
|
for mode, kept in ((0o700, True), (0o770, False)):
|
|
spool.chmod(mode)
|
|
argv = ["amneziawg-config", "--config", str(spool / "g.conf"), "--output", str(out), "--fwmark", "51820"]
|
|
with self.subTest(mode=oct(mode)), patch.object(sys, "argv", argv):
|
|
self.assertEqual(amneziawg_config.main(), 0)
|
|
self.assertEqual("ListenPort = 53" in out.read_text(), kept)
|
|
|
|
def test_declarative_awg3_and_secret_files(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
private_key = directory / "private"
|
|
psk = directory / "psk"
|
|
header = directory / "header"
|
|
private_key.write_text("private-file\n")
|
|
psk.write_text("psk-file\n")
|
|
header.write_text("header-file\n")
|
|
config = render_settings(
|
|
{
|
|
"addresses": ["10.8.0.2/32"],
|
|
"dns": ["1.1.1.1"],
|
|
"privateKeyFile": str(private_key),
|
|
"obfuscation": {
|
|
"s1": 12,
|
|
"s2": 12,
|
|
"s3": 12,
|
|
"s4": 12,
|
|
"h1": "100-200",
|
|
"i1": "<b 0x0102><r 4>",
|
|
"headerProtectionKeyFile": str(header),
|
|
"rekeyAfterTime": "120-180",
|
|
"maxHandshakeAttempts": 10,
|
|
"randomTrailers": True,
|
|
"disableCookies": True,
|
|
},
|
|
"peers": [
|
|
{
|
|
"publicKey": "public",
|
|
"presharedKeyFile": str(psk),
|
|
"allowedIPs": ["0.0.0.0/0", "::/0"],
|
|
"endpoint": "vpn.example.com:51820",
|
|
"persistentKeepalive": "20-30",
|
|
"advancedSecurity": True,
|
|
}
|
|
],
|
|
}
|
|
)
|
|
self.assertIn("PrivateKey = private-file", config)
|
|
self.assertIn("HeaderProtectionKey = header-file", config)
|
|
self.assertIn("RekeyAfterTime = 120-180", config)
|
|
self.assertIn("RandomTrailers = on", config)
|
|
self.assertIn("DisableCookies = on", config)
|
|
self.assertIn("AdvancedSecurity = on", config)
|
|
|
|
prepared = prepare({"kind": "settings", "settings": {
|
|
"addresses": ["10.8.0.2/32"],
|
|
"privateKeyFile": str(private_key),
|
|
"obfuscation": {"headerProtectionKeyFile": str(header)},
|
|
"peers": [{"publicKey": "public", "allowedIPs": ["0.0.0.0/0"]}],
|
|
}})
|
|
self.assertIn("MTU = 1280", prepared)
|
|
|
|
def test_prepare_config_file_and_private_output(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
directory = Path(directory)
|
|
source = directory / "source.conf"
|
|
output = directory / "runtime" / "awg.conf"
|
|
source.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1"))
|
|
config = prepare({"kind": "configFile", "path": str(source)})
|
|
self.assertIn("MTU = 1280", config)
|
|
write_private(str(output), config)
|
|
self.assertEqual(output.stat().st_mode & 0o777, 0o600)
|
|
|
|
def test_probe_address_prefers_public_address_covered_by_default_route(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
self.assertEqual(probe_address(config), "1.1.1.1")
|
|
|
|
def test_probe_address_uses_host_inside_narrow_route(self):
|
|
config = BASE_CONFIG.replace(
|
|
"AllowedIPs = 0.0.0.0/0", "AllowedIPs = 10.23.42.0/24"
|
|
)
|
|
self.assertEqual(probe_address(config), "10.23.42.1")
|
|
|
|
def test_rekey_after_time_takes_the_upper_bound(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
self.assertEqual(rekey_after_time(config.replace("[Peer]", "RekeyAfterTime = 100-300\n[Peer]")), 300)
|
|
self.assertEqual(rekey_after_time(config.replace("[Peer]", "RekeyAfterTime = (off)\n[Peer]")), 0)
|
|
# Only [Interface] counts, and WireGuard's own 120 is the default.
|
|
self.assertEqual(rekey_after_time(config + "RekeyAfterTime = 999\n"), 120)
|
|
|
|
def test_inspect_prints_what_the_start_script_reads(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
path = Path(directory) / "awg.conf"
|
|
path.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1"))
|
|
result = subprocess.run(
|
|
[sys.executable, amneziawg_config.__file__, "--inspect", str(path)],
|
|
capture_output=True,
|
|
text=True,
|
|
check=True,
|
|
)
|
|
self.assertEqual(result.stdout, "auto 1.1.1.1 120\n")
|
|
|
|
def test_random_trailers_with_ranged_handshake_headers_forces_userspace(self):
|
|
config = BASE_CONFIG.replace(
|
|
"ContentPaddingAddition = 8-16",
|
|
"ContentPaddingAddition = 8-16\nH1 = 213818264-462596257\nRandomTrailers = on",
|
|
)
|
|
self.assertEqual(transport_implementation(config), "userspace")
|
|
self.assertEqual(
|
|
transport_implementation(config.replace("RandomTrailers = on", "RandomTrailers = off")),
|
|
"auto",
|
|
)
|
|
|
|
def test_outbound_render_keeps_host_routes_and_resolver(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
|
|
"Address = 10.8.0.2/32", "Address = 10.8.0.2/32\nTable = 1234\ndns = 9.9.9.9"
|
|
)
|
|
rendered = amneziawg_config.as_outbound(config, 2)
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "dns"), [])
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "table"), ["off"])
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "fwmark"), ["2"])
|
|
# The peer is untouched.
|
|
self.assertIn("Endpoint = vpn.example.com:51820", rendered)
|
|
|
|
def test_outbound_render_leaves_the_main_table_alone(self):
|
|
# A prefix on Address is a connected route in the main table, Table = off or not, and
|
|
# a privileged ListenPort is a port taken from the host: a spool entry gets neither.
|
|
config = BASE_CONFIG.replace(
|
|
"Address = 10.8.0.2/32",
|
|
"Address = 1.0.0.1/1, 128.0.0.1/1 # all of it\naddress = fd00::2/1\nListenPort = 53",
|
|
)
|
|
rendered = amneziawg_config.as_outbound(config, 2)
|
|
self.assertEqual(
|
|
amneziawg_config.section_values(rendered, "interface", "address"),
|
|
["1.0.0.1/32, 128.0.0.1/32", "fd00::2/128"],
|
|
)
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "listenport"), [])
|
|
kept = amneziawg_config.as_outbound(config.replace("ListenPort = 53", "ListenPort = 51820"), 2)
|
|
self.assertEqual(amneziawg_config.section_values(kept, "interface", "listenport"), ["51820"])
|
|
with self.assertRaises(ConfigError):
|
|
amneziawg_config.as_outbound(BASE_CONFIG.replace("10.8.0.2/32", "not-an-address"), 2)
|
|
# A declared profile keeps its prefix.
|
|
self.assertEqual(
|
|
amneziawg_config.section_values(
|
|
amneziawg_config.as_outbound(BASE_CONFIG.replace("10.8.0.2/32", "10.8.0.2/24"), 2, host_addresses=False),
|
|
"interface",
|
|
"address",
|
|
),
|
|
["10.8.0.2/24"],
|
|
)
|
|
|
|
def test_commented_headers_are_written_plainly(self):
|
|
# awg-quick takes "[Peer] # home vps" for [Peer]: so does everything here.
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "c.conf"
|
|
source.write_text(
|
|
BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
.replace("[Interface]", "[Interface] # laptop", 1)
|
|
.replace("[Peer]", "[peer] # home vps", 1)
|
|
)
|
|
config = prepare({"kind": "configFile", "path": str(source)})
|
|
self.assertIn("[Interface]\n", config)
|
|
self.assertIn("[Peer]\n", config)
|
|
self.assertNotIn("# home vps", config)
|
|
|
|
def test_headers_awg_quick_would_read_otherwise_are_refused(self):
|
|
# awg-quick cuts a header's comment first: "[Interface] #" opens an Interface section
|
|
# the rewrites would miss, with its Table, Address and DNS reaching the host.
|
|
for extra in ("[Interface] #\nTable = auto\n", "[Interface]#x\nDNS = 1.1.1.1\n", "[Interface]\nMTU = 1280\n"):
|
|
with self.subTest(extra=extra), self.assertRaises(ConfigError):
|
|
amneziawg_config.validate_config(BASE_CONFIG.replace("[Peer]", extra + "[Peer]", 1))
|
|
with self.assertRaises(ConfigError):
|
|
amneziawg_config.validate_config(BASE_CONFIG.replace("Address", "SaveConf\u0130g = true\nAddress", 1))
|
|
|
|
def test_outbound_render_leaves_no_second_table_or_fwmark(self):
|
|
# awg-quick takes the last line of a key: a later "Table = auto" would route the host.
|
|
config = BASE_CONFIG.replace(
|
|
"Address = 10.8.0.2/32",
|
|
"Address = 10.8.0.2/32\nTable = 1234\nFwMark = 1\nTable = auto\nfwmark = 0",
|
|
)
|
|
rendered = amneziawg_config.as_outbound(config, 2)
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "table"), ["off"])
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "fwmark"), ["2"])
|
|
|
|
def test_dns_servers_skip_search_domains(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1, corp.example,2606:4700::1111")
|
|
self.assertEqual(amneziawg_config.dns_servers(config), ["1.1.1.1", "2606:4700::1111"])
|
|
self.assertEqual(amneziawg_config.dns_servers("[Interface]\nAddress = 10.0.0.2/32\n"), [])
|
|
|
|
def test_dns_out_written_before_outbound_render_drops_dns(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "de.conf"
|
|
source.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1,8.8.8.8"))
|
|
output = Path(directory) / "out.conf"
|
|
dns = Path(directory) / "dns"
|
|
subprocess.run(
|
|
[
|
|
sys.executable,
|
|
amneziawg_config.__file__,
|
|
"--config",
|
|
str(source),
|
|
"--output",
|
|
str(output),
|
|
"--outbound-fwmark",
|
|
"2",
|
|
"--dns-out",
|
|
str(dns),
|
|
],
|
|
check=True,
|
|
)
|
|
self.assertEqual(dns.read_text(), "1.1.1.1\n8.8.8.8\n")
|
|
self.assertEqual(amneziawg_config.section_values(output.read_text(), "interface", "dns"), [])
|
|
|
|
def test_resolve_endpoints(self):
|
|
# Under the kill switch awg-quick gets addresses; a name that does not resolve is left.
|
|
config = "[Peer]\nEndpoint = vpn.example:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n"
|
|
|
|
def lookup(host, *_args, **_kwargs):
|
|
if host == "vpn.example":
|
|
return [(amneziawg_config.socket.AF_INET6, None, None, "", ("2001:db8::7", 51820, 0, 0))]
|
|
raise amneziawg_config.socket.gaierror("no such name")
|
|
|
|
with patch.object(amneziawg_config.socket, "getaddrinfo", side_effect=lookup):
|
|
rendered = amneziawg_config.resolve_endpoints(config)
|
|
self.assertEqual(
|
|
rendered,
|
|
"[Peer]\nEndpoint = [2001:db8::7]:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n",
|
|
)
|
|
|
|
def test_wireproxy_listener_takes_the_hop_login(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2, ("hop", "0123abcd"))
|
|
self.assertIn("[Socks5]\nBindAddress = 127.0.0.1:18700\nUsername = hop\nPassword = 0123abcd\n", rendered)
|
|
self.assertNotIn("Username", amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2))
|
|
with self.assertRaises(ConfigError):
|
|
amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2, ("hop", "a\nb"))
|
|
|
|
def test_endpoint_override(self):
|
|
# Only the first peer's Endpoint; a config without one cannot be overridden.
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "warp.conf"
|
|
source.write_text(
|
|
BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
+ "\n[Peer]\nPublicKey = other\nAllowedIPs = 10.0.0.0/8\nEndpoint = second.example:1\n"
|
|
)
|
|
config = prepare({"kind": "configFile", "path": str(source), "endpoint": "[2001:db8::1]:500"})
|
|
self.assertEqual(
|
|
amneziawg_config.section_values(config, "peer", "endpoint"),
|
|
["[2001:db8::1]:500", "second.example:1"],
|
|
)
|
|
rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2)
|
|
self.assertIn("[2001:db8::1]:500", amneziawg_config.section_values(rendered, "peer", "endpoint"))
|
|
self.assertIn("Endpoint = [2001:db8::1]:500", amneziawg_config.as_outbound(config, 2))
|
|
source.write_text("[Interface]\nPrivateKey = private\nAddress = 10.8.0.2/32\n[Peer]\nPublicKey = public\nAllowedIPs = 0.0.0.0/0\n")
|
|
with self.assertRaises(ConfigError):
|
|
prepare({"kind": "configFile", "path": str(source), "endpoint": "192.0.2.1:500"})
|
|
|
|
def test_global_render_pins_the_fwmark(self):
|
|
# The kill switch knows the tunnel's own packets by it; one set in the file is replaced.
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
source = Path(directory) / "home.conf"
|
|
output = Path(directory) / "out" / "home.conf"
|
|
source.write_text(
|
|
BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
|
|
"Address = 10.8.0.2/32", "Address = 10.8.0.2/32\nFwMark = 7"
|
|
)
|
|
)
|
|
result = subprocess.run(
|
|
[sys.executable, str(Path(__file__).with_name("amneziawg_config.py")),
|
|
"--config", str(source), "--output", str(output), "--fwmark", "51820"],
|
|
capture_output=True, text=True,
|
|
)
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
rendered = output.read_text()
|
|
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "fwmark"), ["51820"])
|
|
self.assertIn("DNS = 1.1.1.1", rendered)
|
|
|
|
def test_wireproxy_render_joins_lists_and_adds_socks_listener(self):
|
|
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
|
|
"Address = 10.8.0.2/32",
|
|
"Address = 10.8.0.2/32\nAddress = fd00::2/128\nTable = off\nPostUp = true\nDNS = 9.9.9.9",
|
|
) + "AllowedIPs = ::/0\n\n[Peer]\nPublicKey = other\nAllowedIPs = 10.0.0.0/8\n"
|
|
rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2)
|
|
sections = amneziawg_config.conf_sections(rendered)
|
|
self.assertEqual([name for name, _ in sections], ["interface", "peer", "peer", "socks5"])
|
|
interface = dict(sections[0][1])
|
|
self.assertEqual(interface["address"], "10.8.0.2/32,fd00::2/128")
|
|
self.assertEqual(interface["dns"], "9.9.9.9,1.1.1.1")
|
|
self.assertEqual(interface["fwmark"], "2")
|
|
self.assertEqual(interface["headerprotectionkey"], "header")
|
|
self.assertNotIn("table", interface)
|
|
self.assertNotIn("postup", interface)
|
|
self.assertEqual(dict(sections[1][1])["allowedips"], "0.0.0.0/0,::/0")
|
|
self.assertEqual(dict(sections[2][1])["publickey"], "other")
|
|
self.assertEqual(sections[3][1], [("bindaddress", "127.0.0.1:18700")])
|
|
# Rootless: no mark.
|
|
unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700")
|
|
self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), [])
|
|
|
|
def import_cli(self, text, *args):
|
|
return subprocess.run(
|
|
[sys.executable, amneziawg_config.__file__, "--import", "-", *args],
|
|
input=text,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
|
|
def test_import_conf_and_vpn_links(self):
|
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
config, described = amneziawg_config.import_source(conf)
|
|
self.assertIn("MTU = 1280", config)
|
|
self.assertEqual(described, {"name": "vpn.example.com", "endpoint": "vpn.example.com:51820"})
|
|
|
|
data = vpn_data(("amnezia-awg", "awg", BASE_CONFIG))
|
|
data["description"] = "Home server"
|
|
config, described = amneziawg_config.import_source(encode_vpn(data))
|
|
self.assertIn("DNS = 1.1.1.1,8.8.8.8", config)
|
|
self.assertEqual(described["name"], "Home server")
|
|
|
|
direct = "vpn://" + base64.urlsafe_b64encode(conf.encode()).decode()
|
|
self.assertIn("[Peer]", amneziawg_config.import_source(direct)[0])
|
|
|
|
def test_import_picks_a_container_and_refuses_hooks(self):
|
|
data = vpn_data(
|
|
("amnezia-awg", "awg", BASE_CONFIG),
|
|
("amnezia-awg2", "awg", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")),
|
|
)
|
|
data["defaultContainer"] = "not-awg"
|
|
with self.assertRaisesRegex(ConfigError, "multiple AmneziaWG"):
|
|
amneziawg_config.import_source(encode_vpn(data))
|
|
self.assertIn("10.9.0.2", amneziawg_config.import_source(encode_vpn(data), "amnezia-awg2")[0])
|
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
with self.assertRaisesRegex(ConfigError, "only applies"):
|
|
amneziawg_config.import_source(conf, "amnezia-awg")
|
|
with self.assertRaisesRegex(ConfigError, "privileged"):
|
|
amneziawg_config.import_source(conf.replace("Address =", "PostUp = id\nAddress ="))
|
|
with self.assertRaisesRegex(ConfigError, "expected"):
|
|
amneziawg_config.import_source("vless://nope")
|
|
|
|
def test_import_cli_writes_a_private_conf_and_describes_it(self):
|
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
output = Path(directory) / "home.conf"
|
|
result = self.import_cli(conf, "--describe", "--output", str(output))
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
self.assertEqual(json.loads(result.stdout)["name"], "vpn.example.com")
|
|
self.assertEqual(output.stat().st_mode & 0o777, 0o600)
|
|
self.assertIn("[Interface]", output.read_text())
|
|
hooked = self.import_cli(conf.replace("Address =", "PreUp = id\nAddress ="), "--output", str(output))
|
|
self.assertEqual(hooked.returncode, 1)
|
|
self.assertIn("privileged", hooked.stderr)
|
|
# A refused import leaves what was there.
|
|
self.assertIn("[Interface]", output.read_text())
|
|
self.assertEqual(self.import_cli(conf).returncode, 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|