fix: hardening
This commit is contained in:
19 files changed
+486
-119
No files matched your search
@@ -32,6 +32,7 @@ import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
# User names and listener tags: they become file names, XRay emails and tags, and URL parts.
|
||||
@@ -136,13 +137,23 @@ def write_entry(spool: str, kind: str, name: str, entry: dict) -> None:
|
||||
old = os.umask(0o027)
|
||||
try:
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
path = os.path.join(directory, f"{name}.json")
|
||||
tmp = os.path.join(directory, f".{name}.json.tmp")
|
||||
with open(tmp, "w", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n")
|
||||
os.replace(tmp, path)
|
||||
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)
|
||||
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:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def remove_entry(spool: str, kind: str, name: str) -> None:
|
||||
@@ -352,6 +363,14 @@ def port_free(address: str, port: int, kinds: list[int]) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _is_ip(address) -> bool:
|
||||
try:
|
||||
ipaddress.ip_address(address)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _loopback(address: str) -> bool:
|
||||
return address.startswith("127.") or address in ("::1", "localhost")
|
||||
|
||||
@@ -431,6 +450,8 @@ def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[
|
||||
|
||||
need(_port_allowed(listener["port"], runtime.get("ports") or []),
|
||||
f"port {listener['port']} is not in inbounds.runtime.ports")
|
||||
# XRay takes a path or an @name for a Unix socket: a runtime listener binds an IP only.
|
||||
need(_is_ip(listener["listen"]), f"address '{listener['listen']}' is not an IP address")
|
||||
need(listener["via"] in runtime.get("vias") or [],
|
||||
f"via '{listener['via']}' is not routing.via, \"block\" or in inbounds.runtime.vias")
|
||||
need(not (tls["enable"] and reality["enable"]), "tls and reality are mutually exclusive")
|
||||
@@ -586,6 +607,11 @@ def number_users(spec: dict, names: list[str], state_users: dict, warnings: list
|
||||
if size is not None and number + 2 > size:
|
||||
warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv4; no own address")
|
||||
continue
|
||||
# The number is the last group of the IPv6 address (the prefix is /112 or shorter):
|
||||
# five hex digits would be no address, and the start script would fail on it.
|
||||
if source.get("ipv6") is not None and number > 0xFFFF:
|
||||
warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv6; no own address")
|
||||
continue
|
||||
taken.add(number)
|
||||
numbered.append(
|
||||
{
|
||||
|
||||
@@ -70,6 +70,33 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
|
||||
return userinfo, host, port, _qs(query)
|
||||
|
||||
|
||||
def local_file_keys(value) -> list[str]:
|
||||
"""The keys anywhere in `value` that point a backend at a local file or program.
|
||||
|
||||
The backends hold CAP_NET_ADMIN, and a share link is whatever a subscription serves:
|
||||
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.
|
||||
"""
|
||||
found: set[str] = set()
|
||||
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)
|
||||
elif isinstance(item, list):
|
||||
stack.extend(item)
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def _parse_json_param(value: str, name: str) -> dict:
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
@@ -77,6 +104,8 @@ def _parse_json_param(value: str, name: str) -> dict:
|
||||
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)}")
|
||||
return parsed
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import base64
|
||||
import json
|
||||
import unittest
|
||||
import urllib.parse
|
||||
|
||||
import proxy_parsing
|
||||
from proxy_parsing import build_outbound
|
||||
@@ -141,6 +142,29 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["streamSettings"]["network"], "xhttp")
|
||||
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x")
|
||||
|
||||
def test_xray_xhttp_extra_keeps_ordinary_settings(self):
|
||||
extra = json.dumps({"xPaddingBytes": "100-1000", "downloadSettings": {"address": "dl.example.com"}})
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
|
||||
+ urllib.parse.quote(extra)
|
||||
)
|
||||
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["extra"]["xPaddingBytes"], "100-1000")
|
||||
|
||||
def test_xray_xhttp_extra_cannot_name_local_files(self):
|
||||
# XRay holds CAP_NET_ADMIN: a subscription must not make it write masterKeyLog or read a key.
|
||||
extra = json.dumps(
|
||||
{
|
||||
"downloadSettings": {
|
||||
"tlsSettings": {"masterKeyLog": "/etc/x", "certificates": [{"keyFile": "/root/k"}]}
|
||||
}
|
||||
}
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "keyfile, masterkeylog"):
|
||||
run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra="
|
||||
+ urllib.parse.quote(extra)
|
||||
)
|
||||
|
||||
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"
|
||||
|
||||
@@ -149,6 +149,15 @@ class RuntimeTest(unittest.TestCase):
|
||||
rt.cmd_users_order(self.spec, self.spool, "alice", 12)
|
||||
self.assertEqual(self.state()["users"]["alice"]["order"], 12)
|
||||
|
||||
def test_a_number_past_the_ipv6_group_gets_no_address(self):
|
||||
# The last group holds four hex digits: 0x10000 would be no address, and the start
|
||||
# script would fail on it for every listener.
|
||||
spec = {"serverSource": {"ipv4": None, "ipv6": "fd78::/64", "declared": []}, "users": {}}
|
||||
warnings = []
|
||||
numbered = rt.number_users(spec, ["big", "ok"], {"big": {"order": 70000}, "ok": {"order": 65535}}, warnings)
|
||||
self.assertEqual([(n["email"], n["ipv6"]) for n in numbered], [("ok", "fd78::ffff")])
|
||||
self.assertIn("runtime user 'big': number 70000 does not fit in serverSource.ipv6", warnings[0])
|
||||
|
||||
def test_runtime_users_join_declared_listeners(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in", "awg"])
|
||||
merged, result, warnings = rt.merge(self.spec)
|
||||
@@ -255,6 +264,9 @@ class RuntimeTest(unittest.TestCase):
|
||||
({"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"),
|
||||
# XRay would take these as Unix socket paths.
|
||||
({"type": "vless", "port": 20001, "address": "/run/x.sock"}, "not an IP address"),
|
||||
({"type": "vless", "port": 20001, "address": "@abstract"}, "not an IP address"),
|
||||
]
|
||||
for entry, message in cases:
|
||||
with self.subTest(entry=entry), self.assertRaisesRegex(rt.RuntimeError_, message):
|
||||
|
||||
Reference in new issue
Block a user