feat: add connectivity fix options + hardening
This commit is contained in:
41 files changed
+626
-111
No files matched your search
@@ -11,6 +11,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
@@ -67,8 +68,26 @@ class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _shared_directory(path: str) -> bool:
|
||||
"""Whether someone besides this user may add files next to path.
|
||||
|
||||
Runtime profiles come from a group-writable spool and are read as root: a symlink
|
||||
there would hand over any file root can read, and a FIFO would hang the unit.
|
||||
"""
|
||||
try:
|
||||
info = os.stat(os.path.dirname(os.path.abspath(path)))
|
||||
except OSError:
|
||||
return True
|
||||
return info.st_uid != os.geteuid() or bool(info.st_mode & (stat.S_IWGRP | stat.S_IWOTH))
|
||||
|
||||
|
||||
def _read_limited(path: str) -> str:
|
||||
with Path(path).open("rb") as handle:
|
||||
"""At most MAX_INPUT_BYTES of path, as UTF-8; in a shared directory, only a regular file."""
|
||||
shared = _shared_directory(path)
|
||||
fd = os.open(path, os.O_RDONLY | (os.O_NOFOLLOW | os.O_NONBLOCK if shared else 0))
|
||||
with os.fdopen(fd, "rb") as handle:
|
||||
if shared and not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||
raise ConfigError(f"{path} is not a regular file")
|
||||
data = handle.read(MAX_INPUT_BYTES + 1)
|
||||
if len(data) > MAX_INPUT_BYTES:
|
||||
raise ConfigError(f"input exceeds {MAX_INPUT_BYTES} bytes")
|
||||
@@ -659,16 +678,24 @@ def render_settings(settings: dict[str, Any]) -> str:
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
# What ends a line for str.splitlines(), which the rewrites here split on, but not for
|
||||
# awg-quick's `read -r`, plus NUL, which bash drops from what it reads: "PostUp \f= cmd"
|
||||
# or "Post\0Up = cmd" would reach awg-quick as a hook no check here saw. A lone CR too;
|
||||
# a CRLF line end is fine. No real configuration has any of them.
|
||||
_AMBIGUOUS_CHARACTERS = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x85\u2028\u2029]|\r(?!\n)")
|
||||
|
||||
|
||||
def validate_config(config: str, allow_hooks: bool = False) -> None:
|
||||
if _AMBIGUOUS_CHARACTERS.search(config):
|
||||
raise ConfigError("configuration contains control characters")
|
||||
lowered = config.lower()
|
||||
if "[interface]" not in lowered or "[peer]" not in lowered:
|
||||
raise ConfigError("configuration requires [Interface] and [Peer] sections")
|
||||
if not allow_hooks:
|
||||
for line in config.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
|
||||
continue
|
||||
key = stripped.split("=", 1)[0].strip().lower()
|
||||
# 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()
|
||||
if key in FORBIDDEN_WG_QUICK_KEYS:
|
||||
raise ConfigError(
|
||||
f"configuration contains privileged wg-quick directive '{key}'; "
|
||||
@@ -875,6 +902,9 @@ def main() -> int:
|
||||
config = _set_interface_value(config, "FwMark", str(args.fwmark))
|
||||
if args.resolve_endpoints:
|
||||
config = resolve_endpoints(config)
|
||||
if args.wireproxy is None:
|
||||
# What awg-quick runs, checked again after the rewrites above.
|
||||
validate_config(config, bool(manifest.get("allowConfigHooks", False)))
|
||||
write_private(args.output, config)
|
||||
except (ConfigError, KeyError, OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
parser.exit(1, f"amneziawg-config: {exc}\n")
|
||||
|
||||
@@ -229,17 +229,27 @@ def build_outbound(
|
||||
MAX_SUBSCRIPTION_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
class _HttpOnlyRedirects(urllib.request.HTTPRedirectHandler):
|
||||
"""Redirects stay on http and https: urllib's own also follows one to ftp:."""
|
||||
|
||||
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://")
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
# urlopen also speaks file:, ftp: and data:. This runs as root over a URL that
|
||||
# reaches it from a group-writable spool, so only the two a subscription is
|
||||
# ever served over.
|
||||
# ever served over, redirects included.
|
||||
if urllib.parse.urlsplit(url).scheme not in ("http", "https"):
|
||||
raise ValueError("subscription URL must be http:// or https://")
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
opener = urllib.request.build_opener(_HttpOnlyRedirects)
|
||||
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")
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -342,6 +343,46 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
||||
validate_config(hooked)
|
||||
validate_config(hooked, allow_hooks=True)
|
||||
|
||||
def test_hooks_hidden_from_python_line_splitting_rejected(self):
|
||||
# Each is one line to awg-quick, whose key comes out as PostUp; splitlines()
|
||||
# would cut it before the "=", or a later rewrite would turn it into two lines.
|
||||
for hidden in (
|
||||
"PostUp \f= touch /root/pwned",
|
||||
"PostUp \v= touch /root/pwned",
|
||||
"PostUp \x1c= touch /root/pwned",
|
||||
"PostUp \u2028= touch /root/pwned",
|
||||
"PostUp \r= touch /root/pwned",
|
||||
"Post\0Up = touch /root/pwned",
|
||||
"MTU = 1280\fPostUp = touch /root/pwned",
|
||||
):
|
||||
with self.subTest(hidden=hidden), self.assertRaises(ConfigError):
|
||||
validate_config(BASE_CONFIG.replace("Address =", f"{hidden}\nAddress ="))
|
||||
# A line without "=" is still a PostUp to awg-quick.
|
||||
with self.assertRaisesRegex(ConfigError, "privileged"):
|
||||
validate_config(BASE_CONFIG.replace("Address =", "PostUp\nAddress ="))
|
||||
validate_config(BASE_CONFIG.replace("\n", "\r\n"))
|
||||
|
||||
def test_shared_directory_refuses_symlinks_and_fifos(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
directory = Path(directory)
|
||||
secret = directory / "secret.conf"
|
||||
secret.write_text(BASE_CONFIG)
|
||||
spool = directory / "spool"
|
||||
spool.mkdir()
|
||||
(spool / "link.conf").symlink_to(secret)
|
||||
os.mkfifo(spool / "fifo.conf")
|
||||
(spool / "plain.conf").write_text(BASE_CONFIG)
|
||||
# Private: a declared secret may well be a symlink (sops, agenix).
|
||||
spool.chmod(0o700)
|
||||
self.assertEqual(amneziawg_config._read_limited(str(spool / "link.conf")), BASE_CONFIG)
|
||||
# Group-writable, as the runtime spool is.
|
||||
spool.chmod(0o770)
|
||||
with self.assertRaises(OSError):
|
||||
amneziawg_config._read_limited(str(spool / "link.conf"))
|
||||
with self.assertRaisesRegex(ConfigError, "not a regular file"):
|
||||
amneziawg_config._read_limited(str(spool / "fifo.conf"))
|
||||
self.assertEqual(amneziawg_config._read_limited(str(spool / "plain.conf")), BASE_CONFIG)
|
||||
|
||||
def test_declarative_awg3_and_secret_files(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
directory = Path(directory)
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import http.server
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
from proxy_parsing import (
|
||||
decode_subscription,
|
||||
fetch_raw,
|
||||
@@ -43,6 +46,26 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "http"):
|
||||
fetch_raw(url)
|
||||
|
||||
def test_fetch_refuses_redirects_off_http(self):
|
||||
# A subscription server may redirect; not to a local file or FTP, which root would fetch.
|
||||
class Redirect(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "ftp://127.0.0.1/sub" if self.path == "/ftp" else "file:///etc/passwd")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Redirect)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.shutdown)
|
||||
base = f"http://127.0.0.1:{server.server_port}"
|
||||
# urllib refuses file: itself, and follows ftp: unless told not to.
|
||||
with self.assertRaises(urllib.error.HTTPError):
|
||||
fetch_raw(f"{base}/file")
|
||||
with self.assertRaisesRegex(ValueError, "redirected off http"):
|
||||
fetch_raw(f"{base}/ftp")
|
||||
|
||||
def test_base64_payload_mixed_protocols(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
|
||||
|
||||
Reference in new issue
Block a user