diff --git a/docs/options.md b/docs/options.md index 3bde50d..1395612 100644 --- a/docs/options.md +++ b/docs/options.md @@ -14,7 +14,7 @@ Update module option docs there instead of editing this file by hand. - [enable](#services-proxy-suite-amneziawg-enable) - [kernelModulePackage](#services-proxy-suite-amneziawg-kernelmodulepackage) - [profiles](#services-proxy-suite-amneziawg-profiles) - - + - `` - [allowConfigHooks](#services-proxy-suite-amneziawg-profiles-name-allowconfighooks) - [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart) - [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile) @@ -51,6 +51,7 @@ Update module option docs there instead of editing this file by hand. - [s2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2) - [s3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3) - [s4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4) + - [obfuscationFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscationfile) - [peers](#services-proxy-suite-amneziawg-profiles-name-settings-peers) - item - [advancedSecurity](#services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity) @@ -1765,6 +1766,46 @@ null + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscationFile + + + +Runtime path to a partial JSON object using the same field names and +value types as obfuscation, excluding headerProtectionKeyFile\. +Values are combined with public obfuscation settings at service startup +without putting the file contents in the Nix store\. Omitted or null +fields are unset; duplicate JSON keys and fields set in both sources +are rejected\. A file-provided headerProtectionKey also conflicts with +obfuscation\.headerProtectionKeyFile\. Private and preshared keys use +their existing file options\. Restart the profile after secret rotation\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/run/secrets/awg-obfuscation.json" +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + ## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers @@ -3773,8 +3814,6 @@ list of string ## services\.proxy-suite\.proxy\.routing\.proxy\.domains - - Domain suffixes to match in this routing rule\. Leave empty to skip domain-based matching for this rule entry\. @@ -3810,6 +3849,8 @@ list of string ## services\.proxy-suite\.proxy\.routing\.proxy\.geoips + + sing-geoip rule-set names to match in this routing rule\. Each name becomes a backend geoip rule-set reference\. diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index cbdf7c2..3bad731 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -232,6 +232,21 @@ let default = { }; description = "AmneziaWG 1.x through 3.x obfuscation parameters."; }; + obfuscationFile = mkOption { + type = optionalString; + default = null; + example = "/run/secrets/awg-obfuscation.json"; + description = '' + Runtime path to a partial JSON object using the same field names and + value types as obfuscation, excluding headerProtectionKeyFile. + Values are combined with public obfuscation settings at service startup + without putting the file contents in the Nix store. Omitted or null + fields are unset; duplicate JSON keys and fields set in both sources + are rejected. A file-provided headerProtectionKey also conflicts with + obfuscation.headerProtectionKeyFile. Private and preshared keys use + their existing file options. Restart the profile after secret rotation. + ''; + }; peers = mkOption { type = types.listOf peerType; default = [ ]; diff --git a/nix/checks/amnezia-wg-runtime.nix b/nix/checks/amnezia-wg-runtime.nix index 53083c0..780f9a4 100644 --- a/nix/checks/amnezia-wg-runtime.nix +++ b/nix/checks/amnezia-wg-runtime.nix @@ -31,14 +31,14 @@ let enable = true; amneziaWg = { enable = true; - kernelModulePackage = - if userspaceOnly then null else awgPackages.kernelModule pkgs.linuxPackages; + kernelModulePackage = if userspaceOnly then null else awgPackages.kernelModule pkgs.linuxPackages; profiles.test = { interfaceName = "awg-test"; settings = { addresses = [ "10.23.42.2/32" ]; privateKey = keys.peer1.privateKey; - inherit obfuscation; + obfuscation = { inherit (obfuscation) s1 s2; }; + obfuscationFile = "/run/awg-obfuscation.json"; peers = [ { publicKey = keys.peer0.publicKey; @@ -107,8 +107,16 @@ pkgs.testers.runNixOSTest { start_all() server.wait_for_unit("wg-quick-awg-server.service") + # Provision the partial secret after boot, outside the generated manifest. + for machine in (kernel, userspace): + machine.succeed("""umask 077; echo '${ + builtins.toJSON { inherit (obfuscation) jc jmin jmax; } + }' > /run/awg-obfuscation.json""") + with subtest("packaged kernel module"): kernel.succeed("systemctl start proxy-suite-awg-test.service") + kernel.succeed("test $(stat -c %a /run/proxy-suite-awg-test/awg-test.conf) = 600") + kernel.succeed("test $(stat -c %a /run/proxy-suite-awg-test) = 700") kernel.succeed("ip -d link show awg-test | grep -q amneziawg") kernel.succeed("ping -c 5 10.23.42.1") kernel.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0") @@ -118,6 +126,8 @@ pkgs.testers.runNixOSTest { with subtest("automatic userspace fallback"): userspace.fail("modprobe -n amneziawg") userspace.succeed("systemctl start proxy-suite-awg-test.service") + userspace.succeed("test $(stat -c %a /run/proxy-suite-awg-test/awg-test.conf) = 600") + userspace.succeed("test $(stat -c %a /run/proxy-suite-awg-test) = 700") userspace.succeed("test -r /sys/class/net/awg-test/tun_flags") userspace.succeed("ping -c 5 10.23.42.1") userspace.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0") diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index 22253bb..3f0ca05 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -34,6 +34,7 @@ let settings = { addresses = [ "10.8.0.2/32" ]; privateKeyFile = "/run/secrets/awg-private"; + obfuscationFile = "/run/secrets/awg-obfuscation.json"; obfuscation = { s1 = 12; s2 = 12; @@ -154,11 +155,33 @@ let withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost; in { + manifest = pkgs.runCommand "amneziawg-secret-manifest-check" { } '' + ${pkgs.python3}/bin/python3 - <<'PY' + import json + import shlex + from pathlib import Path + + prepare = Path("${builtins.head homeService.serviceConfig.ExecStartPre}").read_text() + args = shlex.split(prepare) + manifest = json.loads(Path(args[args.index("--manifest") + 1]).read_text()) + assert manifest["kind"] == "settings" + assert manifest["settings"]["obfuscationFile"] == "/run/secrets/awg-obfuscation.json" + assert manifest["settings"]["obfuscation"]["s1"] == 12 + assert manifest["settings"]["obfuscation"]["i1"] is None + PY + touch "$out" + ''; + assertions = [ ( assert !awgOnly.config.services.proxy-suite.proxy.enable; assert homeService.serviceConfig.RuntimeDirectoryMode == "0700"; assert homeService.serviceConfig.UMask == "0077"; + assert + awgOnly.config.services.proxy-suite.amneziaWg.profiles.home.settings.obfuscationFile + == "/run/secrets/awg-obfuscation.json"; + assert + sourceFixture.config.services.proxy-suite.amneziaWg.profiles.nix.settings.obfuscationFile == null; assert builtins.elem "multi-user.target" homeService.wantedBy; assert builtins.elem "proxy-suite-awg-work.service" homeService.conflicts; assert builtins.elem "proxy-suite-tun.service" homeService.conflicts; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 881c340..614e32c 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -217,6 +217,7 @@ let in { proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); + amneziawg-secret-manifest = amneziaWgChecks.manifest; xray-jq-filter-runtime = xrayBackendChecks.runtime; per-app-zapret-runtime = perAppRoutingChecks.runtime; zapret-hostlist-rules = zapretChecks.rules; diff --git a/nix/options-doc/render-options-markdown.nix b/nix/options-doc/render-options-markdown.nix index f42a9bc..b8e8c29 100644 --- a/nix/options-doc/render-options-markdown.nix +++ b/nix/options-doc/render-options-markdown.nix @@ -93,6 +93,9 @@ pkgs.runCommand "proxy-suite-options.md" { } '' if (label == "*") { return "item" } + if (label ~ /^<.*>$/) { + return "`" label "`" + } return label } diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index c011edb..21bf9c7 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -319,6 +319,102 @@ def _secret_value(inline: Any, path: Any, label: str) -> str: return value +OBFUSCATION_UNSIGNED_FIELDS = {"jc", "jmin", "jmax", "s1", "s2", "s3", "s4"} +OBFUSCATION_RANGE_FIELDS = { + "h1", + "h2", + "h3", + "h4", + "contentPaddingAddition", + "rekeyAfterTime", + "rekeyTimeout", + "rejectAfterTime", + "keepaliveTimeout", + "maxHandshakeAttempts", +} +OBFUSCATION_STRING_FIELDS = {"i1", "i2", "i3", "i4", "i5", "headerProtectionKey"} +OBFUSCATION_BOOLEAN_FIELDS = {"randomTrailers", "disableCookies"} + + +def _unique_secret_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + # Even a key can contain secret input; do not echo it. + raise ConfigError("obfuscationFile contains duplicate JSON keys") + result[key] = value + return result + + +def _reject_secret_constant(value: str) -> Any: + raise ConfigError("obfuscationFile contains an invalid JSON constant") + + +def _merge_obfuscation(settings: dict[str, Any]) -> dict[str, Any]: + public = settings.get("obfuscation", {}) + if not isinstance(public, dict): + raise ConfigError("obfuscation must be an object") + path = settings.get("obfuscationFile") + if path is None: + return public + try: + secret = json.loads( + _read_limited(str(path)), + object_pairs_hook=_unique_secret_object, + parse_constant=_reject_secret_constant, + ) + except (OSError, UnicodeError, ValueError, RecursionError) as exc: + # Decoder errors and OS exceptions can include input excerpts or paths. + message = ( + str(exc) if isinstance(exc, ConfigError) + else "cannot read or decode obfuscationFile" + ) + raise ConfigError(message) from None + if not isinstance(secret, dict): + raise ConfigError("obfuscationFile must contain a JSON object") + + merged = dict(public) + known = ( + OBFUSCATION_UNSIGNED_FIELDS | OBFUSCATION_RANGE_FIELDS + | OBFUSCATION_STRING_FIELDS | OBFUSCATION_BOOLEAN_FIELDS + ) + for key, value in secret.items(): + if key not in known: + raise ConfigError("obfuscationFile contains an unsupported field") + if value is None: + continue + if public.get(key) is not None or ( + key == "headerProtectionKey" and public.get("headerProtectionKeyFile") is not None + ): + raise ConfigError(f"obfuscationFile field '{key}' has multiple sources") + unsigned = type(value) is int and value >= 0 + if key in OBFUSCATION_UNSIGNED_FIELDS: + valid = unsigned + elif key in OBFUSCATION_RANGE_FIELDS: + valid = unsigned or ( + isinstance(value, str) + and re.fullmatch(r"([0-9]+|[0-9]+-[0-9]+|\(off\))", value) is not None + ) + elif key in OBFUSCATION_BOOLEAN_FIELDS: + valid = type(value) is bool + else: + valid = ( + isinstance(value, str) + and bool(value.strip()) + and value.splitlines() == [value] + and "\x00" not in value + ) + if valid: + try: + value.encode("utf-8") + except UnicodeEncodeError: + valid = False + if not valid: + raise ConfigError(f"obfuscationFile field '{key}' has an invalid value") + merged[key] = value + return merged + + def render_settings(settings: dict[str, Any]) -> str: addresses = settings.get("addresses", []) peers = settings.get("peers", []) @@ -346,9 +442,7 @@ def render_settings(settings: dict[str, Any]) -> str: if settings.get(source) is not None: lines.append(f"{target} = {settings[source]}") - obfuscation = settings.get("obfuscation", {}) - if not isinstance(obfuscation, dict): - raise ConfigError("obfuscation must be an object") + obfuscation = _merge_obfuscation(settings) obfuscation_map = { "jc": "Jc", "jmin": "Jmin", diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index bb36c78..00c36c2 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -2,10 +2,13 @@ import base64 import json +import subprocess +import sys import tempfile import unittest import zlib from pathlib import Path +from unittest.mock import patch from amneziawg_config import ( ConfigError, @@ -65,6 +68,139 @@ def encode_vpn(data, compressed=True): 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": "", "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)