feat: tproxy lan gateway, killswitch; fix: zapret2 fixes, various other
This commit is contained in:
54 files changed
+1880
-143
No files matched your search
@@ -10,6 +10,7 @@ import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import tempfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
@@ -366,6 +367,29 @@ def as_outbound(config: str, fwmark: int) -> str:
|
||||
return _set_interface_value(config, "FwMark", str(fwmark))
|
||||
|
||||
|
||||
ENDPOINT_LINE = re.compile(r"^(\s*Endpoint\s*=\s*)(\S+):(\d+)\s*$", re.IGNORECASE | re.MULTILINE)
|
||||
|
||||
|
||||
def resolve_endpoints(config: str) -> str:
|
||||
"""Endpoint names looked up here, by this process, as awg would; one that does not resolve is left."""
|
||||
|
||||
def resolve(match: re.Match[str]) -> str:
|
||||
prefix, host, port = match.groups()
|
||||
try:
|
||||
ipaddress.ip_address(host.strip("[]"))
|
||||
return match.group(0)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
family, *_, address = socket.getaddrinfo(host, int(port), type=socket.SOCK_DGRAM, flags=socket.AI_ADDRCONFIG)[0]
|
||||
except (OSError, UnicodeError):
|
||||
return match.group(0)
|
||||
ip = f"[{address[0]}]" if family == socket.AF_INET6 else address[0]
|
||||
return f"{prefix}{ip}:{port}"
|
||||
|
||||
return ENDPOINT_LINE.sub(resolve, config)
|
||||
|
||||
|
||||
# Read once by wireproxy: repeated lines are joined into one list.
|
||||
WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"}
|
||||
# wg-quick's, which wireproxy has no use for.
|
||||
@@ -737,6 +761,17 @@ def main() -> int:
|
||||
metavar="ADDRESS",
|
||||
help="render for wireproxy, as a SOCKS5 listener on ADDRESS (packets marked with --outbound-fwmark)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--fwmark",
|
||||
type=int,
|
||||
metavar="MARK",
|
||||
help="render a global profile whose own packets carry MARK (awg-quick routes it with table MARK)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--resolve-endpoints",
|
||||
action="store_true",
|
||||
help="write Endpoint names as the addresses they resolve to here",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--inspect",
|
||||
metavar="CONFIG",
|
||||
@@ -765,6 +800,10 @@ def main() -> int:
|
||||
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark)
|
||||
elif args.outbound_fwmark is not None:
|
||||
config = as_outbound(config, args.outbound_fwmark)
|
||||
elif args.fwmark is not None:
|
||||
config = _set_interface_value(config, "FwMark", str(args.fwmark))
|
||||
if args.resolve_endpoints:
|
||||
config = resolve_endpoints(config)
|
||||
write_private(args.output, config)
|
||||
except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc:
|
||||
parser.exit(1, f"amneziawg-config: {exc}\n")
|
||||
|
||||
+38
-13
@@ -17,8 +17,7 @@ from awg_inbound import client_entries
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
UUID_TYPES = ("vless", "vmess")
|
||||
PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http")
|
||||
UDP_TYPES = ("shadowsocks", "socks")
|
||||
PASSWORD_TYPES = ("trojan", "hysteria2", "shadowsocks", "socks", "http")
|
||||
|
||||
TRANSPORT_SETTINGS_KEY = {
|
||||
"ws": "wsSettings",
|
||||
@@ -78,6 +77,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
|
||||
client = {"id": secret, "email": email}
|
||||
if listener["type"] == "vless" and listener.get("flow"):
|
||||
client["flow"] = listener["flow"]
|
||||
elif listener["type"] == "hysteria2":
|
||||
client = {"auth": secret, "email": email}
|
||||
else:
|
||||
client = {"password": secret, "email": email}
|
||||
clients.append(client)
|
||||
@@ -93,6 +94,19 @@ def _accounts(listener: dict, tag: str) -> list[dict]:
|
||||
|
||||
|
||||
def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
if listener["type"] == "hysteria2":
|
||||
# QUIC: the transport is hysteria's own, always under TLS.
|
||||
settings = {"version": 2}
|
||||
masquerade = (listener.get("hysteria") or {}).get("masquerade")
|
||||
if masquerade:
|
||||
settings["masquerade"] = {"type": "proxy", "url": masquerade, "rewriteHost": True}
|
||||
return {
|
||||
"network": "hysteria",
|
||||
"hysteriaSettings": settings,
|
||||
"security": "tls",
|
||||
"tlsSettings": _tls_settings(listener["tls"], ["h3"]),
|
||||
}
|
||||
|
||||
transport = listener["transport"]
|
||||
network = transport["type"]
|
||||
stream: dict = {"network": network}
|
||||
@@ -131,22 +145,24 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
}
|
||||
elif tls["enable"] or listener["type"] == "trojan":
|
||||
stream["security"] = "tls"
|
||||
certificate = {
|
||||
"certificateFile": tls["certificateFile"],
|
||||
"keyFile": tls["keyFile"],
|
||||
}
|
||||
stream["tlsSettings"] = {"certificates": [certificate]}
|
||||
if tls.get("serverName"):
|
||||
stream["tlsSettings"]["serverName"] = tls["serverName"]
|
||||
# ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP.
|
||||
if tls.get("alpn"):
|
||||
stream["tlsSettings"]["alpn"] = tls["alpn"]
|
||||
stream["tlsSettings"] = _tls_settings(tls)
|
||||
else:
|
||||
stream["security"] = "none"
|
||||
|
||||
return stream
|
||||
|
||||
|
||||
def _tls_settings(tls: dict, default_alpn: list[str] | None = None) -> dict:
|
||||
settings: dict = {"certificates": [{"certificateFile": tls["certificateFile"], "keyFile": tls["keyFile"]}]}
|
||||
if tls.get("serverName"):
|
||||
settings["serverName"] = tls["serverName"]
|
||||
# ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP.
|
||||
alpn = tls.get("alpn") or default_alpn
|
||||
if alpn:
|
||||
settings["alpn"] = alpn
|
||||
return settings
|
||||
|
||||
|
||||
def render_xray_inbound(listener: dict) -> dict:
|
||||
"""Build one XRay inbound object from a typed listener spec."""
|
||||
tag = listener["tag"]
|
||||
@@ -158,6 +174,8 @@ def render_xray_inbound(listener: dict) -> dict:
|
||||
settings["decryption"] = "none"
|
||||
elif listener_type == "trojan":
|
||||
settings = {"clients": _clients(listener, tag)}
|
||||
elif listener_type == "hysteria2":
|
||||
settings = {"version": 2, "clients": _clients(listener, tag)}
|
||||
elif listener_type == "shadowsocks":
|
||||
settings = {"method": listener["method"], "network": "tcp,udp"}
|
||||
users = listener["users"]
|
||||
@@ -179,7 +197,8 @@ def render_xray_inbound(listener: dict) -> dict:
|
||||
"tag": tag,
|
||||
"listen": listener["listen"],
|
||||
"port": listener["port"],
|
||||
"protocol": listener_type,
|
||||
# XRay names hysteria2 "hysteria", and takes the version in its settings.
|
||||
"protocol": "hysteria" if listener_type == "hysteria2" else listener_type,
|
||||
"settings": settings,
|
||||
"streamSettings": _xray_stream(listener, tag),
|
||||
# routeOnly keeps the sniffed domain for routing decisions without
|
||||
@@ -316,6 +335,12 @@ def build_share_link(
|
||||
scheme = "https" if listener["tls"]["enable"] else "http"
|
||||
return f"{scheme}://{credentials}@{endpoint}#{fragment}"
|
||||
|
||||
if listener_type == "hysteria2":
|
||||
tls = listener["tls"]
|
||||
params = {"sni": tls.get("serverName") or server_address, "alpn": ",".join(tls.get("alpn") or ["h3"])}
|
||||
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
|
||||
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
|
||||
|
||||
params = _link_transport_params(listener)
|
||||
params.update(_link_security_params(listener, server_address))
|
||||
if listener_type == "vless" and listener.get("flow"):
|
||||
|
||||
@@ -458,6 +458,42 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
||||
# The peer is untouched.
|
||||
self.assertIn("Endpoint = vpn.example.com:51820", rendered)
|
||||
|
||||
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_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",
|
||||
|
||||
@@ -214,7 +214,7 @@ class RenderInboundTests(unittest.TestCase):
|
||||
|
||||
def test_unsupported_type_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported type"):
|
||||
render_xray_inbound(listener(type="hysteria2"))
|
||||
render_xray_inbound(listener(type="tuic"))
|
||||
|
||||
|
||||
class ShareLinkTests(unittest.TestCase):
|
||||
@@ -374,6 +374,34 @@ class RoundTripTests(unittest.TestCase):
|
||||
self.assertEqual(ob["transport"]["path"], "/download")
|
||||
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
||||
|
||||
def test_hysteria2_round_trip(self):
|
||||
spec = listener(
|
||||
type="hysteria2",
|
||||
port=8443,
|
||||
users=[{"name": "phone", "password": "p@ss/word", "passwordFile": None}],
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "hy.example.com"},
|
||||
hysteria={"masquerade": "https://www.example.com"},
|
||||
)
|
||||
ib = render_xray_inbound(spec)
|
||||
self.assertEqual(ib["protocol"], "hysteria")
|
||||
self.assertEqual(ib["settings"], {"version": 2, "clients": [{"auth": "p@ss/word", "email": "phone"}]})
|
||||
stream = ib["streamSettings"]
|
||||
self.assertEqual(stream["network"], "hysteria")
|
||||
self.assertEqual(stream["security"], "tls")
|
||||
self.assertEqual(stream["tlsSettings"]["alpn"], ["h3"])
|
||||
self.assertEqual(stream["hysteriaSettings"]["masquerade"]["url"], "https://www.example.com")
|
||||
link = build_share_link(spec, "vpn.example.com")
|
||||
self.assertTrue(link.startswith("hysteria2://p%40ss%2Fword@vpn.example.com:8443?"), link)
|
||||
self.assertEqual(link_params(link)["alpn"], "h3")
|
||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||
self.assertEqual(ob["type"], "hysteria2")
|
||||
self.assertEqual(ob["password"], "p@ss/word")
|
||||
self.assertEqual(ob["server_port"], 8443)
|
||||
self.assertEqual(ob["tls"]["server_name"], "hy.example.com")
|
||||
# Without masquerade XRay answers non-clients with 404; nothing to render.
|
||||
plain = render_xray_inbound(dict(spec, hysteria={"masquerade": None}))
|
||||
self.assertEqual(plain["streamSettings"]["hysteriaSettings"], {"version": 2})
|
||||
|
||||
def test_trojan_round_trip(self):
|
||||
link = build_share_link(
|
||||
listener(
|
||||
|
||||
Reference in new issue
Block a user