feat(proxy-client): добавлены профили и системная служба

Добавлены независимые пользовательские профили, их выбор в Bash-командах и явная установка службы systemd. Инструкции размещены в README пакета.

Проверка: 67 тестов на Python 3.8 и 3.14, shell-наборы и интеграция Bash с CLI. Загрузка ОС и восстановление настоящей службы требуют отдельной проверки.
This commit is contained in:
ddadmin committed 2026-11-02 22:16:12 +01:00
1 parent b36ce50e12
commit b34eb6ac4c
9 files changed
+835 -23

No files matched your search

+212 -8
View File
@@ -120,15 +120,28 @@ class VlessProfile:
return self.query["security"]
SELECTED_PROFILE = "default"
SYSTEM_MODE = False
SYSTEM_CONFIG = Path("/etc/proxy-client")
SYSTEM_RUNTIME = Path("/run/proxy-client")
SYSTEM_XRAY = Path("/usr/local/lib/proxy-client/xray")
def config_home():
if SYSTEM_MODE:
return SYSTEM_CONFIG
root = os.environ.get("XDG_CONFIG_HOME")
return (Path(root).expanduser() if root else Path.home() / ".config") / "proxy-client"
base = (Path(root).expanduser() if root else Path.home() / ".config") / "proxy-client"
return base if SELECTED_PROFILE == "default" else base / "profiles" / SELECTED_PROFILE
def state_home():
if SYSTEM_MODE:
return SYSTEM_RUNTIME
root = os.environ.get("XDG_STATE_HOME")
base = Path(root).expanduser() if root else Path.home() / ".local/state"
return base / "proxy-client"
base = base / "proxy-client"
return base if SELECTED_PROFILE == "default" else base / "profiles" / SELECTED_PROFILE
def state_path():
@@ -277,7 +290,7 @@ def write_private_json(path, value):
def load_profile(path):
# Права проверяем у конечного файла: у симлинка они ничего не значат.
resolved = path.expanduser().resolve(strict=True)
if resolved.stat().st_mode & 0o077:
if resolved.stat().st_mode & (0o037 if SYSTEM_MODE else 0o077):
raise ProxyError(
"файл профиля {} доступен другим пользователям; выполните: chmod 600 {}".format(
resolved, shlex.quote(str(resolved))
@@ -532,7 +545,7 @@ def build_xray_config(profile, local_address, local_port):
def resolve_xray():
found = shutil.which("xray")
found = str(SYSTEM_XRAY) if SYSTEM_MODE else shutil.which("xray")
if found is None:
raise ProxyError("xray не найден в PATH; установите его: proxy-client install")
return str(Path(found).resolve(strict=True))
@@ -907,7 +920,11 @@ def run_managed_xray(config, profile_file):
# SIGTERM (от proxy-client stop) и SIGHUP обрабатываем как Ctrl+C.
signal.signal(signal.SIGTERM, interrupt)
signal.signal(signal.SIGHUP, interrupt)
child = subprocess.Popen([executable, "run", "-c", str(generated_config_path())])
child = subprocess.Popen(
[executable, "run", "-c", str(generated_config_path())],
stdout=subprocess.DEVNULL if SYSTEM_MODE else None,
stderr=subprocess.DEVNULL if SYSTEM_MODE else None,
)
write_private_json(
state_path(),
{
@@ -923,9 +940,15 @@ def run_managed_xray(config, profile_file):
):
raise ProxyError("Xray не открыл локальный порт {}".format(config.port))
diagnose_ip(config)
if SYSTEM_MODE:
stop_hint = "sudo systemctl stop proxy-client"
elif SELECTED_PROFILE == "default":
stop_hint = "Ctrl+C или proxy-client stop"
else:
stop_hint = "Ctrl+C или proxy-client --profile {} stop".format(SELECTED_PROFILE)
print(
"Управляемый Xray работает на {}:{}; остановка: Ctrl+C или proxy-client stop".format(
config.address, config.port
"Управляемый Xray работает на {}:{}; остановка: {}".format(
config.address, config.port, stop_hint
),
flush=True,
)
@@ -963,12 +986,173 @@ def command_stop():
return 0
SERVICE_UNIT = """# Managed by proxy-client
[Unit]
Description=Proxy client (Xray)
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
User=proxy-client
Group=proxy-client
RuntimeDirectory=proxy-client
RuntimeDirectoryMode=0700
UMask=0077
ExecStart=/usr/local/lib/proxy-client/proxy-client service run
Restart=on-failure
RestartSec=5
TimeoutStopSec=15
StandardOutput=journal
StandardError=journal
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
[Install]
WantedBy=multi-user.target
"""
def report_journal_storage(root):
# Приоритет каталогов соответствует journald.conf; одноимённый drop-in
# из /etc перекрывает поставляемый системой файл.
directories = ["usr/lib/systemd", "usr/local/lib/systemd", "run/systemd", "etc/systemd"]
main = next((root / directory / "journald.conf"
for directory in reversed(directories)
if (root / directory / "journald.conf").exists()), None)
dropins = {}
for directory in directories:
for path in (root / directory / "journald.conf.d").glob("*.conf"):
dropins[path.name] = path
storage = None
for path in ([main] if main else []) + [dropins[name] for name in sorted(dropins)]:
section = ""
for line in path.read_text().splitlines():
line = line.strip()
if line.startswith("["):
section = line
elif section == "[Journal]" and re.match(r"Storage\s*=", line):
storage = line.split("=", 1)[1].strip() or None
if storage is None:
print("journald: Storage не задан; сохранение журнала зависит от сборки systemd. "
"Проверьте journalctl --list-boots после перезагрузки.")
return
persistent = storage == "persistent" or (
storage == "auto" and (root / "var/log/journal").is_dir())
print("journald: Storage={}; журнал {} между загрузками (по конфигурации).".format(
storage, "сохраняется" if persistent else "не сохраняется"))
def service_install(args):
source = Path(args.config_dir)
xray = Path(args.xray)
root = Path(args.root) if args.root else Path("/")
if not all(path.is_absolute() for path in (source, xray, root)):
raise ProxyError("config-dir, xray и root должны быть абсолютными путями")
if args.root and (args.enable or args.start):
raise ProxyError("--root несовместим с --enable и --start")
if not args.root and os.geteuid() != 0:
raise ProxyError("системная установка требует root")
settings = root / "etc/proxy-client"
# При обновлении служба уже имеет собственные настройки вне HOME.
if not (settings / "config").exists():
config = parse_config((source / "config").read_text(encoding="utf-8"))
if config.proxy_type != "xray" or not ipaddress.ip_address(config.address).is_loopback:
raise ProxyError("службе нужен type=xray и loopback-адрес")
if not (settings / "default.url").exists():
load_profile(source / "default.url")
check_xray_version(str(xray))
files = {
"usr/local/lib/proxy-client/proxy-client": (Path(__file__).read_bytes(), 0o755),
"usr/local/lib/proxy-client/xray": (xray.read_bytes(), 0o755),
"etc/systemd/system/proxy-client.service": (SERVICE_UNIT.encode(), 0o644),
"usr/lib/sysusers.d/proxy-client.conf": (
b'u proxy-client - "Proxy client" /nonexistent /usr/sbin/nologin\n', 0o644),
}
manifest = root / "usr/local/lib/proxy-client/installed.json"
settings = root / "etc/proxy-client"
# До любой записи проверяем все назначения и компоненты пути.
targets = [root / name for name in files] + [
manifest, settings, settings / "config", settings / "default.url"]
for target in targets:
if any(part.is_symlink() for part in [target, *target.parents]):
raise ProxyError("установка через симлинк запрещена: {}".format(target))
owned = json.loads(manifest.read_text()) if manifest.exists() else {}
for name in files:
target = root / name
if target.exists() and (
not target.is_file() or
owned.get(name) != hashlib.sha256(target.read_bytes()).hexdigest()
):
raise ProxyError("чужой или изменённый файл: {}".format(target))
if not manifest.exists() and settings.exists():
raise ProxyError("чужой каталог настроек: {}".format(settings))
for name, (data, mode) in files.items():
target = root / name
target.parent.mkdir(parents=True, exist_ok=True)
# Атомарная замена позволяет обновить бинарник работающей службы,
# не меняя уже запущенный процесс.
descriptor, temporary = tempfile.mkstemp(prefix=".install-", dir=str(target.parent))
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(data)
os.fchmod(stream.fileno(), mode)
os.replace(temporary, str(target))
finally:
if os.path.exists(temporary):
os.unlink(temporary)
settings = root / "etc/proxy-client"
settings.mkdir(parents=True, exist_ok=True)
settings.chmod(0o750)
for name in ("config", "default.url"):
target = settings / name
if not target.exists():
descriptor = os.open(str(target), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o640)
with os.fdopen(descriptor, "wb") as stream:
stream.write((source / name).read_bytes())
os.fchmod(stream.fileno(), 0o640)
manifest.write_text(json.dumps({
name: hashlib.sha256(data).hexdigest() for name, (data, _) in files.items()
}))
manifest.chmod(0o644)
if not args.root:
import grp
subprocess.run(["systemd-sysusers", "/usr/lib/sysusers.d/proxy-client.conf"], check=True)
gid = grp.getgrnam("proxy-client").gr_gid
for path in (settings, settings / "config", settings / "default.url"):
os.chown(str(path), 0, gid)
subprocess.run(["systemctl", "daemon-reload"], check=True)
if args.enable:
subprocess.run(["systemctl", "enable", "proxy-client.service"], check=True)
if args.start:
subprocess.run(["systemctl", "start", "proxy-client.service"], check=True)
print("Служба установлена. Конфигурация сохранена; автоматического перезапуска нет.")
report_journal_storage(root)
return 0
def build_parser():
parser = argparse.ArgumentParser(
prog="proxy-client",
description="Безопасный запуск команд через явно настроенный прокси.",
)
parser.add_argument("--profile", default="default", help="имя пользовательского профиля")
subparsers = parser.add_subparsers(dest="subcommand")
service = subparsers.add_parser("service", help="системная служба")
actions = service.add_subparsers(dest="service_action", required=True)
serve = actions.add_parser("run", help="запуск из systemd")
serve.add_argument("--config-dir", default="/etc/proxy-client")
serve.add_argument("--runtime-dir", default="/run/proxy-client")
serve.add_argument("--xray", default="/usr/local/lib/proxy-client/xray")
setup = actions.add_parser("install", help="установить системную службу")
setup.add_argument("--config-dir", required=True)
setup.add_argument("--xray", required=True)
setup.add_argument("--root", help="изолированный корень без systemctl")
setup.add_argument("--enable", action="store_true")
setup.add_argument("--start", action="store_true")
install_parser = subparsers.add_parser("install", help="установить проверенный Xray")
install_parser.add_argument(
"--replace", action="store_true", help="заменить существующий ~/.local/bin/xray"
@@ -984,6 +1168,7 @@ def build_parser():
def main():
global SELECTED_PROFILE, SYSTEM_MODE, SYSTEM_CONFIG, SYSTEM_RUNTIME, SYSTEM_XRAY
parser = build_parser()
arguments = parser.parse_args()
if arguments.subcommand is None:
@@ -992,6 +1177,25 @@ def main():
return 2
try:
if arguments.subcommand == "service":
if arguments.profile != "default":
raise ProxyError("service не использует пользовательские профили")
if arguments.service_action == "install":
return service_install(arguments)
SYSTEM_MODE = True
SYSTEM_CONFIG = Path(arguments.config_dir)
SYSTEM_RUNTIME = Path(arguments.runtime_dir)
SYSTEM_XRAY = Path(arguments.xray)
if not all(p.is_absolute() for p in (SYSTEM_CONFIG, SYSTEM_RUNTIME, SYSTEM_XRAY)):
raise ProxyError("системные пути должны быть абсолютными")
if not (SYSTEM_CONFIG / "config").is_file():
raise ProxyError("нет системного config")
return command_start(load_config(), None)
SELECTED_PROFILE = arguments.profile
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", SELECTED_PROFILE):
raise ProxyError("недопустимое имя профиля")
if SELECTED_PROFILE != "default" and not (config_home() / "config").is_file():
raise ProxyError("неизвестный профиль: {}".format(SELECTED_PROFILE))
if arguments.subcommand == "install":
return command_install(arguments.replace)
if arguments.subcommand == "stop":
@@ -1005,7 +1209,7 @@ def main():
return command_run(config, arguments.arguments)
if arguments.subcommand == "start":
return command_start(config, arguments.profile_file)
except (ProxyError, OSError) as error:
except (ProxyError, OSError, ValueError, subprocess.CalledProcessError) as error:
sys.stderr.write("Ошибка: {}\n".format(error))
return 1
return 2