feat/wip: better awg to outbounds config
This commit is contained in:
26 files changed
+805
-218
No files matched your search
@@ -284,6 +284,29 @@ def _set_interface_value(config: str, key: str, value: str) -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _remove_interface_key(config: str, key: str) -> str:
|
||||
pattern = re.compile(rf"^\s*{re.escape(key)}\s*=", re.IGNORECASE)
|
||||
lines: list[str] = []
|
||||
in_interface = False
|
||||
for line in config.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("["):
|
||||
in_interface = stripped.lower() == "[interface]"
|
||||
if not (in_interface and pattern.match(line)):
|
||||
lines.append(line)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def as_outbound(config: str, fwmark: int) -> str:
|
||||
"""Keep the host's routes and resolver: the proxy binds to the interface instead.
|
||||
|
||||
The mark lets the tunnel's own packets past TUN and TProxy capture.
|
||||
"""
|
||||
config = _remove_interface_key(config, "DNS")
|
||||
config = _set_interface_value(config, "Table", "off")
|
||||
return _set_interface_value(config, "FwMark", str(fwmark))
|
||||
|
||||
|
||||
def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]:
|
||||
"""Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order.
|
||||
|
||||
@@ -607,6 +630,12 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest")
|
||||
parser.add_argument("--output")
|
||||
parser.add_argument(
|
||||
"--outbound-fwmark",
|
||||
type=int,
|
||||
metavar="MARK",
|
||||
help="render for an outbound-only interface: no routes or DNS, packets marked MARK",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--inspect",
|
||||
metavar="CONFIG",
|
||||
@@ -625,7 +654,10 @@ def main() -> int:
|
||||
manifest = json.loads(_read_limited(args.manifest))
|
||||
if not isinstance(manifest, dict):
|
||||
raise ConfigError("manifest must be a JSON object")
|
||||
write_private(args.output, prepare(manifest))
|
||||
config = prepare(manifest)
|
||||
if args.outbound_fwmark is not None:
|
||||
config = as_outbound(config, args.outbound_fwmark)
|
||||
write_private(args.output, config)
|
||||
except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc:
|
||||
parser.exit(1, f"amneziawg-config: {exc}\n")
|
||||
return 0
|
||||
|
||||
@@ -447,6 +447,17 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
||||
"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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import unittest
|
||||
|
||||
from warp_outbound import ConfigError, build
|
||||
from warp_outbound import ConfigError, build, obfuscation_keys
|
||||
|
||||
WGCF = """[Interface]
|
||||
PrivateKey = priv=
|
||||
@@ -38,6 +38,12 @@ class WarpOutboundTest(unittest.TestCase):
|
||||
ob = build(WGCF.replace("[Peer]", "RekeyAfterTime = 100-120\n[Peer]\nPersistentKeepalive = 25-35"), "warp", None)
|
||||
self.assertEqual(ob["peers"][0]["persistent_keepalive_interval"], 25)
|
||||
|
||||
def test_obfuscation_keys(self):
|
||||
self.assertEqual(obfuscation_keys(WGCF), [])
|
||||
awg = WGCF.replace("[Peer]", "Jc = 4\nH1 = 1-2\n[Peer]")
|
||||
self.assertEqual(obfuscation_keys(awg), ["h1", "jc"])
|
||||
self.assertNotIn("jc", build(awg, "warp", None))
|
||||
|
||||
def test_rejects_missing_peer(self):
|
||||
with self.assertRaises(ConfigError):
|
||||
build(WGCF.split("[Peer]")[0], "warp", None)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Turn a WireGuard .conf (e.g. wgcf-profile.conf) into a sing-box WireGuard endpoint for WARP."""
|
||||
"""Turn a WireGuard .conf (a wgcf profile, an AmneziaWG profile) into a sing-box WireGuard endpoint."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -8,7 +8,7 @@ import json
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from amneziawg_config import ConfigError, conf_sections
|
||||
from amneziawg_config import VPN_INTERFACE_FIELDS, ConfigError, conf_sections
|
||||
|
||||
|
||||
def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]:
|
||||
@@ -62,16 +62,33 @@ def build(text: str, tag: str, routing_mark: int | None) -> dict[str, Any]:
|
||||
return endpoint
|
||||
|
||||
|
||||
def obfuscation_keys(text: str) -> list[str]:
|
||||
"""AmneziaWG [Interface] keys sing-box has no use for; the endpoint goes without them."""
|
||||
return sorted(
|
||||
{key for name, pairs in conf_sections(text) if name == "interface" for key, _ in pairs}
|
||||
& VPN_INTERFACE_FIELDS.keys()
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--tag", default="warp")
|
||||
parser.add_argument("--routing-mark", type=int)
|
||||
args = parser.parse_args()
|
||||
text = sys.stdin.read()
|
||||
try:
|
||||
print(json.dumps(build(sys.stdin.read(), args.tag, args.routing_mark)))
|
||||
print(json.dumps(build(text, args.tag, args.routing_mark)))
|
||||
except ValueError as error:
|
||||
print(f"proxy-suite: warp: {error}", file=sys.stderr)
|
||||
print(f"proxy-suite: {args.tag}: {error}", file=sys.stderr)
|
||||
return 1
|
||||
dropped = obfuscation_keys(text)
|
||||
if dropped:
|
||||
names = ", ".join(VPN_INTERFACE_FIELDS[key] for key in dropped)
|
||||
print(
|
||||
f"proxy-suite: {args.tag}: warning: sing-box speaks plain WireGuard; dropping {names}."
|
||||
" A server that expects them will not answer",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user