fix: hardening

This commit is contained in:
FUFSoB committed 2026-10-05 22:44:09 +05:00
1 parent 017a947a18
commit a435942b4f
168 files changed
+9166 -1644

No files matched your search

+103 -11
View File
@@ -389,14 +389,61 @@ def dns_servers(config: str) -> list[str]:
return servers
def as_outbound(config: str, fwmark: int) -> str:
def _host_addresses(config: str) -> str:
"""Every [Interface] Address narrowed to the host itself (/32, /128): the kernel routes
its prefix in the main table whatever Table says, and an outbound has no use for it."""
pattern = re.compile(r"^(\s*Address\s*=\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]"
match = pattern.match(line) if in_interface else None
if match:
hosts = []
for item in match.group(2).split("#", 1)[0].split(","):
item = item.strip()
if not item:
continue
try:
interface = ipaddress.ip_interface(item)
except ValueError as exc:
raise ConfigError(f"invalid interface Address '{item}'") from exc
hosts.append(f"{interface.ip}/{interface.max_prefixlen}")
line = f"{match.group(1)}{', '.join(hosts)}"
lines.append(line)
return "\n".join(lines) + "\n"
def _replace_interface_key(config: str, key: str, value: str) -> str:
"""key set to value, every other line of it gone: wg and awg-quick take the last one,
so `Table = 1234` then `Table = auto` would keep auto past a rewrite of the first."""
return _set_interface_value(_remove_interface_key(config, key), key, value)
def _drop_privileged_listen_port(config: str) -> str:
"""A privileged ListenPort (53, say), bound by root, would take it from the host's own
services: the port goes, and the tunnel takes any."""
for value in section_values(config, "interface", "listenport"):
if not value.strip().isascii() or not value.strip().isdigit() or int(value.strip()) < 1024:
return _remove_interface_key(config, "ListenPort")
return config
def as_outbound(config: str, fwmark: int, host_addresses: bool = True) -> 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.
The mark lets the tunnel's own packets past TUN and TProxy capture. host_addresses
narrows Address to the host (_host_addresses), for a profile from a shared spool.
"""
config = _remove_interface_key(config, "DNS")
config = _set_interface_value(config, "Table", "off")
return _set_interface_value(config, "FwMark", str(fwmark))
if host_addresses:
config = _host_addresses(config)
# Any source port does for an outbound.
config = _drop_privileged_listen_port(config)
config = _replace_interface_key(config, "Table", "off")
return _replace_interface_key(config, "FwMark", str(fwmark))
ENDPOINT_LINE = re.compile(r"^(\s*Endpoint\s*=\s*)(\S+):(\d+)\s*$", re.IGNORECASE | re.MULTILINE)
@@ -436,7 +483,9 @@ WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"}
WIREPROXY_DROPPED_KEYS = FORBIDDEN_WG_QUICK_KEYS | {"table", "fwmark"}
def as_wireproxy(config: str, socks_address: str, fwmark: int | None = None) -> str:
def as_wireproxy(
config: str, socks_address: str, fwmark: int | None = None, login: tuple[str, str] | None = None
) -> str:
"""A wireproxy configuration: the profile, served as a SOCKS5 listener on socks_address.
With fwmark, the tunnel's own packets are marked, to get past TUN and TProxy capture.
@@ -463,6 +512,12 @@ def as_wireproxy(config: str, socks_address: str, fwmark: int | None = None) ->
if name == "interface" and fwmark is not None:
lines.append(f"fwmark = {fwmark}")
lines.extend(["", "[Socks5]", f"BindAddress = {socks_address}"])
# Both, or wireproxy takes no login at all: a password alone is none.
if login is not None:
user, password = login
if not re.fullmatch(r"[A-Za-z0-9._-]+", user) or not re.fullmatch(r"[A-Za-z0-9._-]+", password):
raise ConfigError("the SOCKS login must be letters, digits, dot, dash and underscore")
lines.extend([f"Username = {user}", f"Password = {password}"])
return "\n".join(lines) + "\n"
@@ -703,11 +758,27 @@ def validate_config(config: str, allow_hooks: bool = False) -> None:
lowered = config.lower()
if "[interface]" not in lowered or "[peer]" not in lowered:
raise ConfigError("configuration requires [Interface] and [Peer] sections")
# Headers exactly as written, one [Interface]: one the rewrites here miss would let its
# Table, Address or DNS reach the host untouched.
interfaces = 0
for line in config.split("\n"):
stripped = line.strip()
if not stripped.split("#", 1)[0].strip().startswith("["):
continue
if stripped.lower() not in ("[interface]", "[peer]"):
raise ConfigError(f"unexpected section header {stripped[:40]!r}: only [Interface] and [Peer], alone on their line")
interfaces += stripped.lower() == "[interface]"
if interfaces != 1:
raise ConfigError("configuration needs exactly one [Interface] section")
if not allow_hooks:
# Read as awg-quick reads it: lines end at \n, a comment starts at #, and the
# key is what precedes the first =, or the whole line without one.
for line in config.split("\n"):
key = line.split("#", 1)[0].split("=", 1)[0].strip().lower()
# A non-ASCII key can fold to one under the shell's case-insensitive match
# ("SaveConfİg" is SaveConfig to awg-quick's nocasematch); no real key has one.
if not key.isascii():
raise ConfigError(f"configuration has a key with non-ASCII characters: {key[:40]!r}")
if key in FORBIDDEN_WG_QUICK_KEYS:
raise ConfigError(
f"configuration contains privileged wg-quick directive '{key}'; "
@@ -758,6 +829,18 @@ def rekey_after_time(config: str) -> int:
return int(values[-1].split("-")[-1])
def _normalize_headers(config: str) -> str:
"""Section headers as awg-quick reads them ("[Peer] # home" opens a Peer section),
written plainly so the rewrites here see every section it will."""
lines = []
for line in config.split("\n"):
header = line.split("#", 1)[0].strip().lower()
if header in ("[interface]", "[peer]"):
line = "[Interface]" if header == "[interface]" else "[Peer]"
lines.append(line)
return "\n".join(lines)
def prepare(manifest: dict[str, Any]) -> str:
kind = manifest.get("kind")
if kind == "configFile":
@@ -769,7 +852,7 @@ def prepare(manifest: dict[str, Any]) -> str:
config = render_settings(_decode_json_value(manifest.get("settings"), "settings"))
else:
raise ConfigError(f"unsupported manifest kind '{kind}'")
config = _apply_awg3_mtu_default(config)
config = _apply_awg3_mtu_default(_normalize_headers(config))
if manifest.get("endpoint") is not None:
config = override_endpoint(config, str(manifest["endpoint"]))
validate_config(config, bool(manifest.get("allowConfigHooks", False)))
@@ -786,7 +869,7 @@ def import_source(text: str, container: str | None = None) -> tuple[str, dict[st
name = ""
if text.startswith("vpn://"):
data = decode_vpn_link(text)
config = extract_vpn_config(data, container)
config = _normalize_headers(extract_vpn_config(data, container))
for key in ("description", "name", "hostName"):
if isinstance(data.get(key), str) and data[key].strip():
name = data[key].strip()
@@ -794,7 +877,7 @@ def import_source(text: str, container: str | None = None) -> tuple[str, dict[st
elif "[interface]" in text.lower():
if container:
raise ConfigError("--container only applies to a vpn:// link")
config = _apply_awg3_mtu_default(text + "\n")
config = _apply_awg3_mtu_default(_normalize_headers(text + "\n"))
else:
raise ConfigError("expected an AmneziaWG .conf or a vpn:// link")
validate_config(config)
@@ -915,11 +998,20 @@ def main() -> int:
# Before the outbound rendering drops them: per-app routing sends the app's DNS here.
write_private(args.dns_out, "".join(f"{server}\n" for server in dns_servers(config)))
if args.wireproxy is not None:
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark)
# The listener's login from the environment (wg-tunnel.nix): argv is public.
hop_password = os.environ.get("HOP_PASSWORD", "")
login = (os.environ.get("HOP_USER", "hop"), hop_password) if hop_password else None
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark, login)
elif args.outbound_fwmark is not None:
config = as_outbound(config, args.outbound_fwmark)
# A declared profile keeps its prefixes; one from a group-writable spool may not
# route a range of the host's into its tunnel.
shared = args.config is not None and _shared_directory(args.config)
config = as_outbound(config, args.outbound_fwmark, host_addresses=shared)
elif args.fwmark is not None:
config = _set_interface_value(config, "FwMark", str(args.fwmark))
config = _replace_interface_key(config, "FwMark", str(args.fwmark))
if args.wireproxy is None and args.config is not None and _shared_directory(args.config):
# A global profile from the group-writable spool, which root's awg-quick brings up.
config = _drop_privileged_listen_port(config)
if args.resolve_endpoints:
config = resolve_endpoints(config)
if args.wireproxy is None:
+9 -2
View File
@@ -220,8 +220,15 @@ require_cmd "$IP_BIN"
require_cmd "$NFT_BIN"
require_cmd "$CURL_BIN"
OUTPUT_DIR="${1:-/tmp/proxy-suite-xray-tun-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "$OUTPUT_DIR"
# Run as root, with captures of the journal and the ruleset: a fresh private directory,
# never one another user could have made first.
umask 077
if [ -n "${1:-}" ]; then
OUTPUT_DIR=$1
mkdir -p "$OUTPUT_DIR"
else
OUTPUT_DIR=$(mktemp -d "${TMPDIR:-/tmp}/proxy-suite-xray-tun-$(date +%Y%m%d-%H%M%S)-XXXXXX")
fi
ORIG_PROXY_ACTIVE=0
ORIG_TUN_ACTIVE=0
+195 -6
View File
@@ -3,9 +3,137 @@
import argparse
import json
import re
import signal
import subprocess
import sys
import time
import urllib.error
from proxy_parsing import decode_subscription, fetch_raw, parse_hybrid_subscription, parse_subscription
from proxy_parsing import (
FetchError,
decode_subscription,
fetch_raw,
parse_hybrid_subscription,
parse_subscription,
)
# The whole fetch: the socket timeout bounds one read only, and a server trickling its
# reply would otherwise hold a cold start, which waits on this, for as long as it liked.
OVERALL_DEADLINE_SECONDS = 90
def _out_of_time(_signum, _frame):
raise FetchError(f"subscription fetch took longer than {OVERALL_DEADLINE_SECONDS}s")
def _describe(exc: Exception) -> str:
"""The error, unless it may quote the URL: http.client's InvalidURL and "nonnumeric port"
carry the path or the userinfo, which hold the subscription's token."""
if isinstance(exc, (FetchError, urllib.error.URLError, TimeoutError, ConnectionError)):
return str(exc)
return type(exc).__name__
# Runs of the backend's own check one subscription may take, and their wall time: past
# either, what is left goes unchecked rather than dropped.
MAX_CHECK_RUNS = 256
CHECK_BUDGET_SECONDS = 120
# Where the backend's refusal names the outbound at fault.
_XRAY_REFUSED_TAG = re.compile(r"failed to build outbound config with tag (.*?)(?: > |$)", re.MULTILINE)
_SING_BOX_REFUSED_INDEX = re.compile(r"\boutbounds?\[(\d+)\]")
class _OutOfBudget(Exception):
pass
class _Checker:
"""The backend's own config check of a batch: one entry it refuses would fail its whole
start, every other outbound with it, so the refused ones go here instead."""
def __init__(self, kind: str, binary: str):
self.kind = kind
self.binary = binary
self.runs = 0
self.deadline = time.monotonic() + CHECK_BUDGET_SECONDS
def refused(self, outbounds: list[dict]) -> "int | None":
"""None when the backend takes the batch; else the index of the outbound its error
names, or -1 when it names none."""
if self.runs >= MAX_CHECK_RUNS or time.monotonic() >= self.deadline:
raise _OutOfBudget
self.runs += 1
if self.kind == "sing-box":
argv = [self.binary, "check", "-c", "/dev/stdin"]
obs = [{k: v for k, v in ob.items() if k not in ("detour", "domain_resolver")} for ob in outbounds]
else:
argv = [self.binary, "run", "-test", "-format", "json", "-c", "stdin:"]
obs = [{k: v for k, v in ob.items() if k != "proxySettings"} for ob in outbounds]
try:
result = subprocess.run(
argv,
input=json.dumps({"outbounds": obs}).encode(),
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=max(self.deadline - time.monotonic(), 1),
check=False,
)
except subprocess.TimeoutExpired:
raise _OutOfBudget from None
if result.returncode == 0:
return None
error = result.stderr.decode("utf-8", errors="replace")
if self.kind == "sing-box":
match = _SING_BOX_REFUSED_INDEX.search(error)
if match and int(match.group(1)) < len(outbounds):
return int(match.group(1))
elif match := _XRAY_REFUSED_TAG.search(error):
for index, ob in enumerate(outbounds):
if ob.get("tag") == match.group(1):
return index
return -1
def keep(self, outbounds: list[dict]) -> list[dict]:
"""The outbounds the backend takes, dropping each one it refuses."""
if not outbounds:
return outbounds
# A check that fails on nothing at all says nothing about the entries.
try:
works = self.refused([]) is None
except (OSError, _OutOfBudget):
works = False
if not works:
print(f"warning: {self.kind}'s config check does not run; entries left unchecked", file=sys.stderr)
return outbounds
return self._keep(list(outbounds))
def _drop(self, outbound: dict) -> None:
print(f"warning: skipping entry {outbound.get('tag')!r}: {self.kind} refuses it", file=sys.stderr)
def _keep(self, batch: list[dict]) -> list[dict]:
while batch:
try:
refused = self.refused(batch)
except (OSError, _OutOfBudget):
print(
f"warning: {len(batch)} entries left unchecked: {self.kind}'s check could not finish",
file=sys.stderr,
)
return batch
if refused is None:
return batch
if refused >= 0:
self._drop(batch.pop(refused))
continue
# An error that names no outbound: bisect.
if len(batch) == 1:
self._drop(batch[0])
return []
middle = len(batch) // 2
return self._keep(batch[:middle]) + self._keep(batch[middle:])
return batch
def main() -> None:
@@ -23,34 +151,95 @@ def main() -> None:
ap.add_argument(
"--links-out", default=None, dest="links_out", help="Also write {tag: original URI} here, for sharing."
)
# For a caller that drops privileges first: root opens the file, this only writes to it.
ap.add_argument(
"--links-fd", type=int, default=None, dest="links_fd", help="As --links-out, to this open descriptor."
)
ap.add_argument(
"--allow-private-servers",
action="store_true",
dest="allow_private",
help="Keep entries whose server is on a private network (RFC 1918, CGNAT, ULA).",
)
ap.add_argument(
"--allow-insecure",
action="store_true",
dest="allow_insecure",
help="Keep entries that turn certificate checks off (insecure=1).",
)
ap.add_argument(
"--https-only",
action="store_true",
dest="https_only",
help="Refuse an http:// URL: anyone on the way could hand over entries of their own.",
)
ap.add_argument("--check-sing-box", default=None, dest="check_sing_box", metavar="SING_BOX",
help="Drop the sing-box entries this sing-box binary's config check refuses.")
ap.add_argument("--check-xray", default=None, dest="check_xray", metavar="XRAY",
help="Drop the XRay entries this xray binary's config check refuses.")
args = ap.parse_args()
checkers = {
kind: _Checker(kind, binary)
for kind, binary in (("sing-box", args.check_sing_box), ("xray", args.check_xray))
if binary
}
def checked(kind: str, outbounds: list[dict]) -> list[dict]:
return checkers[kind].keep(outbounds) if kind in checkers else outbounds
url = sys.stdin.read().strip()
if not url:
print("error: no URL provided on stdin", file=sys.stderr)
sys.exit(1)
if args.https_only and not url.lower().startswith("https://"):
print("error: this subscription must be an https:// URL", file=sys.stderr)
sys.exit(1)
signal.signal(signal.SIGALRM, _out_of_time)
signal.alarm(OVERALL_DEADLINE_SECONDS)
try:
raw = fetch_raw(url)
except Exception as exc:
print(f"error: failed to fetch subscription: {exc}", file=sys.stderr)
print(f"error: failed to fetch subscription: {_describe(exc)}", file=sys.stderr)
sys.exit(1)
finally:
signal.alarm(0)
lines = decode_subscription(raw)
links: dict[str, str] = {}
if args.backend == "hybrid":
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark, links)
outbounds = parse_hybrid_subscription(
lines,
args.tag_prefix,
args.routing_mark,
links,
allow_private=args.allow_private,
allow_insecure=args.allow_insecure,
)
outbounds = {"singBox": checked("sing-box", outbounds["singBox"]), "xray": checked("xray", outbounds["xray"])}
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
else:
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend, links)
outbounds = parse_subscription(
lines,
args.tag_prefix,
args.routing_mark,
args.backend,
links,
allow_private=args.allow_private,
allow_insecure=args.allow_insecure,
)
outbounds = checked(args.backend, outbounds)
has_outbounds = bool(outbounds)
if not has_outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
sys.exit(1)
if args.links_out:
with open(args.links_out, "w", encoding="utf-8") as handle:
kept = {ob.get("tag") for ob in (outbounds["singBox"] + outbounds["xray"] if args.backend == "hybrid" else outbounds)}
links = {tag: line for tag, line in links.items() if tag in kept}
links_target = args.links_out or args.links_fd
if links_target is not None:
with open(links_target, "w", encoding="utf-8") as handle:
json.dump(links, handle)
print(json.dumps(outbounds))
+255 -32
View File
@@ -22,6 +22,7 @@ from __future__ import annotations
import argparse
import base64
import copy
import fcntl
import hashlib
import ipaddress
import json
@@ -32,7 +33,8 @@ import socket
import stat
import subprocess
import sys
import tempfile
import time
import urllib.parse
import uuid
# User names and listener tags: they become file names, XRay emails and tags, and URL parts.
@@ -63,7 +65,6 @@ SS_METHODS = (
"chacha20-ietf-poly1305",
"xchacha20-poly1305",
"xchacha20-ietf-poly1305",
"none",
)
@@ -74,11 +75,29 @@ class RuntimeError_(ValueError):
# --- the spool ------------------------------------------------------------------------
def _read_entry(path: str) -> dict:
def _open_kind_dir(directory: str) -> int:
"""users/ or listeners/, not followed if a member of the group-writable spool swapped
in a symlink to another directory."""
return os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
def _awg_capacity(listener: dict) -> int | None:
"""How many users an AmneziaWG listener's subnet holds, as awg_inbound.py hands out
addresses: the network, this host (offset 1) and the broadcast are not theirs. None
when the spec does not say."""
try:
network = ipaddress.ip_network(listener["amneziaWg"]["subnet"], strict=False)
except (KeyError, TypeError, ValueError):
return None
last = network.num_addresses - (1 if network.prefixlen < 31 else 0)
return max(last - 2, 0)
def _read_entry(path: str, dir_fd: int | None = None) -> dict:
"""One spool file, as root reads it: a regular file only, never through a symlink,
which would hand over any file root can read, nor a FIFO, which would hang the start."""
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=dir_fd)
except OSError as exc:
raise RuntimeError_(f"cannot read {path}: {exc.strerror}") from None
with os.fdopen(fd, "rb") as handle:
@@ -90,7 +109,7 @@ def _read_entry(path: str) -> dict:
data = handle.read(MAX_ENTRY_BYTES + 1)
try:
value = json.loads(data.decode("utf-8"))
except (UnicodeDecodeError, ValueError) as exc:
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
raise RuntimeError_(f"{path} is not valid JSON: {exc}") from None
if not isinstance(value, dict):
raise RuntimeError_(f"{path} must hold a JSON object")
@@ -99,12 +118,24 @@ def _read_entry(path: str) -> dict:
def _entries(directory: str, warnings: list[str], what: str) -> dict[str, dict]:
try:
names = sorted(os.listdir(directory))
dir_fd = _open_kind_dir(directory)
except FileNotFoundError:
return {}
except OSError as exc:
warnings.append(f"cannot list {directory}: {exc.strerror}")
return {}
try:
return _entries_at(dir_fd, directory, warnings, what)
finally:
os.close(dir_fd)
def _entries_at(dir_fd: int, directory: str, warnings: list[str], what: str) -> dict[str, dict]:
try:
names = sorted(os.listdir(dir_fd))
except OSError as exc:
warnings.append(f"cannot list {directory}: {exc.strerror}")
return {}
entries = {}
for file_name in names:
if file_name.startswith(".") or not file_name.endswith(".json"):
@@ -114,7 +145,7 @@ def _entries(directory: str, warnings: list[str], what: str) -> dict[str, dict]:
warnings.append(f"ignoring runtime {what} '{name}': not a valid name")
continue
try:
entries[name] = _read_entry(os.path.join(directory, file_name))
entries[name] = _read_entry(file_name, dir_fd)
except RuntimeError_ as exc:
warnings.append(f"ignoring runtime {what} '{name}': {exc}")
return entries
@@ -141,25 +172,71 @@ def write_entry(spool: str, kind: str, name: str, entry: dict) -> None:
os.makedirs(directory, exist_ok=True)
finally:
os.umask(old)
path = os.path.join(directory, f"{name}.json")
# A new file of its own, never a fixed name: a symlink a member left there would take
# the write of this tool run as root wherever it points.
fd, tmp = tempfile.mkstemp(prefix=f".{name}.json.", dir=directory)
dir_fd = _open_kind_dir(directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n")
os.chmod(tmp, 0o640)
os.replace(tmp, path)
except BaseException:
# A new file of its own, never a fixed name: a symlink a member left there would
# take the write of this tool run as root wherever it points.
while True:
tmp = f".{name}.json.{secrets.token_hex(8)}"
try:
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=dir_fd)
break
except FileExistsError:
continue
try:
os.unlink(tmp)
except OSError:
pass
raise
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n")
os.fchmod(handle.fileno(), 0o640)
os.replace(tmp, f"{name}.json", src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
except BaseException:
try:
os.unlink(tmp, dir_fd=dir_fd)
except OSError:
pass
raise
finally:
os.close(dir_fd)
def remove_entry(spool: str, kind: str, name: str) -> None:
os.unlink(os.path.join(spool, kind, f"{name}.json"))
dir_fd = _open_kind_dir(os.path.join(spool, kind))
try:
os.unlink(f"{name}.json", dir_fd=dir_fd)
finally:
os.close(dir_fd)
LOCK_WAIT_SECONDS = 15
def lock_spool(spool: str, lock: str | None = None) -> int:
"""Held across a command's read, check and write, so `users rm` racing `bind` cannot
write the user back. lock: a file root made outside the spool, where no member can swap it."""
# Read-only, which flock needs no more than: a 0640 one still serves the group.
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
try:
if not lock:
raise FileNotFoundError
path = lock
fd = os.open(path, flags)
except FileNotFoundError:
# Not made yet (tmpfiles has not run since the switch): the spool's own.
path = os.path.join(spool, ".lock")
fd = os.open(path, flags | os.O_CREAT, 0o660)
if not stat.S_ISREG(os.fstat(fd).st_mode):
os.close(fd)
raise RuntimeError_(f"{path} is not a regular file")
# A member holding it for good must not hang every other change.
deadline = time.monotonic() + LOCK_WAIT_SECONDS
while True:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return fd
except BlockingIOError:
if time.monotonic() >= deadline:
os.close(fd)
raise RuntimeError_(f"{spool} is locked by another change; try again") from None
time.sleep(0.1)
# --- the shape of entries -------------------------------------------------------------
@@ -170,7 +247,8 @@ def _is_port(value) -> bool:
def _nonspace(value) -> bool:
return isinstance(value, str) and value != "" and not re.search(r"\s", value)
# No control characters either: a NUL is no whitespace, and no value XRay can use.
return isinstance(value, str) and value != "" and not re.search(r"[\s\x00-\x1f\x7f]", value)
def _strings(value) -> bool:
@@ -197,6 +275,25 @@ def _is_alpn(value) -> bool:
return isinstance(value, list) and all(item in ALPNS for item in value)
def _is_x25519_key(value) -> bool:
"""A REALITY key as XRay reads it: 32 bytes, unpadded URL-safe base64. Anything else
and XRay refuses the whole configuration, the declared listeners with it."""
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", value):
return False
try:
return len(base64.urlsafe_b64decode(value + "=")) == 32
except ValueError:
return False
def _ss2022_key_ok(value, method) -> bool:
"""A Shadowsocks 2022 key: standard base64 of exactly the method's key length."""
try:
return len(base64.b64decode(value, validate=True)) == SS2022_KEY_BYTES[method]
except (TypeError, ValueError):
return False
# What a runtime listener's JSON may set, and how. The file fields of the option are not
# here: a runtime listener names nothing on disk. Nor raw JSON, AmneziaWG or port hopping,
# which need more than XRay (interfaces, nftables) and are built in Nix.
@@ -216,7 +313,9 @@ LISTENER_SCHEMA = {
"serverPassword": _nullable(_nonspace),
"transport": {
"type": _one_of(*TRANSPORTS),
"path": _is_str,
# XRay refuses its whole config over a fallback path not starting with "/", and a
# fallback to this listener takes its path.
"path": lambda value: isinstance(value, str) and (value == "" or value.startswith("/")),
"host": _nullable(_nonspace),
"mode": _nullable(_one_of(*XHTTP_MODES)),
"serviceName": _is_str,
@@ -230,11 +329,15 @@ LISTENER_SCHEMA = {
},
"reality": {
"enable": _is_bool,
"dest": _nonspace,
# Not "/path" or "@name": XRay takes those for a Unix socket, which a runtime listener
# never names.
"dest": lambda value: _nonspace(value) and not str(value).startswith(("/", "@")),
"serverNames": _strings,
"privateKey": _nullable(_nonspace),
"publicKey": _nullable(_nonspace),
"shortIds": lambda value: _strings(value) and all(re.fullmatch(r"[0-9a-fA-F]{0,16}", i) for i in value),
"privateKey": _nullable(_is_x25519_key),
"publicKey": _nullable(_is_x25519_key),
# Whole bytes: XRay refuses an odd number of hex digits.
# And at least one: XRay refuses an empty list, every listener with it.
"shortIds": lambda value: _strings(value) and bool(value) and all(re.fullmatch(r"(?:[0-9a-fA-F]{2}){0,8}", i) for i in value),
"xver": _one_of(0, 1, 2),
},
"fallbacks": "fallbacks",
@@ -250,7 +353,7 @@ LISTENER_SCHEMA = {
FALLBACK_SCHEMA = {
"name": _nullable(_nonspace),
"alpn": _nullable(_one_of("h2", "http/1.1")),
"path": _nullable(_is_str),
"path": _nullable(lambda value: isinstance(value, str) and (value == "" or value.startswith("/"))),
"dest": _nullable(lambda value: _is_port(value) or _nonspace(value)),
"listener": _nullable(lambda value: isinstance(value, str) and bool(NAME.fullmatch(value))),
"xver": _one_of(0, 1, 2),
@@ -378,6 +481,48 @@ def _loopback(address: str) -> bool:
return address.startswith("127.") or address in ("::1", "localhost")
def _internal_host(host: str) -> bool:
"""A host this server reaches but the internet should not: loopback, private,
link-local (cloud metadata), or any other address that is not globally routable."""
host = host.strip("[]").rstrip(".").lower()
if host == "localhost" or host.endswith(".localhost"):
return True
try:
address = ipaddress.ip_address(host)
except ValueError:
# inet_aton's forms (2130706433, 0x7f.1) that XRay's resolver may still take.
try:
address = ipaddress.ip_address(socket.inet_aton(host))
except (OSError, ValueError): # ValueError: an embedded NUL
return False
if getattr(address, "ipv4_mapped", None):
address = address.ipv4_mapped
return not address.is_global
def _dest_host(dest: str) -> str:
"""The host of a REALITY dest: host:port, [v6]:port, or a bare port (loopback)."""
if dest.isascii() and dest.isdigit():
return "127.0.0.1"
if dest.startswith("["):
return dest[1:].split("]", 1)[0]
return dest.rsplit(":", 1)[0] if dest.count(":") == 1 else dest
def _dest_port(dest: str) -> int | None:
"""The port of a REALITY dest, as _dest_host splits it; None for a socket path."""
# ASCII digits only: str.isdigit takes "²", which int() refuses.
if dest.isascii() and dest.isdigit():
return int(dest)
if dest.startswith("[") and "]:" in dest:
port = dest.rsplit("]:", 1)[1]
elif dest.count(":") == 1:
port = dest.rsplit(":", 1)[1]
else:
return None
return int(port) if port.isascii() and port.isdigit() else None
# --- users ----------------------------------------------------------------------------
@@ -434,15 +579,29 @@ def new_user(order: int, listeners: list[str]) -> dict:
# --- listeners ------------------------------------------------------------------------
def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[str]:
def listener_problems(listener: dict, runtime: dict, share_links: bool, shared: dict | None = None) -> list[str]:
"""The declared listeners' assertions (service-assertions.nix), for a runtime listener
filled in with the defaults and its users, plus the fences of inbounds.runtime."""
filled in with the defaults and its users, plus the fences of inbounds.runtime.
shared: {"addresses", "ports"} its share links may name, the server's own (_share_fence)."""
problems = []
def need(condition: bool, message: str) -> None:
if not condition:
problems.append(message)
# Declared users' links carry their own credentials: pointing them at another host or a
# member's port would hand those over.
if shared is not None:
share_address = listener.get("shareAddress")
need(share_address is None or share_address in shared["addresses"],
f"shareAddress {json.dumps(share_address)} is neither inbounds.serverAddress nor a declared listener's")
share_port = listener.get("sharePort")
need(share_port is None or share_port == listener["port"] or share_port in shared["ports"],
f"sharePort {share_port} is neither the listener's port nor a declared listener's")
# Ahead of the declared listeners in a subscription, which clients often take first.
need(listener.get("order", 0) >= 0, "order must not be negative")
kind = listener["type"]
transport = listener["transport"]
tls = listener["tls"]
@@ -450,6 +609,13 @@ def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[
hysteria = listener["hysteria"]
users = listener["users"]
tls_terminated = tls["enable"] or kind in ("trojan", "hysteria2")
# A declared user's credentials (set in Nix) never cross the network in the clear; on
# loopback the listener is a fallback's target, behind its front's TLS.
loopback = _is_ip(listener["listen"]) and ipaddress.ip_address(listener["listen"]).is_loopback
if kind in ("vless", "socks", "http") and not tls["enable"] and not reality["enable"] and not loopback:
for user in users:
need(bool(user.get("runtime")),
f"declared user '{user['name']}' would send its credentials in the clear: give the listener tls or reality")
need(_port_allowed(listener["port"], runtime.get("ports") or []),
f"port {listener['port']} is not in inbounds.runtime.ports")
@@ -464,6 +630,17 @@ def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[
"shadowsocks with more than one user needs a 2022-blake3-aes-* method")
need(not multi_ss or listener.get("serverPassword") is not None,
"shadowsocks with more than one user needs serverPassword")
# A declared user keeps the password it has: on a 2022 method it is the key, and one of
# another length fails XRay's whole start. Runtime users get theirs derived (_user_for).
if kind == "shadowsocks" and listener.get("method") in SS2022_KEY_BYTES:
for user in users:
password = _user_for(user, listener).get("password")
need(not isinstance(password, str) or _ss2022_key_ok(password, listener["method"]),
f"user '{user['name']}' has a password that is no {listener['method']} key")
server_password = listener.get("serverPassword")
need(server_password is None or kind != "shadowsocks" or listener["method"] not in SS2022_KEY_BYTES
or _ss2022_key_ok(server_password, listener["method"]),
f"serverPassword must be base64 of {SS2022_KEY_BYTES.get(listener.get('method'))} bytes for {listener.get('method')}")
need(not reality["enable"] or transport["type"] in ("raw", "xhttp", "grpc"),
"reality only runs over the raw, xhttp and grpc transports")
need(not share_links or not reality["enable"] or kind in ("vless", "trojan"),
@@ -489,6 +666,32 @@ def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[
"hysteria2 takes no reality or transport")
need(hysteria.get("masquerade") is None or kind == "hysteria2",
"hysteria.masquerade is for hysteria2 listeners only")
# XRay dials both for anyone, past routing: not this host or its LAN (a local decoy is
# declared). Names are not resolved, so port 443 keeps one that resolves inside to TLS.
if reality["enable"]:
dest = str(reality["dest"])
declared = dest in [str(item) for item in runtime.get("fallbackDests") or []]
need(declared or not _internal_host(_dest_host(dest)),
f"reality.dest {json.dumps(dest)} is on this host or a private network, and not in inbounds.runtime.fallbackDests")
need(declared or _dest_port(dest) == 443,
f"reality.dest {json.dumps(dest)} must be a site's port 443, unless it is in inbounds.runtime.fallbackDests")
masquerade = hysteria.get("masquerade")
if masquerade is not None:
try:
parts = urllib.parse.urlsplit(masquerade)
host = parts.hostname
port = parts.port
except ValueError:
parts, host, port = None, None, None
need(parts is not None and parts.scheme in ("http", "https") and bool(host) and not _internal_host(host),
f"hysteria.masquerade {json.dumps(masquerade)} must be an http(s) URL of a public site")
# As for reality.dest: a name that resolves inside passes the check above, so the
# port stays a web one, not whatever service listens there.
if parts is not None and host:
host_port = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
declared = host_port in [str(item) for item in runtime.get("fallbackDests") or []]
need(declared or port in (None, 80, 443),
f"hysteria.masquerade {json.dumps(masquerade)} must use port 80 or 443, unless {host_port} is in inbounds.runtime.fallbackDests")
need(not hysteria["salamander"]["enable"] or kind == "hysteria2",
"hysteria.salamander is for hysteria2 listeners only")
need(not listener["acceptProxyProtocol"] or not _udp_only(listener),
@@ -711,6 +914,11 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
problem("user", name, f"cannot be on '{tag}': {why}")
continue
candidate = users[name]
capacity = _awg_capacity(target) if target["type"] == "amneziawg" else None
if capacity is not None and len(target["users"]) >= capacity:
# awg_inbound.py's allocation would fail, and with it every listener's start.
problem("user", name, f"cannot be on '{tag}': its subnet has no free address")
continue
if tag in declared and target["type"] == "shadowsocks" and target["users"]:
if not target["method"].startswith("2022-blake3-aes-") or (
target.get("serverPassword") is None and target.get("serverPasswordFile") is None
@@ -721,10 +929,17 @@ def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dic
# Ports, fences and the declared assertions, on the listeners as they now stand.
declared_ports = {listener["port"] for listener in merged["listeners"]}
shared = {
"addresses": {a for a in [spec.get("serverAddress")] + [l.get("shareAddress") for l in merged["listeners"]] if a},
"ports": declared_ports | {l["sharePort"] for l in merged["listeners"] if l.get("sharePort")},
}
used_ports: set[int] = set()
for tag in sorted(runtime_listeners, key=lambda t: (runtime_listeners[t]["order"], t)):
listener = runtime_listeners[tag]
why = listener_problems(listener, runtime, share_links)
try:
why = listener_problems(listener, runtime, share_links, shared)
except Exception as exc: # noqa: BLE001 - this one listener goes, not every inbound
why = [f"cannot be checked: {exc}"]
if listener["port"] in declared_ports or listener["port"] in used_ports:
why.append(f"port {listener['port']} is taken by another listener")
if not why and check_ports and not port_free(listener["listen"], listener["port"], _protocols(listener)):
@@ -1273,7 +1488,12 @@ def main(argv: list[str] | None = None) -> int:
if changes and not all(os.access(path, os.W_OK | os.X_OK) for path in writable):
print(f"Cannot write {spool}", file=sys.stderr)
return 77
# Read before the lock: someone typing a listener in must not hold every other change.
piped = sys.stdin.read() if args.command == "add" and getattr(args, "source", "") == "-" else None
lock = None
try:
if changes:
lock = lock_spool(spool, (spec.get("runtime") or {}).get("lock"))
if args.command == "users" and args.verb in (None, "list"):
state, warnings = load_spool(spool)
for warning in warnings:
@@ -1300,7 +1520,7 @@ def main(argv: list[str] | None = None) -> int:
if args.source in TYPES:
entry = listener_from_flags(args.source, args)
else:
text = sys.stdin.read() if args.source == "-" else open(args.source, encoding="utf-8").read()
text = piped if args.source == "-" else open(args.source, encoding="utf-8").read()
try:
entry = json.loads(text)
except ValueError as exc:
@@ -1342,6 +1562,9 @@ def main(argv: list[str] | None = None) -> int:
except OSError as exc:
print(f"{exc.filename or ''}: {exc.strerror}", file=sys.stderr)
return 1
finally:
if lock is not None:
os.close(lock)
return 0
+60 -13
View File
@@ -6,11 +6,15 @@ on 127.0.0.53 has a loopback source, which the kernel never routes out of a real
With no route in the interface's table the mark meets an unreachable rule, so a lookup fails
rather than leaving any other way.
Per-app TUN and TProxy use it too, a port per mark (--listen): there a lookup of a resolver on
loopback is sent on into the route, where the backend's DNS hijack answers it.
"""
import argparse
import asyncio
import os
import re
import socket
import struct
import sys
@@ -19,11 +23,18 @@ TIMEOUT = 4.0
MAX_MESSAGE = 65535
# The source address of the queries sent on (--bind): on a TProxy route's local route the
# kernel would pick the destination as the source, and the reply would not come back.
BIND: dict[int, str] = {}
def upstream_socket(server: str, kind: int, mark: int) -> socket.socket:
family = socket.AF_INET6 if ":" in server else socket.AF_INET
sock = socket.socket(family, kind)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_MARK, mark)
if family in BIND:
sock.bind((BIND[family], 0))
sock.setblocking(False)
except OSError:
sock.close()
@@ -131,28 +142,64 @@ def notify_ready():
sock.sendall(b"READY=1")
async def serve(port: int, mark: int, servers: list[str]):
def listen_spec(item: str) -> tuple[int, int]:
"""PORT:MARK, ASCII digits only (str.isdigit also takes "²", which int() then refuses)."""
match = re.fullmatch(r"([0-9]+):([0-9]+)", item)
if not match or not 1 <= int(match[1]) <= 65535 or int(match[2]) >= 2**32:
raise argparse.ArgumentTypeError(f"{item!r}: not PORT:MARK (port 1-65535, a 32-bit mark)")
return int(match[1]), int(match[2])
async def serve(listeners: list[tuple[int, int]], servers: list[str]):
loop = asyncio.get_running_loop()
for host in ("127.0.0.1", "::1"):
try:
await loop.create_datagram_endpoint(lambda: UdpListener(servers, mark), local_addr=(host, port))
await asyncio.start_server(tcp_handler(servers, mark), host, port)
except OSError as exc:
# IPv6 may be off.
if host == "127.0.0.1":
raise
print(f"per-app-dns: not on [{host}]:{port}: {exc}", file=sys.stderr)
for port, mark in listeners:
for host in ("127.0.0.1", "::1"):
try:
await loop.create_datagram_endpoint(
lambda mark=mark: UdpListener(servers, mark), local_addr=(host, port)
)
await asyncio.start_server(tcp_handler(servers, mark), host, port)
except OSError as exc:
# IPv6 may be off.
if host == "127.0.0.1":
raise
print(f"per-app-dns: not on [{host}]:{port}: {exc}", file=sys.stderr)
notify_ready()
await asyncio.Event().wait()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, required=True)
parser.add_argument("--mark", type=int, required=True)
parser.add_argument("--port", type=int)
parser.add_argument("--mark", type=int)
parser.add_argument(
"--listen",
action="append",
default=[],
type=listen_spec,
metavar="PORT:MARK",
help="another port, whose lookups are sent on with this mark; repeatable",
)
parser.add_argument(
"--bind",
action="append",
default=[],
metavar="ADDRESS",
help="the source address of the queries sent on, one per family",
)
parser.add_argument("servers", nargs="*", help="resolver addresses, asked in order")
args = parser.parse_args()
asyncio.run(serve(args.port, args.mark, args.servers))
for address in args.bind:
BIND[socket.AF_INET6 if ":" in address else socket.AF_INET] = address
listeners = []
if args.port is not None or args.mark is not None:
if args.port is None or args.mark is None:
parser.error("--port and --mark go together")
listeners.append((args.port, args.mark))
listeners.extend(args.listen)
if not listeners:
parser.error("nothing to listen on: --port and --mark, or --listen")
asyncio.run(serve(listeners, args.servers))
return 0
+8 -1
View File
@@ -435,7 +435,8 @@ def build_share_link(
params["flow"] = listener["flow"]
_apply_variant(params, variant, listener_type)
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}"
# A trojan password may hold @, #, ? or %; a vless uuid comes through unchanged.
return f"{listener_type}://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
def render_amneziawg_inbound(listener: dict) -> dict:
@@ -568,6 +569,12 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
for listener in spec["listeners"]:
onion = onion_address if listener["tag"] in spec.get("onionListeners", []) else ""
rendered = build_listener(listener, server_address, spec.get("shareLinks", True), onion)
sniffing = rendered["inbound"].get("sniffing")
raw = listener.get("xrayJson") is not None or listener.get("jsonFile") is not None
if isinstance(sniffing, dict) and not raw and spec.get("sniffDomainsExcluded"):
# Names routing sends past the via (rules/proxy-inbounds.nix): matched on the
# address the client asked for only, never on what its handshake claims.
sniffing["domainsExcluded"] = list(spec["sniffDomainsExcluded"])
inbounds.append(rendered["inbound"])
variants = [(rendered["links"], {})]
for name, variant_links in rendered.get("variantLinks") or []:
+179 -14
View File
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
import base64
import ipaddress
import re
import socket
import sys
import urllib.parse
import urllib.request
@@ -56,6 +58,8 @@ def _xray_tls(tls: dict | None) -> tuple[str, dict]:
"XRay no longer supports tlsSettings.allowInsecure; "
"remove insecure=1 or use a supported certificate verification option"
)
if tls.get("certificate_sha256"):
settings["pinnedPeerCertSha256"] = tls["certificate_sha256"]
if tls.get("ech_config_list"):
settings["echConfigList"] = tls["ech_config_list"]
utls = tls.get("utls", {})
@@ -213,28 +217,109 @@ def build_outbound(
if backend not in {"sing-box", "xray"}:
raise ValueError(f"unsupported backend '{backend}'")
outbound = _parse_url(url, tag, backend)
return _finish_outbound(_parse_url(url, tag, backend), routing_mark, backend)
def _finish_outbound(outbound: dict, routing_mark: int | None, backend: str) -> dict:
if backend == "xray":
return render_xray_outbound(outbound, routing_mark)
if routing_mark is not None:
if backend == "xray":
return render_xray_outbound(outbound, routing_mark)
outbound["routing_mark"] = routing_mark
elif backend == "xray":
return render_xray_outbound(outbound)
return outbound
class RefusedServer(ValueError):
"""A subscription entry whose server is this host or its link."""
# Opt-in per subscription (allowPrivateServers): a provider's servers are not on the LAN.
_PRIVATE_NETWORKS = tuple(
ipaddress.ip_network(net)
for net in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "fc00::/7")
)
def _server_address(host: str) -> "ipaddress.IPv4Address | ipaddress.IPv6Address | None":
try:
address = ipaddress.ip_address(host)
except ValueError:
# inet_aton's forms (2130706433, 0x7f.1, 127.1), which a resolver may still take.
if not re.fullmatch(r"[0-9A-Fa-fXx.]+", host):
return None
try:
address = ipaddress.IPv4Address(socket.inet_aton(host))
except OSError:
return None
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
return address.ipv4_mapped
return address
def _check_address(host, address, allow_private: bool) -> None:
if address.is_loopback or address.is_unspecified or address in ipaddress.ip_network("0.0.0.0/8"):
raise RefusedServer(f"server {host} is this host")
if address.is_link_local or address.is_multicast:
raise RefusedServer(f"server {host} is a link-local or multicast address")
if not allow_private and any(address in net for net in _PRIVATE_NETWORKS):
raise RefusedServer(f"server {host} is a private address (see allowPrivateServers)")
def check_server(host, allow_private: bool = False) -> None:
"""Raises RefusedServer for a literal address (or localhost) on this host, its link, or,
unless allow_private, a private network: urltest would pick a loopback entry as the exit."""
if not isinstance(host, str):
return
name = host.strip().rstrip(".").lower()
# The backends dial "[127.0.0.1]" as 127.0.0.1: judged unbracketed, or it is no
# address and no name either, and passes unchecked.
if name.startswith("[") and name.endswith("]"):
name = name[1:-1].rstrip(".")
if name == "localhost" or name.endswith(".localhost"):
raise RefusedServer(f"server {host} is this host")
address = _server_address(name)
if address is not None:
_check_address(host, address, allow_private)
# A subscription is a list of share links; the biggest real ones are tens of KiB.
# Read runs as root at service start, so a server that never stops sending must not
# take the whole proxy down with it.
MAX_SUBSCRIPTION_BYTES = 8 * 1024 * 1024
class FetchError(ValueError):
"""A fetch refused or cut short here: its message never quotes the URL, which is a secret."""
def _nearness(host) -> int:
"""How close to this host a URL's host is: 2 for this host or its link, 1 for a private
network, 0 for anywhere else or a name other than localhost."""
if not isinstance(host, str):
return 0
name = host.strip().rstrip(".").lower()
if name == "localhost" or name.endswith(".localhost"):
return 2
address = _server_address(name)
if address is None:
return 0
if address.is_loopback or address.is_unspecified or address.is_link_local or address in ipaddress.ip_network("0.0.0.0/8"):
return 2
return 1 if any(address in net for net in _PRIVATE_NETWORKS) else 0
class _HttpOnlyRedirects(urllib.request.HTTPRedirectHandler):
"""Redirects stay on http and https: urllib's own also follows one to ftp:."""
"""Redirects stay on http and https (urllib's own also follows ftp:), never downgrade
https, and never point nearer to this host (loopback, LAN, metadata) than their source."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
if urllib.parse.urlsplit(newurl).scheme not in ("http", "https"):
raise ValueError("subscription redirected off http:// and https://")
target = urllib.parse.urlsplit(newurl)
scheme = target.scheme
if scheme not in ("http", "https"):
raise FetchError("subscription redirected off http:// and https://")
if scheme == "http" and urllib.parse.urlsplit(req.full_url).scheme == "https":
raise FetchError("subscription redirected from https:// to http://")
if _nearness(target.hostname) > _nearness(urllib.parse.urlsplit(req.full_url).hostname):
raise FetchError("subscription redirected to this host or a private network")
return super().redirect_request(req, fp, code, msg, headers, newurl)
@@ -243,7 +328,7 @@ def fetch_raw(url: str) -> bytes:
# reaches it from a group-writable spool, so only the two a subscription is
# ever served over, redirects included.
if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
raise ValueError("subscription URL must be http:// or https://")
raise FetchError("subscription URL must be http:// or https://")
request = urllib.request.Request(
url,
headers={"User-Agent": "v2rayN/6.0"},
@@ -252,7 +337,7 @@ def fetch_raw(url: str) -> bytes:
with opener.open(request, timeout=30) as response:
data = response.read(MAX_SUBSCRIPTION_BYTES + 1)
if len(data) > MAX_SUBSCRIPTION_BYTES:
raise ValueError(f"subscription is larger than {MAX_SUBSCRIPTION_BYTES} bytes")
raise FetchError(f"subscription is larger than {MAX_SUBSCRIPTION_BYTES} bytes")
return data
@@ -308,6 +393,48 @@ def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str
return _unique_tag(make_tag(tag_prefix, _remark_from_line(line), index), seen_tags)
# Real subscriptions hold hundreds; 8 MiB of short lines would be minutes of start script
# and gigabytes of backend config.
MAX_SUBSCRIPTION_ENTRIES = 5000
def _ech_dns_server(value) -> str | None:
"""The resolver XRay asks for the ECH config, when echConfigList names one instead of
holding the config: "[name+]udp://1.1.1.1:53", "https://dns.example/dns-query", "h2c://…"."""
if not isinstance(value, str) or "://" not in value:
return None
url = value.split("+", 1)[1] if "+" in value.split("://", 1)[0] else value
try:
host = urllib.parse.urlsplit(url).hostname
except ValueError:
host = None
# Unparsable: the whole value, which check_server passes unless it is an address itself.
return host or value
def _dialed_servers(outbound: dict) -> list:
"""Every address the outbound dials: its server, any "address" (any case) in an xhttp
extra's downloadSettings, and the resolver an ECH config is fetched from."""
servers = [outbound.get("server")]
tls = outbound.get("tls")
if isinstance(tls, dict) and (ech := _ech_dns_server(tls.get("ech_config_list"))):
servers.append(ech)
transport = outbound.get("transport")
stack = [transport.get("extra")] if isinstance(transport, dict) else []
while stack:
item = stack.pop()
if isinstance(item, dict):
for key, value in item.items():
if str(key).lower() == "address":
servers.append(value if isinstance(value, str) else str(value))
elif str(key).lower() == "echconfiglist" and (ech := _ech_dns_server(value)):
servers.append(ech)
stack.append(value)
elif isinstance(item, list):
stack.extend(item)
return servers
def _walk_subscription(
lines: list[str],
tag_prefix: str,
@@ -315,10 +442,13 @@ def _walk_subscription(
backends: list[str],
links: dict[str, str] | None,
keep,
allow_private: bool = False,
allow_insecure: bool = False,
) -> None:
"""Parses every supported line, trying each backend in turn, and hands the result to keep.
A line no backend accepts is reported with every backend's complaint and skipped.
A line no backend accepts is reported with every backend's complaint and skipped, as is
one whose server check_server refuses.
"""
seen_tags: set[str] = set()
@@ -326,12 +456,29 @@ def _walk_subscription(
scheme = detect_scheme(line)
if scheme not in PARSERS:
continue
if len(seen_tags) >= MAX_SUBSCRIPTION_ENTRIES:
print(
f"warning: subscription has more than {MAX_SUBSCRIPTION_ENTRIES} entries: the rest are left out",
file=sys.stderr,
)
break
tag = _subscription_tag(line, tag_prefix, index, seen_tags)
errors = []
for backend in backends:
try:
outbound = build_outbound(line, tag, routing_mark, backend)
outbound = _parse_url(line, tag, backend)
for server in _dialed_servers(outbound):
check_server(server, allow_private)
# Whoever serves the list could otherwise have the tunnel trust any certificate:
# anyone on the way stands in for the server then. Per backend: XRay may pin it.
if not allow_insecure and isinstance(outbound.get("tls"), dict) and outbound["tls"].get("insecure"):
raise ValueError("it turns certificate checks off (insecure=1; see allowInsecure)")
outbound = _finish_outbound(outbound, routing_mark, backend)
except RefusedServer as exc:
# The same server whichever backend reads the line.
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
break
except Exception as exc:
errors.append(f"{backend}: {exc}" if len(backends) > 1 else str(exc))
continue
@@ -354,17 +501,33 @@ def parse_subscription(
routing_mark: int | None,
backend: str = "sing-box",
links: dict[str, str] | None = None,
allow_private: bool = False,
allow_insecure: bool = False,
) -> list[dict]:
"""links, when given, collects tag -> the line it came from, to share it back."""
if backend not in {"sing-box", "xray"}:
raise ValueError(f"unsupported backend '{backend}'")
outbounds: list[dict] = []
_walk_subscription(
lines, tag_prefix, routing_mark, [backend], links, lambda _, ob: outbounds.append(ob)
lines,
tag_prefix,
routing_mark,
[backend],
links,
lambda _, ob: outbounds.append(ob),
allow_private,
allow_insecure,
)
return outbounds
def parse_hybrid_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None = None, links: dict[str, str] | None = None
lines: list[str],
tag_prefix: str,
routing_mark: int | None = None,
links: dict[str, str] | None = None,
allow_private: bool = False,
allow_insecure: bool = False,
) -> dict[str, list[dict]]:
"""Each line goes to whichever backend can dial it, sing-box first."""
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
@@ -375,5 +538,7 @@ def parse_hybrid_subscription(
["sing-box", "xray"],
links,
lambda backend, ob: outbounds["singBox" if backend == "sing-box" else "xray"].append(ob),
allow_private,
allow_insecure,
)
return outbounds
+293 -42
View File
@@ -2,7 +2,9 @@
import base64
import binascii
import ipaddress
import json
import re
import urllib.parse
SUPPORTED_VLESS_TRANSPORTS = {
@@ -17,11 +19,83 @@ SUPPORTED_VLESS_TRANSPORTS = {
"quic",
}
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | {
# XRay 26 removed the HTTP/2 and QUIC transports and refuses to start on them.
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS - {"h2", "http", "quic"} | {
"xhttp",
"splithttp",
}
# The rest of what a backend refuses to start on, so one bad subscription entry is
# skipped instead of taking every other outbound down with it (see _port below).
VLESS_FLOWS = {
"sing-box": {"", "xtls-rprx-vision"},
"xray": {"", "xtls-rprx-vision", "xtls-rprx-vision-udp443"},
}
SING_BOX_VMESS_SECURITY = {"auto", "none", "zero", "aes-128-cfb", "aes-128-gcm", "chacha20-poly1305"}
TUIC_CONGESTION_CONTROLS = {"cubic", "new_reno", "bbr"}
XHTTP_MODES = {"", "auto", "packet-up", "stream-up", "stream-one"}
SS2022_KEY_BYTES = {
"2022-blake3-aes-128-gcm": 16,
"2022-blake3-aes-256-gcm": 32,
"2022-blake3-chacha20-poly1305": 32,
}
SING_BOX_SS_METHODS = set(SS2022_KEY_BYTES) | {
"none",
"aes-128-gcm",
"aes-192-gcm",
"aes-256-gcm",
"chacha20-ietf-poly1305",
"xchacha20-ietf-poly1305",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"rc4-md5",
"chacha20-ietf",
"xchacha20",
}
# XRay lowercases these; its 2022 methods are matched as written.
XRAY_SS_METHODS = {
"aes-128-gcm",
"aes-256-gcm",
"chacha20-poly1305",
"chacha20-ietf-poly1305",
"xchacha20-poly1305",
"xchacha20-ietf-poly1305",
"aead_aes_128_gcm",
"aead_aes_256_gcm",
"aead_chacha20_poly1305",
"aead_xchacha20_poly1305",
}
UUID_RE = re.compile(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}|[0-9a-fA-F]{32}")
# REALITY's x25519 key, unpadded base64url; its short id, whole hex bytes, at most 8.
REALITY_PUBLIC_KEY_RE = re.compile(r"[A-Za-z0-9_-]{43}")
REALITY_SHORT_ID_RE = re.compile(r"(?:[0-9a-fA-F]{2}){0,8}")
# A path Go's url.Parse takes: no control characters, and % only as an escape. XRay ignores
# the parse error on spiderX and dies on the nil URL, taking every outbound with it.
REALITY_SPIDER_X_RE = re.compile(r"/(?:[^\x00-\x1f\x7f%]|%[0-9A-Fa-f]{2})*")
# hysteria2's pinSHA256: the certificate's SHA-256, hex, colons optional.
CERT_SHA256_RE = re.compile(r"[0-9A-Fa-f]{64}|[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){31}")
def _one_of(value, allowed: set, what: str):
if value not in allowed:
# repr: the value is the link's, escape sequences and all, and goes to a terminal.
raise ValueError(f"unsupported {what} {str(value)[:80]!r}")
return value
# sing-box takes any string as a VLESS/VMess id; XRay a UUID, or 1-30 characters it hashes into one.
def _user_id(value, backend: str, protocol: str) -> str:
if not isinstance(value, str):
raise ValueError(f"{protocol} id must be a string")
if backend == "xray" and not (UUID_RE.fullmatch(value) or 1 <= len(value) <= 30):
# Not quoted: the id is the credential, and the message reaches the journal.
raise ValueError(f"invalid {protocol} id ({len(value)} characters): XRay takes a UUID or 1-30 characters")
return value
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
@@ -41,7 +115,7 @@ def _port(value) -> int:
try:
port = int(value)
except (TypeError, ValueError):
raise ValueError(f"invalid port '{value}'") from None
raise ValueError(f"invalid port {str(value)[:20]!r}") from None
if not 1 <= port <= 65535:
raise ValueError(f"port {port} is out of range (1-65535)")
return port
@@ -70,6 +144,20 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
return userinfo, host, port, _qs(query)
def _all_keys(value) -> set[str]:
"""Every key anywhere in `value`, lowercased."""
found: set[str] = set()
stack = [value]
while stack:
item = stack.pop()
if isinstance(item, dict):
found.update(str(key).lower() for key in item)
stack.extend(item.values())
elif isinstance(item, list):
stack.extend(item)
return found
def local_file_keys(value) -> list[str]:
"""The keys anywhere in `value` that point a backend at a local file or program.
@@ -77,35 +165,55 @@ def local_file_keys(value) -> list[str]:
xhttp's extra carries a whole streamSettings (downloadSettings), where
certificateFile is a file XRay reads and masterKeyLog one it writes. The start
script's localFileKeysJq applies the same rule to runtime JSON outbounds.
Any non-ASCII key counts too: Go's JSON folds case, reading "maſterKeyLog" as masterKeyLog.
"""
found: set[str] = set()
return sorted(
k
for k in _all_keys(value)
if not k.isascii()
or k.endswith(("file", "directory"))
or (k.endswith("path") and k != "path")
or k in ("masterkeylog", "torrc", "extra_args")
)
# The same streamSettings could also set the socket's mark or interface, or chain
# through another outbound: a subscription would steer around proxy-suite's own
# routing (the loop-avoiding mark, a loopback hop). These go; other socket options stay.
SOCKET_KEYS = {"customsockopt", "dialerproxy", "interface", "mark", "tproxy"}
def _strip_socket_keys(value) -> None:
stack = [value]
while stack:
item = stack.pop()
if isinstance(item, dict):
for key, child in item.items():
k = str(key).lower()
if (
k.endswith(("file", "directory"))
or (k.endswith("path") and k != "path")
or k in ("masterkeylog", "torrc", "extra_args")
):
found.add(k)
stack.append(child)
for key in [k for k in item if str(k).lower() in SOCKET_KEYS]:
del item[key]
stack.extend(item.values())
elif isinstance(item, list):
stack.extend(item)
return sorted(found)
def _refuse_constant(value: str):
raise ValueError(f"{value} is not JSON")
def _parse_json_param(value: str, name: str) -> dict:
try:
parsed = json.loads(value)
except json.JSONDecodeError as exc:
# NaN and Infinity: Python takes them, the JSON written for the backends cannot hold them.
parsed = json.loads(value, parse_constant=_refuse_constant)
except ValueError as exc:
raise ValueError(f"invalid {name} JSON: {exc}") from exc
if not isinstance(parsed, dict):
raise ValueError(f"invalid {name} JSON: expected object")
if unsafe := local_file_keys(parsed):
raise ValueError(f"{name} JSON names local files: {', '.join(unsafe)}")
_strip_socket_keys(parsed)
# XRay 26 refuses its whole configuration over a removed setting: this entry goes instead.
if "allowinsecure" in _all_keys(parsed):
raise ValueError(f"{name} JSON sets allowInsecure, which XRay no longer accepts")
return parsed
@@ -156,7 +264,7 @@ def _mk_transport(
}
if host_header:
transport["host"] = host_header
if mode:
if _one_of(mode, XHTTP_MODES, "xhttp mode"):
transport["mode"] = mode
if extra:
transport["extra"] = _parse_json_param(extra, "xhttp extra")
@@ -189,7 +297,7 @@ def _require(params: dict, name: str, security: str) -> str:
# sing-box's uTLS build refuses to start on a fingerprint it does not know, so
# one bad share link would otherwise take the whole config down with it. XRay's
# set is larger (it has "unsafe"), so only an explicitly-XRay entry skips this.
# set is larger (it has "unsafe"), so an XRay entry is checked against its own.
SING_BOX_FINGERPRINTS = {
"chrome",
"firefox",
@@ -202,6 +310,34 @@ SING_BOX_FINGERPRINTS = {
"random",
"randomized",
}
# XRay's own names (transport/internet/tls), matched lowercased. REALITY refuses
# "unsafe" and "hellogolang" on top.
XRAY_FINGERPRINTS = SING_BOX_FINGERPRINTS | {
"randomizednoalpn",
"unsafe",
*(
"hello" + name
for name in (
"firefox_120 firefox_148 chrome_120 chrome_131 chrome_133 ios_13 ios_14 edge_106 "
"safari_26_3 360_11_0 qq_11_1 golang randomized randomizedalpn randomizednoalpn "
"firefox_auto firefox_55 firefox_56 firefox_63 firefox_65 firefox_99 firefox_102 "
"firefox_105 chrome_auto chrome_58 chrome_62 chrome_70 chrome_72 chrome_83 chrome_87 "
"chrome_96 chrome_100 chrome_102 chrome_106_shuffle ios_auto ios_11_1 ios_12_1 "
"android_11_okhttp edge_85 edge_auto safari_16_0 safari_auto 360_auto 360_7_5 "
"qq_auto chrome_100_psk chrome_112_psk_shuf chrome_114_padding_psk_shuf "
"chrome_115_pq chrome_115_pq_psk chrome_120_pq"
).split()
),
}
def _check_fingerprint(fp: str, backend: str, reality: bool = False) -> str:
if backend != "xray":
if fp not in SING_BOX_FINGERPRINTS:
raise ValueError(f"unsupported uTLS fingerprint '{fp}': sing-box would refuse to start")
elif fp.lower() not in XRAY_FINGERPRINTS or (reality and fp.lower() in ("unsafe", "hellogolang")):
raise ValueError(f"unsupported uTLS fingerprint '{fp}': XRay would refuse to start")
return fp
# Panels write alpn either as "h2,http/1.1" or as a JSON list; str() on the list
@@ -219,11 +355,7 @@ def _mk_tls(
) -> dict:
tls: dict = {"enabled": True, "server_name": server_name}
if fp:
if backend != "xray" and fp not in SING_BOX_FINGERPRINTS:
raise ValueError(
f"unsupported uTLS fingerprint '{fp}': sing-box would refuse to start"
)
tls["utls"] = {"enabled": True, "fingerprint": fp}
tls["utls"] = {"enabled": True, "fingerprint": _check_fingerprint(fp, backend)}
if alpn:
tls["alpn"] = _alpn(alpn)
return tls
@@ -247,6 +379,35 @@ def _set_auth(ob: dict, userinfo: str) -> None:
ob["password"] = password
# XRay's GetPrivateIPMatcher and GetPrivateDomainMatcher (common/geodata/consts.go): the
# only servers it lets VLESS reach in the clear.
_XRAY_PRIVATE_NETWORKS = tuple(
ipaddress.ip_network(net)
for net in (
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16",
"172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16",
"198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/3",
"::/127", "fc00::/7", "fe80::/10", "ff00::/8",
)
)
_XRAY_PRIVATE_SUFFIXES = (
"lan", "localdomain", "example", "invalid", "localhost", "test", "local", "home.arpa", "internal",
)
def _xray_wants_transport_security(host: str) -> bool:
try:
address = ipaddress.ip_address(host)
except ValueError:
domain = host.lower().rstrip(".")
if re.fullmatch(r"[a-z]([a-z0-9-]{0,61}[a-z0-9])?", domain):
return False
return not any(domain == s or domain.endswith("." + s) for s in _XRAY_PRIVATE_SUFFIXES)
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
address = address.ipv4_mapped
return not any(address in net for net in _XRAY_PRIVATE_NETWORKS if net.version == address.version)
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
userinfo, host, port, params = _parse_url_parts(url, "vless")
security = _param(params, "security", "none")
@@ -266,22 +427,27 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
"tag": tag,
"server": host,
"server_port": _port(port),
"uuid": userinfo,
"uuid": _user_id(userinfo, backend, "VLESS"),
"packet_encoding": "xudp",
}
if security == "reality":
ob["tls"] = _mk_tls(
_param(params, "sni", host),
fp=_param(params, "fp", "chrome"),
backend=backend,
)
fp = _check_fingerprint(_param(params, "fp", "chrome"), backend, reality=True)
ob["tls"] = _mk_tls(_param(params, "sni", host), fp=fp, backend=backend)
public_key = _require(params, "pbk", "reality")
if not REALITY_PUBLIC_KEY_RE.fullmatch(public_key):
raise ValueError(f"invalid reality pbk '{public_key}': expected a 43-character base64url key")
short_id = params.get("sid", "")
if not REALITY_SHORT_ID_RE.fullmatch(short_id):
raise ValueError(f"invalid reality sid '{short_id}': expected up to 16 hex digits, in pairs")
ob["tls"]["reality"] = {
"enabled": True,
"public_key": _require(params, "pbk", "reality"),
"short_id": params.get("sid", ""),
"public_key": public_key,
"short_id": short_id,
}
if backend == "xray" and params.get("spx"):
if not REALITY_SPIDER_X_RE.fullmatch(params["spx"]):
raise ValueError(f"invalid reality spx {params['spx']!r}: XRay wants a URL path")
ob["tls"]["reality"]["spider_x"] = params["spx"]
elif security == "tls":
ob["tls"] = _mk_tls(
@@ -293,6 +459,9 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
if backend == "xray" and "ech" in params:
ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"])
if backend == "xray" and "tls" not in ob and _xray_wants_transport_security(host):
raise ValueError("XRay refuses VLESS without TLS or REALITY to a public server")
tr = _mk_transport(
normalized_transport,
path=_param(params, "path", "/"),
@@ -306,12 +475,24 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
ob["transport"] = tr
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
if _one_of(flow, VLESS_FLOWS[backend], f"{backend} VLESS flow"):
ob["flow"] = flow
return ob
def _alter_id(value) -> int:
"""VMess alterId as the backends take it: an int a subscription cannot make so large
(or fractional, or negative) that the backend refuses the whole configuration."""
try:
alter_id = int(value or 0)
except (TypeError, ValueError):
raise ValueError(f"invalid VMess aid {value!r}") from None
if not 0 <= alter_id <= 65535:
raise ValueError("VMess aid must be in 0-65535")
return alter_id
def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
b64 = url[len("vmess://") :]
b64, _, _ = b64.partition("#")
@@ -323,21 +504,31 @@ def parse_vmess(url: str, tag: str, backend: str = "sing-box") -> dict:
except (binascii.Error, ValueError):
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
host = str(data["add"])
host = str(data["add"]).strip()
# "[::1]", as the URL schemes write it: the backends dial it unbracketed.
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
port = _port(data["port"])
net = _check_transport(str(data.get("net", "tcp")), backend, "VMess")
tls_field = str(data.get("tls", ""))
sni = str(data.get("sni") or data.get("host") or host)
# Panels write unset fields as "": that is the default, not a value. XRay reads
# one it does not know as "auto"; sing-box refuses to start.
security = data.get("scy") or "auto"
if backend != "xray":
_one_of(security, SING_BOX_VMESS_SECURITY, "sing-box VMess security")
elif not isinstance(security, str):
raise ValueError("VMess scy must be a string")
ob: dict = {
"type": "vmess",
"tag": tag,
"server": host,
"server_port": port,
"uuid": data["id"],
# Panels write unset fields as "": that is the default, not a value.
"security": data.get("scy") or "auto",
"alter_id": int(data.get("aid") or 0),
"uuid": _user_id(data["id"], backend, "VMess"),
"security": security,
"alter_id": _alter_id(data.get("aid")),
}
if tls_field in ("tls", "reality"):
@@ -372,7 +563,7 @@ def parse_trojan(url: str, tag: str, backend: str = "sing-box") -> dict:
"tag": tag,
"server": host,
"server_port": _port(port),
"password": urllib.parse.unquote(userinfo),
"password": _nonempty_password(urllib.parse.unquote(userinfo), "Trojan"),
"tls": _mk_tls(
_param(params, "sni", host),
fp=params.get("fp"),
@@ -408,7 +599,39 @@ def _decode_ss_userinfo(userinfo: str) -> tuple[str, str]:
raise ValueError("invalid shadowsocks userinfo") from exc
def parse_shadowsocks(url: str, tag: str) -> dict:
def _nonempty_password(password: str, protocol: str) -> str:
# XRay refuses its whole configuration over one empty password; sing-box takes an
# empty Trojan one, which no server has.
if not password:
raise ValueError(f"{protocol} password is empty")
return password
def _check_ss(method: str, password: str, backend: str) -> None:
if backend == "xray":
if method not in SS2022_KEY_BYTES and method.lower() not in XRAY_SS_METHODS:
raise ValueError(f"unsupported XRay shadowsocks method '{method}'")
else:
_one_of(method, SING_BOX_SS_METHODS, "sing-box shadowsocks method")
if method.lower() != "none":
_nonempty_password(password, "Shadowsocks")
if method not in SS2022_KEY_BYTES:
return
# A 2022 password is the key itself, padded base64 ("iPSK:uPSK" for EIH, AES only):
# both backends decode it at start.
keys = password.split(":")
if len(keys) > 1 and "aes" not in method:
raise ValueError(f"{method} takes a single key")
for key in keys:
try:
decoded = base64.b64decode(key, validate=True)
except binascii.Error:
decoded = b""
if len(decoded) != SS2022_KEY_BYTES[method]:
raise ValueError(f"{method} needs a base64 key of {SS2022_KEY_BYTES[method]} bytes")
def parse_shadowsocks(url: str, tag: str, backend: str = "sing-box") -> dict:
# Support both SIP002 form:
# ss://base64(method:password)@host:port#name
# and legacy subscriptions that base64-encode the whole endpoint:
@@ -431,6 +654,7 @@ def parse_shadowsocks(url: str, tag: str) -> dict:
host, port = _split_host_port(hostpart)
method, password = _decode_ss_userinfo(userinfo)
_check_ss(method, password, backend)
return {
"type": "shadowsocks",
@@ -442,7 +666,16 @@ def parse_shadowsocks(url: str, tag: str) -> dict:
}
def parse_hysteria2(url: str, tag: str) -> dict:
# "20000-30000" or a lone "443" in sing-box's "a:b" form: it refuses to start on a bare port.
def _port_range(part: str, mport: str) -> str:
match = re.fullmatch(r"([0-9]+)(?:-([0-9]+))?", part)
low, high = (int(match[1]), int(match[2] or match[1])) if match else (0, 0)
if not 1 <= low <= high <= 65535:
raise ValueError(f"invalid hysteria2 mport {mport[:40]!r}")
return f"{low}:{high}"
def parse_hysteria2(url: str, tag: str, backend: str = "sing-box") -> dict:
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
userinfo, host, port, params = _parse_url_parts(url, scheme)
@@ -458,14 +691,24 @@ def parse_hysteria2(url: str, tag: str) -> dict:
"insecure": params.get("insecure", "0") == "1",
},
}
# XRay checks the certificate against the pin instead (sing-box pins only a public key).
pin = params.get("pinSHA256", "")
if backend == "xray" and pin:
if not CERT_SHA256_RE.fullmatch(pin):
raise ValueError(f"invalid hysteria2 pinSHA256 {pin[:100]!r}")
ob["tls"]["insecure"] = False
ob["tls"]["certificate_sha256"] = pin.replace(":", "").lower()
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
# sing-box refuses to start on salamander without one.
if not params.get("obfs-password"):
raise ValueError("hysteria2 salamander obfs is missing its obfs-password")
ob["obfs"] = {"type": "salamander", "password": params["obfs-password"]}
# Port hopping, as v2rayN writes it: "20000-30000", or several joined by commas. A fixed
# interval: hop_interval_max, which would randomise it, is newer than sing-box 1.13.
if params.get("mport"):
ob["server_ports"] = [r.strip().replace("-", ":") for r in params["mport"].split(",") if r.strip()]
ob["server_ports"] = [_port_range(r.strip(), params["mport"]) for r in params["mport"].split(",") if r.strip()]
ob["hop_interval"] = "30s"
return ob
@@ -475,6 +718,9 @@ def parse_tuic(url: str, tag: str) -> dict:
userinfo, host, port, params = _parse_url_parts(url, "tuic")
uuid, _, password = userinfo.partition(":")
alpn = _alpn(_param(params, "alpn", "h3"))
# Unlike VLESS, sing-box's TUIC takes nothing but a UUID.
if not UUID_RE.fullmatch(uuid):
raise ValueError("invalid TUIC uuid: not a UUID")
return {
"type": "tuic",
@@ -483,7 +729,9 @@ def parse_tuic(url: str, tag: str) -> dict:
"server_port": _port(port),
"uuid": uuid,
"password": urllib.parse.unquote(password),
"congestion_control": _param(params, "congestion_control", "bbr"),
"congestion_control": _one_of(
_param(params, "congestion_control", "bbr"), TUIC_CONGESTION_CONTROLS, "TUIC congestion_control"
),
"udp_relay_mode": _param(params, "udp_relay_mode", "native"),
"tls": {
"enabled": True,
@@ -576,4 +824,7 @@ BACKEND_AWARE_PARSERS = {
"vless",
"vmess",
"trojan",
"ss",
"hysteria2",
"hy2",
}
+85
View File
@@ -383,6 +383,23 @@ class AmneziaWgConfigTests(unittest.TestCase):
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)
@@ -499,6 +516,66 @@ class AmneziaWgConfigTests(unittest.TestCase):
# 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"])
@@ -544,6 +621,14 @@ class AmneziaWgConfigTests(unittest.TestCase):
"[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:
+54 -29
View File
@@ -58,7 +58,7 @@ def reality(**overrides):
"serverNames": ["www.microsoft.com"],
"privateKey": "private-key",
"privateKeyFile": None,
"publicKey": "public-key",
"publicKey": "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc",
"shortIds": ["0123abcd"],
"xver": 0,
}
@@ -69,11 +69,11 @@ def reality(**overrides):
def multi_user_shadowsocks(**overrides):
spec = {
"type": "shadowsocks",
"serverPassword": "server-psk",
"serverPassword": "c2VydmVyLXBzay0wMDAwMA==",
"serverPasswordFile": None,
"users": [
{"name": "a", "password": "psk-a", "passwordFile": None},
{"name": "b", "password": "psk-b", "passwordFile": None},
{"name": "a", "password": "cHNrLWEtcHNrLWEtcHNrLQ==", "passwordFile": None},
{"name": "b", "password": "cHNrLWItcHNrLWItcHNrLQ==", "passwordFile": None},
],
}
spec.update(overrides)
@@ -224,18 +224,18 @@ class RenderInboundTests(unittest.TestCase):
def test_shadowsocks_single_user_uses_password(self):
ib = render_xray_inbound(
listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}])
listener(type="shadowsocks", users=[{"name": "", "password": "cHNrLXBzay1wc2stcHNrLQ==", "passwordFile": None}])
)
self.assertEqual(ib["settings"]["password"], "psk")
self.assertEqual(ib["settings"]["password"], "cHNrLXBzay1wc2stcHNrLQ==")
self.assertEqual(ib["settings"]["method"], "2022-blake3-aes-128-gcm")
self.assertEqual(ib["settings"]["network"], "tcp,udp")
def test_shadowsocks_multi_user_has_server_key_and_clients(self):
ib = render_xray_inbound(multi_user_shadowsocks())
self.assertEqual(ib["settings"]["password"], "server-psk")
self.assertEqual(ib["settings"]["password"], "c2VydmVyLXBzay0wMDAwMA==")
self.assertEqual(
ib["settings"]["clients"],
[{"password": "psk-a", "email": "a"}, {"password": "psk-b", "email": "b"}],
[{"password": "cHNrLWEtcHNrLWEtcHNrLQ==", "email": "a"}, {"password": "cHNrLWItcHNrLWItcHNrLQ==", "email": "b"}],
)
def test_shadowsocks_multi_user_needs_server_key(self):
@@ -262,7 +262,7 @@ class ShareLinkTests(unittest.TestCase):
self.assertTrue(link.startswith("vless://uuid-1@vpn.example.com:443?"))
params = link_params(link)
self.assertEqual(params["security"], "reality")
self.assertEqual(params["pbk"], "public-key")
self.assertEqual(params["pbk"], "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc")
self.assertEqual(params["sid"], "0123abcd")
self.assertEqual(params["sni"], "www.microsoft.com")
self.assertEqual(params["flow"], "xtls-rprx-vision")
@@ -291,7 +291,7 @@ class ShareLinkTests(unittest.TestCase):
params = link_params(build_share_link(dict(target, front=reality_front), "1.2.3.4"))
self.assertEqual(
(params["security"], params["pbk"], params["sni"], params["sid"]),
("reality", "public-key", "www.microsoft.com", "0123abcd"),
("reality", "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc", "www.microsoft.com", "0123abcd"),
)
def test_reality_link_without_public_key_fails(self):
@@ -365,17 +365,17 @@ class ShareLinkTests(unittest.TestCase):
def test_shadowsocks_link_is_sip002(self):
spec = listener(
type="shadowsocks", method="aes-128-gcm", users=[{"name": "", "password": "psk", "passwordFile": None}]
type="shadowsocks", method="aes-128-gcm", users=[{"name": "", "password": "cHNrLXBzay1wc2stcHNrLQ==", "passwordFile": None}]
)
link = build_share_link(spec, "vpn.example.com")
userinfo = link[len("ss://") :].split("@", 1)[0]
userinfo += "=" * (-len(userinfo) % 4)
decoded = base64.urlsafe_b64decode(userinfo).decode()
self.assertEqual(decoded, "aes-128-gcm:psk")
self.assertEqual(decoded, "aes-128-gcm:cHNrLXBzay1wc2stcHNrLQ==")
def test_shadowsocks_2022_link_is_percent_encoded(self):
link = build_share_link(multi_user_shadowsocks(serverPassword="a+b/c="), "vpn.example.com")
self.assertTrue(link.startswith("ss://2022-blake3-aes-128-gcm:a%2Bb%2Fc%3D%3Apsk-a@"), link)
self.assertTrue(link.startswith("ss://2022-blake3-aes-128-gcm:a%2Bb%2Fc%3D%3AcHNrLWEtcHNrLWEtcHNrLQ%3D%3D@"), link)
def test_http_link_over_tls_is_https(self):
@@ -414,7 +414,7 @@ class RoundTripTests(unittest.TestCase):
self.assertEqual(settings["id"], "uuid-1")
self.assertEqual(settings["flow"], "xtls-rprx-vision")
rs = ob["streamSettings"]["realitySettings"]
self.assertEqual(rs["publicKey"], "public-key")
self.assertEqual(rs["publicKey"], "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc")
self.assertEqual(rs["shortId"], "0123abcd")
self.assertEqual(rs["serverName"], "www.microsoft.com")
@@ -545,32 +545,35 @@ class RoundTripTests(unittest.TestCase):
)
def test_trojan_round_trip(self):
link = build_share_link(
listener(
type="trojan",
users=[{"name": "", "password": "pw", "passwordFile": None}],
tls={"enable": False, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
),
"vpn.example.com",
)
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["type"], "trojan")
self.assertEqual(ob["password"], "pw")
# A declared password may hold what a URL gives meaning to.
for password in ("pw", "p@ss#w?rd/%"):
link = build_share_link(
listener(
type="trojan",
users=[{"name": "", "password": password, "passwordFile": None}],
tls={"enable": False, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
),
"vpn.example.com",
)
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["type"], "trojan")
self.assertEqual(ob["password"], password)
self.assertEqual(ob["server"], "vpn.example.com")
def test_shadowsocks_round_trip(self):
link = build_share_link(
listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}]),
listener(type="shadowsocks", users=[{"name": "", "password": "cHNrLXBzay1wc2stcHNrLQ==", "passwordFile": None}]),
"vpn.example.com",
)
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["type"], "shadowsocks")
self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm")
self.assertEqual(ob["password"], "psk")
self.assertEqual(ob["password"], "cHNrLXBzay1wc2stcHNrLQ==")
def test_shadowsocks_multi_user_round_trip(self):
link = build_share_link(multi_user_shadowsocks(), "vpn.example.com", 1)
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["password"], "server-psk:psk-b")
self.assertEqual(ob["password"], "c2VydmVyLXBzay0wMDAwMA==:cHNrLWItcHNrLWItcHNrLQ==")
def test_vmess_round_trip(self):
link = build_share_link(listener(type="vmess"), "vpn.example.com")
@@ -580,6 +583,17 @@ class RoundTripTests(unittest.TestCase):
class BuildInboundsTests(unittest.TestCase):
def test_exception_names_are_never_sniffed(self):
# A name routing sends direct is matched on what the client dials, not on the SNI
# it sends to some other host.
excluded = ["full:vpn.example.com", "domain:google.com"]
spec = {"listeners": [listener(tag="a", reality=reality())], "sniffDomainsExcluded": excluded}
ib = build_inbounds(spec, "vpn.example.com")["inbounds"][0]
self.assertEqual(ib["sniffing"]["domainsExcluded"], excluded)
self.assertTrue(ib["sniffing"]["routeOnly"])
ib = build_inbounds({"listeners": [listener(tag="a", reality=reality())]}, "vpn.example.com")["inbounds"][0]
self.assertNotIn("domainsExcluded", ib["sniffing"])
def test_spec_renders_inbounds_and_links(self):
spec = {
"serverAddress": "vpn.example.com",
@@ -599,11 +613,22 @@ class BuildInboundsTests(unittest.TestCase):
def test_client_outbound_falls_back_to_xray(self):
link = build_share_link(
listener(transport={"type": "xhttp", "path": "/p", "host": None, "mode": "auto", "serviceName": ""}),
listener(
transport={"type": "xhttp", "path": "/p", "host": None, "mode": "auto", "serviceName": ""},
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "vpn.example.com"},
),
"vpn.example.com",
)
self.assertEqual(client_outbound(link, "x")["protocol"], "vless")
def test_client_outbound_none_for_plaintext_vless_xray_refuses(self):
# XRay refuses VLESS in the clear to a public server, and sing-box has no XHTTP.
link = build_share_link(
listener(transport={"type": "xhttp", "path": "/p", "host": None, "mode": "auto", "serviceName": ""}),
"vpn.example.com",
)
self.assertIsNone(client_outbound(link, "x"))
def test_xhttp_mode_reaches_the_inbound_and_the_link(self):
spec = listener(
transport={"type": "xhttp", "path": "/p", "host": None, "mode": "packet-up", "serviceName": ""}
+130 -12
View File
@@ -25,15 +25,15 @@ def vmess_url(extra: dict) -> str:
class BuildOutboundTests(unittest.TestCase):
def test_vless_reality(self):
ob = run_parser(
"vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
"vless://uuid@example.com:443?security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=chrome&sni=cdn.example.com&sid=abcd"
)
self.assertEqual(ob["type"], "vless")
self.assertEqual(ob["server"], "example.com")
self.assertEqual(ob["tls"]["reality"]["public_key"], "pubkey")
self.assertEqual(ob["tls"]["reality"]["public_key"], "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc")
def test_vless_reality_germany_main_shape(self):
ob = run_parser(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
)
self.assertEqual(ob["type"], "vless")
self.assertEqual(ob["server_port"], 443)
@@ -46,7 +46,7 @@ class BuildOutboundTests(unittest.TestCase):
def test_xray_vless_reality_germany_main_shape(self):
ob = run_xray_parser(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
)
self.assertEqual(ob["protocol"], "vless")
self.assertEqual(ob["settings"]["address"], "example.com")
@@ -62,13 +62,13 @@ class BuildOutboundTests(unittest.TestCase):
def test_vless_raw_transport_is_tcp(self):
# XRay renamed the tcp network to "raw"; it is still plain TCP.
ob = run_parser(
"vless://uuid@example.com:443?type=raw&security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com"
"vless://uuid@example.com:443?type=raw&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=chrome&sni=cdn.example.com"
)
self.assertNotIn("transport", ob)
def test_at_sign_in_query_does_not_eat_the_host(self):
ob = run_parser(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey"
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
"&fp=chrome&sni=cdn.example.com&Telegram=@somechannel,@somechannel"
)
self.assertEqual(ob["server"], "example.com")
@@ -76,7 +76,7 @@ class BuildOutboundTests(unittest.TestCase):
def test_trailing_path_is_not_part_of_the_port(self):
ob = run_parser(
"vless://uuid@example.com:23576/?type=tcp&security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com"
"vless://uuid@example.com:23576/?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=chrome&sni=cdn.example.com"
)
self.assertEqual(ob["server_port"], 23576)
@@ -94,21 +94,110 @@ class BuildOutboundTests(unittest.TestCase):
def test_reality_empty_fingerprint_falls_back_to_chrome(self):
# sing-box's REALITY client refuses to start without a uTLS block.
ob = run_parser(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=&sni=cdn.example.com"
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&fp=&sni=cdn.example.com"
)
self.assertEqual(ob["tls"]["utls"]["fingerprint"], "chrome")
def test_xray_only_fingerprint_rejected_for_sing_box(self):
url = (
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey"
"&fp=unsafe&sni=cdn.example.com"
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
"&fp=hellochrome_120&sni=cdn.example.com"
)
with self.assertRaises(ValueError):
run_parser(url)
self.assertEqual(
run_xray_parser(url)["streamSettings"]["realitySettings"]["fingerprint"],
"unsafe",
"hellochrome_120",
)
# XRay's REALITY refuses the two it takes for plain TLS only.
for fp in ("unsafe", "hellogolang", "bogus"):
with self.subTest(fp=fp), self.assertRaisesRegex(ValueError, "XRay would refuse"):
run_xray_parser(url.replace("hellochrome_120", fp))
def test_values_a_backend_refuses_to_start_on_are_rejected(self):
"""Each of these took sing-box check or xray -test down with the whole config;
rejected here, a subscription skips just that entry."""
reality = (
"vless://uuid@example.com:443?security=reality&sni=a.example.com"
"&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&sid=ab"
)
tuic = "tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443"
k16 = base64.b64encode(b"k" * 16).decode()
cases = [
(reality + "&flow=xtls-rprx-direct", "both", "flow"),
(reality + "&flow=xtls-rprx-vision-udp443", "sing-box", "flow"),
(reality.replace("pbk=SbVK", "pbk=SbV+"), "both", "pbk"),
(reality.replace("pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc", "pbk=pubkey"), "both", "pbk"),
(reality.replace("sid=ab", "sid=abc"), "both", "sid"),
(reality.replace("sid=ab", "sid=0123456789abcdef00"), "both", "sid"),
(reality.replace("sid=ab", "sid=zz"), "both", "sid"),
(reality + "&spx=nopath", "xray", "spx"),
(reality + "&spx=%2F%25zz", "xray", "spx"),
(reality + "&spx=%2Fa%01b", "xray", "spx"),
(reality.replace("uuid@", "x" * 31 + "@"), "xray", "VLESS id"),
("vless://uuid@example.com:443?type=xhttp&security=tls&mode=bogus", "xray", "xhttp mode"),
("vless://uuid@example.com:443?type=h2&security=tls", "xray", "transport"),
("vless://uuid@example.com:443?type=quic&security=tls", "xray", "transport"),
("trojan://pw@example.com:443?security=tls&fp=bogus", "both", "fingerprint"),
(vmess_url({"scy": "aes-128-ctr"}), "sing-box", "VMess security"),
(vmess_url({"scy": "bogus"}), "sing-box", "VMess security"),
(vmess_url({"id": 123}), "both", "VMess id"),
(vmess_url({"id": None}), "xray", "VMess id"),
(tuic + "?congestion_control=reno", "sing-box", "congestion_control"),
("tuic://not-a-uuid:pw@example.com:443", "sing-box", "TUIC uuid"),
("hy2://pw@example.com:443?mport=a-b", "both", "mport"),
("hy2://pw@example.com:443?mport=1-70000", "both", "mport"),
("hy2://pw@example.com:443?mport=0-5", "both", "mport"),
("hy2://pw@example.com:443?mport=30000-20000", "both", "mport"),
("hy2://pw@example.com:443?insecure=1&pinSHA256=abcd", "xray", "pinSHA256"),
("trojan://@example.com:443?security=tls", "both", "password is empty"),
("hy2://pw@example.com:443?obfs=salamander", "both", "obfs-password"),
("ss://plain:pw@example.com:8388", "both", "method"),
("ss://aes-128-ctr:pw@example.com:8388", "xray", "method"),
("ss://chacha20-poly1305:pw@example.com:8388", "sing-box", "method"),
("ss://2022-blake3-aes-128-gcm:pw@example.com:8388", "both", "base64 key"),
("ss://2022-blake3-aes-128-gcm:" + base64.b64encode(b"k" * 32).decode() + "@example.com:8388", "both", "base64 key"),
(f"ss://2022-blake3-chacha20-poly1305:{k16}%3A{k16}@example.com:8388", "both", "single key"),
]
for url, backends, message in cases:
for backend in ("sing-box", "xray") if backends == "both" else (backends,):
with self.subTest(url=url, backend=backend), self.assertRaisesRegex(ValueError, message):
build_outbound(url, "test-outbound", backend=backend)
def test_values_one_backend_takes_still_parse(self):
reality = (
"vless://uuid@example.com:443?security=reality&sni=a.example.com"
"&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc&sid=0123456789ABCDEF"
)
self.assertEqual(run_xray_parser(reality + "&flow=xtls-rprx-vision-udp443")["settings"]["flow"],
"xtls-rprx-vision-udp443")
self.assertEqual(run_parser(reality)["tls"]["reality"]["short_id"], "0123456789ABCDEF")
self.assertEqual(run_xray_parser(vmess_url({"scy": "aes-128-ctr"}))["settings"]["security"], "aes-128-ctr")
self.assertEqual(run_parser(vmess_url({"scy": "aes-128-cfb"}))["security"], "aes-128-cfb")
# XRay takes a space (and non-ASCII) in spiderX; only control characters and bad escapes kill it.
spx = run_xray_parser(reality + "&spx=%2Fa%20b%C3%A9")["streamSettings"]["realitySettings"]["spiderX"]
self.assertEqual(spx, "/a b\u00e9")
self.assertEqual(run_xray_parser("ss://chacha20-poly1305:pw@example.com:8388")["settings"]["method"],
"chacha20-poly1305")
self.assertEqual(run_parser("ss://aes-128-ctr:pw@example.com:8388")["method"], "aes-128-ctr")
k16 = base64.b64encode(b"k" * 16).decode()
ss2022 = run_parser(f"ss://2022-blake3-aes-128-gcm:{k16}%3A{k16}@example.com:8388")
self.assertEqual(ss2022["password"], f"{k16}:{k16}")
def test_hysteria2_port_hopping_takes_lone_ports(self):
# sing-box refuses a bare "443"; it is the one-port range.
ob = run_parser("hy2://pw@example.com:443?mport=443, 20000-30000")
self.assertEqual(ob["server_ports"], ["443:443", "20000:30000"])
remote = run_xray_parser("hy2://pw@example.com:443?mport=443,20000-30000")
self.assertEqual(remote["streamSettings"]["finalmask"]["udp"][0]["settings"]["remotePorts"], "443-443,20000-30000")
def test_hysteria2_pin_replaces_insecure_for_xray(self):
pin = ":".join(["AB"] * 32)
url = f"hy2://pw@example.com:443?sni=a.example.com&insecure=1&pinSHA256={pin}"
tls = run_xray_parser(url)["streamSettings"]["tlsSettings"]
self.assertEqual(tls["pinnedPeerCertSha256"], "ab" * 32)
# sing-box pins only a public key: the link stays insecure there.
self.assertTrue(run_parser(url)["tls"]["insecure"])
def test_reality_without_pbk_is_rejected_clearly(self):
with self.assertRaisesRegex(ValueError, "pbk"):
@@ -165,6 +254,33 @@ class BuildOutboundTests(unittest.TestCase):
+ urllib.parse.quote(extra)
)
def test_xray_xhttp_extra_cannot_set_socket_options(self):
# A mark or interface would step around proxy-suite's routing; a dialerProxy chains elsewhere.
for extra, left in (
({"downloadSettings": {"address": "dl.example.com", "sockopt": {"mark": 0, "tcpFastOpen": True}}},
{"downloadSettings": {"address": "dl.example.com", "sockopt": {"tcpFastOpen": True}}}),
({"downloadSettings": {"sockopt": {"customSockopt": [], "TProxy": "redirect"}}},
{"downloadSettings": {"sockopt": {}}}),
({"downloadSettings": {"sockopt": {"dialerProxy": "direct", "interface": "eth0"}}},
{"downloadSettings": {"sockopt": {}}}),
({"Mark": 1, "xPaddingBytes": "100-1000"}, {"xPaddingBytes": "100-1000"}),
# The Kelvin sign, which Go folds to k as Python's lower() does.
({"downloadSettings": {"sockopt": {"mar\u212a": 0}}}, {"downloadSettings": {"sockopt": {}}}),
):
with self.subTest(extra=extra):
ob = run_xray_parser(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
+ urllib.parse.quote(json.dumps(extra))
)
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["extra"], left)
# Go's JSON decoding folds U+017F to s: XRay reads this as masterKeyLog, so a
# non-ASCII key is refused outright.
with self.assertRaisesRegex(ValueError, "names local files"):
run_xray_parser(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
+ urllib.parse.quote(json.dumps({"downloadSettings": {"tlsSettings": {"ma\u017fterKeyLog": "/etc/x"}}}))
)
def test_xray_vless_ech(self):
ob = run_xray_parser(
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
@@ -245,7 +361,9 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["tls"]["server_name"], "example.com")
self.assertEqual(ob["transport"]["headers"]["Host"], "example.com")
self.assertEqual(ob["transport"]["path"], "/")
tuic = run_parser("tuic://uuid:pw@example.com:443?alpn=&congestion_control=&udp_relay_mode=")
tuic = run_parser(
"tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?alpn=&congestion_control=&udp_relay_mode="
)
self.assertEqual(tuic["tls"]["alpn"], ["h3"])
self.assertEqual((tuic["congestion_control"], tuic["udp_relay_mode"]), ("bbr", "native"))
+336 -1
View File
@@ -1,10 +1,22 @@
#!/usr/bin/env python3
import base64
import contextlib
import http.server
import importlib.util
import io
import os
import sys
import tempfile
import threading
import time
import unittest
import urllib.error
import urllib.parse
import urllib.request
from unittest import mock
import proxy_parsing
from proxy_parsing import (
decode_subscription,
fetch_raw,
@@ -12,7 +24,10 @@ from proxy_parsing import (
parse_subscription,
)
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
VLESS_URI = (
"vless://uuid@example.com:443?security=reality&pbk=SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
"&fp=chrome&sni=cdn.example.com&sid=abcd"
)
VLESS_XHTTP_URI = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
VLESS_ECH_URI = "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
SS_URI = "ss://{}@ss.example.com:8388".format(
@@ -27,6 +42,14 @@ def _make_b64_payload(*uris: str) -> bytes:
return base64.b64encode(text.encode())
def _load_fetch_subscription():
here = os.path.dirname(os.path.abspath(proxy_parsing.__file__))
spec = importlib.util.spec_from_file_location("fetch_subscription", os.path.join(here, "fetch-subscription.py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def run_fetcher(
server_data: bytes,
tag_prefix: str = "test",
@@ -67,6 +90,81 @@ class FetchSubscriptionTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "redirected off http"):
fetch_raw(f"{base}/ftp")
def test_fetch_refuses_https_to_http_redirect(self):
handler = proxy_parsing._HttpOnlyRedirects()
request = urllib.request.Request("https://sub.example.com/s")
with self.assertRaisesRegex(ValueError, "from https:// to http://"):
handler.redirect_request(request, None, 302, "Found", {}, "http://sub.example.com/s")
# http to https, and https to https, still follow.
self.assertIsNotNone(handler.redirect_request(request, None, 302, "Found", {}, "https://cdn.example.com/s"))
plain = urllib.request.Request("http://sub.example.com/s")
self.assertIsNotNone(handler.redirect_request(plain, None, 302, "Found", {}, "https://sub.example.com/s"))
def test_fetch_refuses_redirects_nearer_to_this_host(self):
handler = proxy_parsing._HttpOnlyRedirects()
public = urllib.request.Request("http://203.0.113.5/s")
for target in ("http://127.0.0.1:8080/", "http://169.254.169.254/latest/meta-data/",
"http://[::1]/", "http://localhost/", "http://192.168.1.1/", "http://2130706433/"):
with self.subTest(target=target):
with self.assertRaisesRegex(ValueError, "this host or a private network"):
handler.redirect_request(public, None, 302, "Found", {}, target)
# Served from there already: a converter on loopback, a server on the LAN.
local = urllib.request.Request("http://127.0.0.1:25500/sub")
self.assertIsNotNone(handler.redirect_request(local, None, 302, "Found", {}, "http://127.0.0.1:25500/s2"))
lan = urllib.request.Request("http://192.168.1.2/sub")
self.assertIsNotNone(handler.redirect_request(lan, None, 302, "Found", {}, "http://192.168.1.3/s"))
with self.assertRaisesRegex(ValueError, "private network"):
handler.redirect_request(lan, None, 302, "Found", {}, "http://127.0.0.1/s")
# A name other than localhost is not looked up.
with mock.patch.object(proxy_parsing.socket, "getaddrinfo", side_effect=AssertionError("looked up")):
self.assertIsNotNone(handler.redirect_request(public, None, 302, "Found", {}, "http://cdn.example.com/s"))
def test_fetch_has_a_total_deadline(self):
# Every byte inside the socket timeout, but the body never ends.
class Trickle(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Length", "1000")
self.end_headers()
try:
for _ in range(1000):
self.wfile.write(b"x")
self.wfile.flush()
time.sleep(0.1)
except OSError:
pass
def log_message(self, *_):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Trickle)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
fetch = _load_fetch_subscription()
stderr = io.StringIO()
started = time.monotonic()
with mock.patch.object(fetch, "OVERALL_DEADLINE_SECONDS", 1), \
mock.patch.object(fetch.sys, "argv", ["fetch-subscription.py", "--tag-prefix", "t"]), \
mock.patch.object(fetch.sys, "stdin", io.StringIO(f"http://127.0.0.1:{server.server_port}/")), \
contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit):
fetch.main()
self.assertLess(time.monotonic() - started, 5)
self.assertIn("longer than 1s", stderr.getvalue())
def test_one_bad_entry_does_not_take_the_others(self):
# sing-box refuses to start on any of these; each is skipped, the good one kept.
bad = [
VLESS_URI.replace("pbk=SbVK", "pbk=Sb+K"),
VLESS_URI + "&flow=bogus",
"ss://{}@ss.example.com:8388".format(base64.urlsafe_b64encode(b"rc4:pw").decode()),
"tuic://00000000-0000-0000-0000-000000000000:pw@t.example.com:443?congestion_control=reno",
]
obs = run_fetcher(_make_b64_payload(*bad, SS_URI))
self.assertEqual([ob["type"] for ob in obs], ["shadowsocks"])
self.assertEqual(obs[0]["method"], "chacha20-ietf-poly1305")
def test_base64_payload_mixed_protocols(self):
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
obs = run_fetcher(payload)
@@ -210,5 +308,242 @@ class FetchSubscriptionTests(unittest.TestCase):
self.assertEqual(obs, {"singBox": [], "xray": []})
# Whoever serves a subscription picks its servers, and urltest prefers the fastest: an entry
# on this host would win, and make whatever listens there (Tor, the proxy itself) the exit.
LOCAL_SERVER_URIS = [
"socks5://127.0.0.1:9050#fast",
"socks5://127.8.9.10:1080",
"socks5://localhost:1080",
"socks5://Tor.LOCALHOST.:1080",
"socks5://[::1]:1080",
"socks5://[::ffff:127.0.0.1]:1080",
"socks5://0.0.0.0:1080",
"socks5://0.1.2.3:1080",
"socks5://[::]:1080",
# inet_aton's spellings of 127.0.0.1, which a resolver may hand back as an address.
"socks5://2130706433:1080",
"socks5://0x7f.1:1080",
"socks5://127.1:1080",
"http://169.254.169.254:80",
"socks5://[fe80::1]:1080",
"socks5://224.0.0.1:1080",
"socks5://[ff02::1]:1080",
VLESS_URI.replace("example.com", "127.0.0.1"),
# VMess's "add" is no URL: backends dial a bracketed one all the same.
"vmess://"
+ base64.b64encode(
b'{"add":"[127.0.0.1]","port":"80","id":"11111111-1111-1111-1111-111111111111","net":"ws","path":"/x"}'
).decode(),
"vmess://"
+ base64.b64encode(b'{"add":"[::1]","port":"80","id":"11111111-1111-1111-1111-111111111111"}').decode(),
]
PRIVATE_SERVER_URIS = [
"http://192.168.1.1:80",
"socks5://10.0.0.2:1080",
"socks5://172.16.5.4:1080",
"socks5://100.64.0.1:1080",
"socks5://[fd00::1]:1080",
"socks5://[::ffff:192.168.1.1]:1080",
]
PUBLIC_SERVER_URIS = [
"socks5://1.1.1.1:1080",
"socks5://[2606:4700::1111]:1080",
"socks5://localhost.example.com:1080",
"socks5://172.32.0.1:1080",
"socks5://3735928559:1080",
]
class SubscriptionServerTests(unittest.TestCase):
def parse(self, uris, *, backend="sing-box", allow_private=False):
lines = decode_subscription(_make_b64_payload(*uris))
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
if backend == "hybrid":
obs = parse_hybrid_subscription(lines, "sub", None, allow_private=allow_private)
else:
obs = parse_subscription(lines, "sub", None, backend, allow_private=allow_private)
return obs, stderr.getvalue()
def test_local_servers_are_dropped(self):
for uri in LOCAL_SERVER_URIS:
for allow_private in (False, True):
with self.subTest(uri=uri, allow_private=allow_private):
obs, err = self.parse([uri, SS_URI], allow_private=allow_private)
self.assertEqual([ob["server"] for ob in obs], ["ss.example.com"])
self.assertIn("skipping entry 0", err)
def test_private_servers_need_the_opt_in(self):
for uri in PRIVATE_SERVER_URIS:
with self.subTest(uri=uri):
obs, err = self.parse([uri, SS_URI])
self.assertEqual(len(obs), 1)
self.assertIn("private address", err)
obs, _ = self.parse([uri, SS_URI], allow_private=True)
self.assertEqual(len(obs), 2)
def test_public_servers_are_kept(self):
obs, err = self.parse(PUBLIC_SERVER_URIS)
self.assertEqual(len(obs), len(PUBLIC_SERVER_URIS), err)
def test_xray_and_hybrid_drop_local_servers_too(self):
local = VLESS_XHTTP_URI.replace("example.com", "127.0.0.1")
obs, _ = self.parse([local, VLESS_URI], backend="xray")
self.assertEqual([ob["settings"]["address"] for ob in obs], ["example.com"])
obs, err = self.parse([local, VLESS_XHTTP_URI], backend="hybrid")
self.assertEqual(obs["singBox"], [])
self.assertEqual([ob["settings"]["address"] for ob in obs["xray"]], ["example.com"])
# Refused once, not once per backend.
self.assertEqual(err.count("skipping entry 0"), 1)
def test_xhttp_download_settings_address_is_checked(self):
extra = urllib.parse.quote(
'{"downloadSettings":{"Address":"127.0.0.1","port":80,"network":"xhttp","security":"none"}}'
)
local = f"{VLESS_XHTTP_URI}&extra={extra}"
obs, err = self.parse([local, VLESS_URI], backend="xray")
self.assertEqual(len(obs), 1)
self.assertIn("is this host", err)
def test_ech_resolver_is_checked(self):
# XRay fetches an ECH config from the resolver echConfigList names, by its own dialer.
for ech in ("udp://127.0.0.1", "cdn.example.com+https://127.0.0.1:9/dns-query", "h2c://[::1]/q"):
with self.subTest(ech=ech):
uri = VLESS_ECH_URI.replace("udp%3A%2F%2F1.1.1.1", urllib.parse.quote(ech, safe=""))
obs, err = self.parse([uri, VLESS_URI], backend="xray")
self.assertEqual(len(obs), 1)
self.assertIn("is this host", err)
obs, err = self.parse([VLESS_ECH_URI], backend="xray")
self.assertEqual(len(obs), 1, err)
def test_entries_the_backend_would_refuse_are_skipped(self):
bad = [
# Without TLS XRay refuses VLESS to a public server.
"vless://11111111-1111-1111-1111-111111111111@1.1.1.1:443",
"ss://{}@ss.example.com:8388".format(base64.urlsafe_b64encode(b"aes-128-gcm:").decode()),
"trojan://@trojan.example.com:443",
VLESS_XHTTP_URI + "&extra=" + urllib.parse.quote('{"xPaddingBytes":NaN}'),
]
for uri in bad:
with self.subTest(uri=uri):
obs, err = self.parse([uri, VLESS_URI], backend="xray")
self.assertEqual(len(obs), 1, err)
self.assertIn("skipping entry 0", err)
def test_insecure_entries_need_the_opt_in(self):
insecure = "hy2://secret@hy.example.com:443?sni=hy.example.com&insecure=1"
obs, err = self.parse([insecure, HY2_URI])
self.assertEqual(len(obs), 1)
self.assertIn("certificate checks off", err)
lines = decode_subscription(_make_b64_payload(insecure, HY2_URI))
with contextlib.redirect_stderr(io.StringIO()):
kept = parse_subscription(lines, "sub", None, "sing-box", allow_insecure=True)
self.assertEqual(len(kept), 2)
def test_pinned_insecure_entries_go_to_xray(self):
pinned = f"hy2://secret@hy.example.com:443?sni=hy.example.com&insecure=1&pinSHA256={'ab' * 32}"
obs, err = self.parse([pinned], backend="hybrid")
self.assertEqual(obs["singBox"], [], err)
self.assertEqual(obs["xray"][0]["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], "ab" * 32)
def test_dropped_entry_leaves_no_link(self):
links: dict[str, str] = {}
lines = decode_subscription(_make_b64_payload("socks5://127.0.0.1:9050#fast", SS_URI))
with contextlib.redirect_stderr(io.StringIO()):
parse_subscription(lines, "sub", None, "sing-box", links)
self.assertEqual(list(links.values()), [SS_URI])
def test_check_server_does_not_look_names_up(self):
with mock.patch.object(proxy_parsing.socket, "getaddrinfo", side_effect=AssertionError("looked up")):
for host in (None, "", "example.com", "127.0.0.1.nip.io", "not an address", "12ab.example"):
with self.subTest(host=host):
proxy_parsing.check_server(host)
# Stands in for the backend: refuses a config holding a "bad" tag, naming the first one
# the way FAKE_STYLE says, and counts its runs.
FAKE_BACKEND = """
import json, os, sys
with open(os.environ["FAKE_RUNS"], "a") as handle:
handle.write("run\\n")
obs = json.load(sys.stdin)["outbounds"]
bad = [i for i, ob in enumerate(obs) if ob["tag"].startswith("bad")]
if not bad:
sys.exit(0)
style = os.environ["FAKE_STYLE"]
if style == "xray":
tag = obs[bad[0]]["tag"]
sys.exit(f"Failed to start: main: failed to load config files: [stdin:] > infra/conf: "
f"failed to build outbound config with tag {tag} > infra/conf: no")
if style == "sing-box":
sys.exit(f"\\x1b[31mFATAL\\x1b[0m[0000] initialize outbound[{bad[0]}]: no")
sys.exit("panic: runtime error: invalid memory address or nil pointer dereference")
"""
class BackendCheckTests(unittest.TestCase):
"""fetch-subscription.py's check of each batch by the backend's own binary."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.binary = os.path.join(self.tmp.name, "backend")
self.runs = os.path.join(self.tmp.name, "runs")
with open(self.binary, "w") as handle:
handle.write(f"#!{sys.executable}\n{FAKE_BACKEND}")
os.chmod(self.binary, 0o755)
self.fetch = _load_fetch_subscription()
def keep(self, tags, style="xray", kind="xray"):
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr), \
mock.patch.dict(os.environ, {"FAKE_RUNS": self.runs, "FAKE_STYLE": style}):
kept = self.fetch._Checker(kind, self.binary).keep([{"tag": t} for t in tags])
return [ob["tag"] for ob in kept], stderr.getvalue()
def run_count(self):
with open(self.runs) as handle:
return len(handle.readlines())
def test_refused_entries_go_and_the_rest_stay(self):
for style, kind in (("xray", "xray"), ("sing-box", "sing-box"), ("none", "xray"), ("none", "sing-box")):
with self.subTest(style=style, kind=kind):
kept, err = self.keep(["a", "bad1", "b", "c", "bad2", "d"], style, kind)
self.assertEqual(kept, ["a", "b", "c", "d"])
self.assertIn("'bad1'", err)
self.assertIn("'bad2'", err)
def test_a_named_refusal_costs_one_run(self):
tags = [f"bad{i}" if i % 50 == 7 else str(i) for i in range(500)]
for style in ("xray", "sing-box"):
with self.subTest(style=style):
if os.path.exists(self.runs):
os.unlink(self.runs)
kept, _ = self.keep(tags, style, style)
self.assertEqual(kept, [t for t in tags if not t.startswith("bad")])
# The empty config, one run per bad entry, and the one that passes.
self.assertEqual(self.run_count(), 1 + 10 + 1)
def test_a_clean_batch_takes_one_run(self):
kept, _ = self.keep([str(i) for i in range(100)])
self.assertEqual(len(kept), 100)
# The empty config first, then the batch.
self.assertEqual(self.run_count(), 2)
def test_a_check_that_does_not_run_checks_nothing(self):
self.binary = "/nonexistent/backend"
kept, err = self.keep(["a", "bad"])
self.assertEqual(kept, ["a", "bad"])
self.assertIn("does not run", err)
def test_out_of_runs_keeps_the_rest_unchecked(self):
tags = [f"bad{i}" for i in range(10)] + [str(i) for i in range(20)]
for style in ("xray", "none"):
with self.subTest(style=style), mock.patch.object(self.fetch, "MAX_CHECK_RUNS", 5):
kept, err = self.keep(tags, style)
self.assertTrue(set(map(str, range(20))) <= set(kept), kept)
self.assertIn("left unchecked", err)
if __name__ == "__main__":
unittest.main()
+166 -5
View File
@@ -9,6 +9,7 @@ import os
import stat
import tempfile
import unittest
from unittest import mock
import inbound_runtime as rt
@@ -111,7 +112,7 @@ class RuntimeTest(unittest.TestCase):
# `xray x25519` as XRay 26 prints it.
self.xray = os.path.join(self.tmp.name, "xray")
with open(self.xray, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\necho 'PrivateKey: private-x'\necho 'Password (PublicKey): public-x'\necho 'Hash32: h'\n")
f.write("#!/bin/sh\necho 'PrivateKey: cmVhbGl0eS10ZXN0LXByaXZhdGUta2V5LTMyYnl0ZXM'\necho 'Password (PublicKey): cmVhbGl0eS10ZXN0LXB1YmxpYy1rZXktMzItYnl0ZXM'\necho 'Hash32: h'\n")
os.chmod(self.xray, 0o755)
def tearDown(self):
@@ -171,6 +172,15 @@ class RuntimeTest(unittest.TestCase):
self.assertEqual(result["selfSources"][0]["ipv6"], "fd78::4")
self.assertEqual(warnings, [])
def test_a_full_amneziawg_subnet_refuses_another_runtime_user(self):
# A /30 holds one client: awg_inbound.py would fail every listener's start on a second.
awg = next(l for l in self.spec["listeners"] if l["tag"] == "awg")
awg["amneziaWg"] = {"subnet": "10.9.0.0/30"}
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["awg"])
with self.assertRaisesRegex(rt.RuntimeError_, "no free address"):
rt.cmd_users_add(self.spec, self.spool, "carol", None, ["awg"])
self.assertEqual(list(self.state()["users"]), ["alice"])
def test_a_second_user_on_a_plain_shadowsocks_listener_is_refused(self):
with self.assertRaisesRegex(rt.RuntimeError_, "2022-blake3-aes method"):
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["ss-in"])
@@ -195,7 +205,7 @@ class RuntimeTest(unittest.TestCase):
def test_bind_writes_the_runtime_side(self):
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
self.add_listener("friends", type="vless", port=20001)
self.add_listener("friends", type="vless", port=20001, tls={"enable": True, "certificate": "main"})
rt.cmd_bind(self.spec, self.spool, "alice", "vless-in", True)
rt.cmd_bind(self.spec, self.spool, "bob", "friends", True)
state = self.state()
@@ -214,7 +224,8 @@ class RuntimeTest(unittest.TestCase):
def test_removing_takes_the_bindings_along(self):
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
self.add_listener("friends", type="vless", port=20001, users=["alice", "bob"])
self.add_listener("friends", type="vless", port=20001, users=["alice", "bob"],
tls={"enable": True, "certificate": "main"})
rt.cmd_bind(self.spec, self.spool, "alice", "friends", True)
rt.cmd_users_rm(self.spec, self.spool, "alice")
self.assertEqual(self.state()["listeners"]["friends"]["users"], ["bob"])
@@ -228,6 +239,40 @@ class RuntimeTest(unittest.TestCase):
# --- listeners ---------------------------------------------------------------
def test_a_declared_password_that_is_no_2022_key_is_refused(self):
# A declared user's password is the key as it is: one of 16 bytes is right for aes-128,
# not for aes-256, where XRay would fail every listener's start.
key16, key32 = (base64.b64encode(bytes(range(n))).decode() for n in (16, 32))
self.spec["users"]["ss"]["password"] = key16
self.add_listener("ss128", type="shadowsocks", port=20001, method="2022-blake3-aes-128-gcm", users=["ss"],
serverPassword=key16)
with self.assertRaisesRegex(rt.RuntimeError_, "no 2022-blake3-aes-256-gcm key"):
self.add_listener("ss256", type="shadowsocks", port=20002, method="2022-blake3-aes-256-gcm", users=["ss"],
serverPassword=key32)
def test_declared_credentials_never_go_in_the_clear(self):
# bob's uuid is set in Nix: on a plain vless listener anyone on the way reads it.
with self.assertRaisesRegex(rt.RuntimeError_, "in the clear"):
self.add_listener("plain", type="vless", port=20001, users=["bob"])
# A runtime user's is drawn for the spool, and a loopback listener is a fallback's target.
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
self.add_listener("plain", type="vless", port=20001, users=["alice"])
self.add_listener("behind", type="vless", port=20002, address="127.0.0.1", users=["bob"])
def test_share_links_point_only_at_this_server(self):
# Declared users can be bound here: a link elsewhere would hand their uuid to whoever
# listens there, from the subscription they already have.
for fields, why in (
({"shareAddress": "evil.example.net"}, "shareAddress"),
({"sharePort": 31337}, "sharePort"),
({"order": -1000}, "order"),
):
with self.subTest(fields=fields):
with self.assertRaisesRegex(rt.RuntimeError_, why):
self.add_listener("decoy", type="vmess", port=20001, users=["bob"], **fields)
self.add_listener("decoy", type="vmess", port=20001, users=["bob"], shareAddress="vpn.example.com", sharePort=20001)
self.assertEqual(self.state()["listeners"]["decoy"]["shareAddress"], "vpn.example.com")
def test_reality_listener_gets_generated_keys(self):
args = rt.main.__globals__["argparse"].Namespace(
port=20001, listen=None, via=None, share_port=None, share_address=None, fingerprint="firefox", order=None, method=None,
@@ -241,7 +286,7 @@ class RuntimeTest(unittest.TestCase):
self.assertEqual(entry["shareFingerprint"], "firefox")
rt.cmd_add(self.spec, self.spool, "friends", entry, self.xray)
saved = self.state()["listeners"]["friends"]
self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("private-x", "public-x"))
self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("cmVhbGl0eS10ZXN0LXByaXZhdGUta2V5LTMyYnl0ZXM", "cmVhbGl0eS10ZXN0LXB1YmxpYy1rZXktMzItYnl0ZXM"))
self.assertRegex(saved["reality"]["shortIds"][0], r"^[0-9a-f]{8}$")
merged, result, _ = rt.merge(self.spec)
friends = next(l for l in merged["listeners"] if l["tag"] == "friends")
@@ -264,6 +309,50 @@ class RuntimeTest(unittest.TestCase):
({"type": "vless", "port": 20001, "shareFingerprint": "netscape"}, "shareFingerprint: invalid value"),
({"type": "hysteria2", "port": 20001, "hysteria": {"portHopping": "1-2"}}, "not something"),
({"type": "vless", "port": 20001, "fallbacks": [{"dest": 22}]}, "not in inbounds.runtime.fallbackDests"),
# XRay dials these for anyone: never this host, its LAN or the cloud metadata.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "127.0.0.1:5432"}},
"reality.dest .* private network"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "[::ffff:10.0.0.1]:443"}},
"reality.dest .* private network"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "2130706433:443"}},
"reality.dest .* private network"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "localhost:443"}},
"reality.dest .* private network"),
# A name may resolve inside: only ever a site's 443, not any service it has.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "db.example.com:5432"}},
"reality.dest .* port 443"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "[2001:db8::1]:22"}},
"reality.dest .* port 443"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "/run/x.sock"}},
"reality.dest"),
# A Unix socket, even one named to look like a port 443.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "@sock:443"}},
"reality.dest"),
# Each fails XRay's whole start, every declared listener with it.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "shortIds": []}},
"shortIds"),
({"type": "vless", "port": 20001, "transport": {"type": "ws", "path": "x"}}, "transport.path"),
({"type": "vless", "port": 20001, "fallbacks": [{"path": "x", "dest": "127.0.0.1:8080"}]}, "path"),
# Neither may raise and take every listener with it: "²" is a digit to isdigit.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "\u00b2"}},
"reality.dest .* port 443"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "dest": "a\u0000b:443"}},
"reality.dest: invalid value"),
({"type": "hysteria2", "port": 20001, "tls": {"certificate": "main"},
"hysteria": {"masquerade": "http://169.254.169.254/latest/meta-data/"}}, "masquerade .* public site"),
({"type": "hysteria2", "port": 20001, "tls": {"certificate": "main"},
"hysteria": {"masquerade": "file:///etc/shadow"}}, "masquerade .* public site"),
# A name may resolve inside (localtest.me is 127.0.0.1): a web port only.
({"type": "hysteria2", "port": 20001, "tls": {"certificate": "main"},
"hysteria": {"masquerade": "http://localtest.me:9090/"}}, "masquerade .* port 80 or 443"),
# Values XRay refuses, with the declared listeners along with them.
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "shortIds": ["abc"]}},
"shortIds: invalid"),
({"type": "vless", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"], "privateKey": "not-a-key"}},
"privateKey: invalid"),
({"type": "shadowsocks", "port": 20001, "method": "none"}, "method: invalid"),
({"type": "shadowsocks", "port": 20001, "method": "2022-blake3-aes-128-gcm", "serverPassword": "junk"},
"serverPassword must be base64 of 16 bytes"),
({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"),
({"type": "vless", "port": 20001, "flow": "xtls-rprx-vision", "transport": {"type": "ws"}}, "flow is only valid"),
({"type": "vmess", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"]}}, "reality only for vless"),
@@ -280,6 +369,14 @@ class RuntimeTest(unittest.TestCase):
self.add_listener("a", type="vless", port=20001)
with self.assertRaisesRegex(rt.RuntimeError_, "taken by another listener"):
self.add_listener("b", type="vless", port=20001)
# A public site, or a local decoy the configuration names, on whatever port.
for tag, port, dest in (("r1", 20003, "www.example.com:443"), ("r2", 20004, "127.0.0.1:8080"),
("r3", 20006, "[2606:4700::1111]:443")):
self.add_listener(tag, type="vless", port=port, reality={"enable": True, "serverNames": ["a.com"], "dest": dest})
self.add_listener("h", type="hysteria2", port=20005, tls={"certificate": "main"},
hysteria={"masquerade": "https://www.example.com"})
self.add_listener("h2", type="hysteria2", port=20007, tls={"certificate": "main"},
hysteria={"masquerade": "http://www.example.com:80/"})
def test_fallback_to_a_runtime_listener(self):
self.add_listener("ws", type="vless", port=20002, address="127.0.0.1", transport={"type": "ws", "path": "/ws"}, users=["bob"])
@@ -292,7 +389,7 @@ class RuntimeTest(unittest.TestCase):
self.assertEqual(by_tag["ws"]["front"]["port"], 8443)
self.assertEqual(by_tag["front"]["tls"]["certificateFile"], "/run/cert")
with self.assertRaisesRegex(rt.RuntimeError_, "already the fallback listener"):
self.add_listener("front2", type="vless", port=20003, fallbacks=[{"path": "/ws", "listener": "ws"}], users=["bob"])
self.add_listener("front2", type="vless", port=20003, tls={"enable": True, "certificate": "main"}, fallbacks=[{"path": "/ws", "listener": "ws"}], users=["bob"])
def test_listener_without_users_waits(self):
self.add_listener("empty", type="vless", port=20001)
@@ -320,6 +417,70 @@ class RuntimeTest(unittest.TestCase):
_, result, more = rt.merge_state(self.spec, state)
self.assertIn(("user", "noorder"), result["problems"])
def test_a_listener_that_trips_a_check_goes_alone(self):
# Written straight into the spool, past cmd_add: merge drops it, not every listener.
self.write("listeners", "odd", {"order": 1, "type": "vless", "port": 20001,
"reality": {"enable": True, "serverNames": ["a.com"], "dest": "\u00b2"}})
with mock.patch.object(rt, "listener_problems", side_effect=ValueError("boom")):
_, result, _ = rt.merge_state(self.spec, self.state())
self.assertIn(("listener", "odd"), result["problems"])
def test_a_kind_directory_swapped_for_a_link_is_not_followed(self):
# The spool is group-writable: users/ renamed away and a link left in its place.
elsewhere = os.path.join(self.tmp.name, "elsewhere")
os.makedirs(elsewhere)
with open(os.path.join(elsewhere, "eve.json"), "w", encoding="utf-8") as f:
f.write(json.dumps({"order": 5, "uuid": "44444444-4444-4444-8444-444444444444", "password": "p", "listeners": []}))
os.symlink(elsewhere, os.path.join(self.spool, "users"))
state, warnings = rt.load_spool(self.spool)
self.assertEqual(state["users"], {})
self.assertEqual(len(warnings), 1)
with self.assertRaises(OSError):
self.write("users", "alice", {"order": 6})
with self.assertRaises(OSError):
rt.remove_entry(self.spool, "users", "eve")
self.assertEqual(os.listdir(elsewhere), ["eve.json"])
def test_changes_take_the_spool_lock(self):
fd = rt.lock_spool(self.spool)
try:
other = os.open(os.path.join(self.spool, ".lock"), os.O_RDWR)
try:
with self.assertRaises(BlockingIOError):
rt.fcntl.flock(other, rt.fcntl.LOCK_EX | rt.fcntl.LOCK_NB)
finally:
os.close(other)
finally:
os.close(fd)
# A lock file another made 0640 still serves: it is opened read-only.
os.chmod(os.path.join(self.spool, ".lock"), 0o440)
os.close(rt.lock_spool(self.spool))
os.unlink(os.path.join(self.spool, ".lock"))
os.symlink(os.path.join(self.tmp.name, "target"), os.path.join(self.spool, ".lock"))
with self.assertRaises(OSError):
rt.lock_spool(self.spool)
self.assertFalse(os.path.exists(os.path.join(self.tmp.name, "target")))
def test_a_lock_outside_the_spool_is_used_not_made(self):
lock = os.path.join(self.tmp.name, "spool.lock")
# Not there yet: the spool's own instead, and the outside one is not made.
os.close(rt.lock_spool(self.spool, lock))
self.assertFalse(os.path.exists(lock))
os.unlink(os.path.join(self.spool, ".lock"))
open(lock, "w").close()
os.chmod(lock, 0o440)
fd = rt.lock_spool(self.spool, lock)
try:
other = os.open(lock, os.O_RDONLY)
try:
with self.assertRaises(BlockingIOError):
rt.fcntl.flock(other, rt.fcntl.LOCK_EX | rt.fcntl.LOCK_NB)
finally:
os.close(other)
finally:
os.close(fd)
self.assertFalse(os.path.exists(os.path.join(self.spool, ".lock")))
def test_entries_are_group_readable_only(self):
self.write("users", "alice", {"order": 5})
mode = stat.S_IMODE(os.stat(os.path.join(self.spool, "users", "alice.json")).st_mode)
+12 -3
View File
@@ -48,8 +48,14 @@ gh_api() {
# Xray-core was already on v26.9.9, and 404s for amneziawg-go).
latest_tag() {
local owner=$1 repo=$2 tag
tag=$(gh_api "https://api.github.com/repos/${owner}/${repo}/tags?per_page=100" |
jq -r '.[].name' | grep -E '^v?[0-9]' | sort -V | tail -n1)
# The tag is spliced into a Nix string and an awk replacement: git allows `"`,
# `$`, `{` and `&` in ref names, so only plain version-shaped tags pass.
local tags
tags=$(gh_api "https://api.github.com/repos/${owner}/${repo}/tags?per_page=100" |
jq -r '.[].name' | grep -E '^v?[0-9][0-9A-Za-z._+-]*$') || true
# sort -V puts v1.0.0-rc1 after v1.0.0: plain numbered tags win where a repo has any.
tag=$(grep -E '^v?[0-9]+(\.[0-9]+)*$' <<< "$tags" | sort -V | tail -n1 || true)
[[ -n "$tag" ]] || tag=$(sort -V <<< "$tags" | tail -n1)
[[ -n "$tag" ]] || { echo "unable to resolve latest tag for ${owner}/${repo}" >&2; return 1; }
printf '%s\n' "$tag"
}
@@ -185,7 +191,10 @@ for pin in "${PINS[@]}"; do
if [[ "$current" != "$new" ]]; then
set_attr "$file" "" "$key" "$new" || { echo "could not write ${key} in ${file}" >&2; exit 1; }
BUMPED[$key]=1
echo "updated ${repo}: ${current} -> ${new}"
# The commit the tag names now, for the review: a moved tag shows up as a commit that
# is not on the project's history.
commit=$(gh_api "https://api.github.com/repos/${owner}/${repo}/commits/${tag_ref}" | jq -r '.sha // empty') || true
echo "updated ${repo}: ${current} -> ${new} (commit ${commit:-unknown})"
fi
set_attr "$file" "$repo" hash "$hash" || { echo "could not write hash for ${repo}" >&2; exit 1; }
refresh_vendor_hash "$file" "$repo" "$attr"