feat: warp/awg and hysteria2 improvements
This commit is contained in:
24 files changed
+676
-18
No files matched your search
@@ -11,6 +11,8 @@ without changing the spec or the link generator.
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import urllib.parse
|
||||
|
||||
from awg_inbound import client_entries
|
||||
@@ -57,6 +59,34 @@ def _server_secret(listener: dict, tag: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _salamander(listener: dict) -> str | None:
|
||||
"""The Salamander password of a hysteria2 listener that obfuscates, else None.
|
||||
|
||||
Given inline or as a file; otherwise generated on first start and kept in the
|
||||
state file, so share links stay the same across restarts.
|
||||
"""
|
||||
salamander = (listener.get("hysteria") or {}).get("salamander") or {}
|
||||
if not salamander.get("enable"):
|
||||
return None
|
||||
if salamander.get("password") is not None or salamander.get("passwordFile") is not None:
|
||||
return _resolve(
|
||||
salamander.get("password"), salamander.get("passwordFile"), "salamander password", listener["tag"]
|
||||
)
|
||||
path = listener["salamanderStateFile"]
|
||||
try:
|
||||
stored = _read_secret(path)
|
||||
except FileNotFoundError:
|
||||
stored = ""
|
||||
if stored:
|
||||
return stored
|
||||
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
|
||||
generated = secrets.token_urlsafe(24)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(generated + "\n")
|
||||
return generated
|
||||
|
||||
|
||||
def _b64(value: str) -> str:
|
||||
"""base64 without padding, as share links carry it."""
|
||||
return base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
@@ -100,12 +130,16 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
masquerade = (listener.get("hysteria") or {}).get("masquerade")
|
||||
if masquerade:
|
||||
settings["masquerade"] = {"type": "proxy", "url": masquerade, "rewriteHost": True}
|
||||
return {
|
||||
stream = {
|
||||
"network": "hysteria",
|
||||
"hysteriaSettings": settings,
|
||||
"security": "tls",
|
||||
"tlsSettings": _tls_settings(listener["tls"], ["h3"]),
|
||||
}
|
||||
salamander = _salamander(listener)
|
||||
if salamander is not None:
|
||||
stream["finalmask"] = {"udp": [{"type": "salamander", "settings": {"password": salamander}}]}
|
||||
return stream
|
||||
|
||||
transport = listener["transport"]
|
||||
network = transport["type"]
|
||||
@@ -126,8 +160,9 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
# online; the forwarded address is only trusted when one of these headers is present.
|
||||
if transport.get("trustedXForwardedFor"):
|
||||
stream.setdefault("sockopt", {})["trustedXForwardedFor"] = transport["trustedXForwardedFor"]
|
||||
# Behind another listener's fallback, the client address arrives in PROXY protocol.
|
||||
if listener.get("front"):
|
||||
# Behind another listener's fallback or a TCP front, the client address arrives in
|
||||
# PROXY protocol.
|
||||
if listener.get("front") or listener.get("acceptProxyProtocol"):
|
||||
stream.setdefault("sockopt", {})["acceptProxyProtocol"] = True
|
||||
|
||||
reality = listener["reality"]
|
||||
@@ -146,6 +181,8 @@ def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
),
|
||||
"shortIds": reality["shortIds"],
|
||||
}
|
||||
if reality.get("xver"):
|
||||
stream["realitySettings"]["xver"] = reality["xver"]
|
||||
elif tls["enable"] or listener["type"] == "trojan":
|
||||
stream["security"] = "tls"
|
||||
stream["tlsSettings"] = _tls_settings(tls)
|
||||
@@ -312,6 +349,12 @@ def build_share_link(
|
||||
if user_index < 0 or user_index >= len(users):
|
||||
raise ValueError(f"listener '{tag}': user index {user_index} is out of range")
|
||||
|
||||
# Behind another listener's fallback, clients dial that one, under its TLS or REALITY.
|
||||
front = listener.get("front") or listener
|
||||
# A listener with a name of its own is dialled by it, so the name clients look up is the
|
||||
# one they then send as SNI; it is also the default SNI.
|
||||
server_address = front.get("shareAddress") or server_address
|
||||
|
||||
user = users[user_index]
|
||||
secret = _user_secret(user, listener_type, tag)
|
||||
user_name = user.get("name") or f"{tag}-{user_index}"
|
||||
@@ -319,8 +362,6 @@ def build_share_link(
|
||||
fragment = urllib.parse.quote(label, safe="")
|
||||
endpoint_address = onion_address or server_address
|
||||
host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address
|
||||
# Behind another listener's fallback, clients dial that one, under its TLS or REALITY.
|
||||
front = listener.get("front") or listener
|
||||
endpoint = f"{host}:{_share_port(front)}"
|
||||
|
||||
if listener_type == "vmess":
|
||||
@@ -349,6 +390,13 @@ def build_share_link(
|
||||
if listener_type == "hysteria2":
|
||||
tls = listener["tls"]
|
||||
params = {"sni": tls.get("serverName") or server_address, "alpn": ",".join(tls.get("alpn") or ["h3"])}
|
||||
salamander = _salamander(listener)
|
||||
if salamander is not None:
|
||||
params.update({"obfs": "salamander", "obfs-password": salamander})
|
||||
# v2rayN's name for the hop range; clients that do not know it stay on the port.
|
||||
hopping = (listener.get("hysteria") or {}).get("portHopping")
|
||||
if hopping:
|
||||
params["mport"] = hopping
|
||||
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
|
||||
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
|
||||
|
||||
|
||||
@@ -161,6 +161,18 @@ def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
|
||||
}
|
||||
if ob.get("password"):
|
||||
stream["hysteriaSettings"]["auth"] = ob["password"]
|
||||
# XRay wants udphop outermost, ahead of any other UDP mask.
|
||||
if ob.get("server_ports"):
|
||||
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
|
||||
{
|
||||
"type": "udphop",
|
||||
"settings": {
|
||||
"mode": "intervalRemote",
|
||||
"interval": "20-40",
|
||||
"remotePorts": ",".join(r.replace(":", "-") for r in ob["server_ports"]),
|
||||
},
|
||||
}
|
||||
)
|
||||
if ob.get("obfs", {}).get("type") == "salamander":
|
||||
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
|
||||
{
|
||||
|
||||
@@ -433,6 +433,12 @@ def parse_hysteria2(url: str, tag: str) -> dict:
|
||||
if params.get("obfs") == "salamander":
|
||||
ob["obfs"] = {"type": "salamander", "password": params.get("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["hop_interval"] = "30s"
|
||||
|
||||
return ob
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ def listener(**overrides):
|
||||
"type": "vless",
|
||||
"port": 443,
|
||||
"sharePort": None,
|
||||
"acceptProxyProtocol": False,
|
||||
"listen": "::",
|
||||
"via": "direct",
|
||||
"users": [{"name": "", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}],
|
||||
@@ -40,6 +41,7 @@ def listener(**overrides):
|
||||
"privateKeyFile": None,
|
||||
"publicKey": None,
|
||||
"shortIds": [""],
|
||||
"xver": 0,
|
||||
},
|
||||
"xrayJson": None,
|
||||
"jsonFile": None,
|
||||
@@ -57,6 +59,7 @@ def reality(**overrides):
|
||||
"privateKeyFile": None,
|
||||
"publicKey": "public-key",
|
||||
"shortIds": ["0123abcd"],
|
||||
"xver": 0,
|
||||
}
|
||||
settings.update(overrides)
|
||||
return settings
|
||||
@@ -183,6 +186,19 @@ class RenderInboundTests(unittest.TestCase):
|
||||
{"trustedXForwardedFor": ["X-Real-IP"], "acceptProxyProtocol": True},
|
||||
)
|
||||
|
||||
def test_accept_proxy_protocol_behind_a_tcp_front(self):
|
||||
"""nginx's stream front sends the client address in PROXY protocol, with no fallback involved."""
|
||||
ib = render_xray_inbound(listener(acceptProxyProtocol=True, reality=reality()))
|
||||
self.assertEqual(ib["streamSettings"]["sockopt"], {"acceptProxyProtocol": True})
|
||||
self.assertNotIn("sockopt", render_xray_inbound(listener(reality=reality()))["streamSettings"])
|
||||
|
||||
def test_reality_xver_only_when_set(self):
|
||||
self.assertNotIn("xver", render_xray_inbound(listener(reality=reality()))["streamSettings"]["realitySettings"])
|
||||
self.assertEqual(
|
||||
render_xray_inbound(listener(reality=reality(xver=2)))["streamSettings"]["realitySettings"]["xver"],
|
||||
2,
|
||||
)
|
||||
|
||||
def test_grpc_transport(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"})
|
||||
@@ -447,6 +463,66 @@ class RoundTripTests(unittest.TestCase):
|
||||
# Without masquerade XRay answers non-clients with 404; nothing to render.
|
||||
plain = render_xray_inbound(dict(spec, hysteria={"masquerade": None}))
|
||||
self.assertEqual(plain["streamSettings"]["hysteriaSettings"], {"version": 2})
|
||||
self.assertNotIn("finalmask", plain["streamSettings"])
|
||||
|
||||
def test_hysteria2_salamander_and_hopping_reach_links(self):
|
||||
salamander = {"enable": True, "password": "m@sk", "passwordFile": None}
|
||||
spec = listener(
|
||||
type="hysteria2",
|
||||
users=[{"name": "phone", "password": "pw", "passwordFile": None}],
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "hy.example.com"},
|
||||
hysteria={"masquerade": None, "salamander": salamander, "portHopping": "20000-30000"},
|
||||
)
|
||||
self.assertEqual(
|
||||
render_xray_inbound(spec)["streamSettings"]["finalmask"],
|
||||
{"udp": [{"type": "salamander", "settings": {"password": "m@sk"}}]},
|
||||
)
|
||||
link = build_share_link(spec, "vpn.example.com")
|
||||
params = link_params(link)
|
||||
self.assertEqual((params["obfs"], params["obfs-password"], params["mport"]), ("salamander", "m@sk", "20000-30000"))
|
||||
# The link reads back with both, into either backend.
|
||||
ob = build_outbound(link, "hop", backend="sing-box")
|
||||
self.assertEqual(ob["obfs"], {"type": "salamander", "password": "m@sk"})
|
||||
self.assertEqual(ob["server_ports"], ["20000:30000"])
|
||||
self.assertEqual(ob["server_port"], 443)
|
||||
masks = build_outbound(link, "hop", backend="xray")["streamSettings"]["finalmask"]["udp"]
|
||||
self.assertEqual([m["type"] for m in masks], ["udphop", "salamander"])
|
||||
self.assertEqual(masks[0]["settings"]["remotePorts"], "20000-30000")
|
||||
|
||||
def test_share_address_is_dialled_and_the_default_sni(self):
|
||||
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
|
||||
front = listener(shareAddress="cdn.example.com", tls=tls, flow="xtls-rprx-vision")
|
||||
link = build_share_link(front, "vpn.example.com")
|
||||
self.assertTrue(link.startswith("vless://uuid-1@cdn.example.com:443?"), link)
|
||||
self.assertEqual(link_params(link)["sni"], "cdn.example.com")
|
||||
# A listener behind its fallback is dialled the same way.
|
||||
behind = listener(
|
||||
port=10006,
|
||||
address="127.0.0.1",
|
||||
transport={"type": "xhttp", "path": "/x", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []},
|
||||
front={"tag": "front-in", "type": "vless", "port": 443, "sharePort": None, "shareAddress": "cdn.example.com", "tls": tls, "reality": reality(enable=False)},
|
||||
)
|
||||
self.assertTrue(build_share_link(behind, "vpn.example.com").startswith("vless://uuid-1@cdn.example.com:443?"))
|
||||
self.assertTrue(build_share_link(listener(tls=tls), "vpn.example.com").startswith("vless://uuid-1@vpn.example.com:443?"))
|
||||
|
||||
def test_hysteria2_salamander_password_generated_once(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
state = os.path.join(tmp, "inbounds", "hy2-in", "salamander-password")
|
||||
spec = listener(
|
||||
type="hysteria2",
|
||||
users=[{"name": "phone", "password": "pw", "passwordFile": None}],
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
|
||||
hysteria={"salamander": {"enable": True, "password": None, "passwordFile": None}},
|
||||
salamanderStateFile=state,
|
||||
)
|
||||
first = link_params(build_share_link(spec, "vpn.example.com"))["obfs-password"]
|
||||
self.assertTrue(first)
|
||||
self.assertEqual(oct(os.stat(state).st_mode & 0o777), "0o600")
|
||||
# Kept across restarts, so the links users hold stay valid.
|
||||
self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["obfs-password"], first)
|
||||
self.assertEqual(
|
||||
render_xray_inbound(spec)["streamSettings"]["finalmask"]["udp"][0]["settings"]["password"], first
|
||||
)
|
||||
|
||||
def test_trojan_round_trip(self):
|
||||
link = build_share_link(
|
||||
|
||||
Reference in new issue
Block a user