diff --git a/ops/audits/CF-TUNNEL-SYNC-2026-11-16.md b/ops/audits/CF-TUNNEL-SYNC-2026-11-16.md new file mode 100644 index 0000000..36133e3 --- /dev/null +++ b/ops/audits/CF-TUNNEL-SYNC-2026-11-16.md @@ -0,0 +1,71 @@ +# Быстрый Cloudflare-туннель: автообновление (16.11.2026) + +## Зачем + +Быстрый туннель (`*.trycloudflare.com`) работает в РФ стабильно — за сутки +**0 сбоев из 120**, тогда как прямой Reality/WS глохнет в 52% проверок +(TLS к нашему IP режется, TCP проходит). + +Но у быстрого туннеля есть недостаток: **URL меняется при каждом +перезапуске**. Раньше клиентские профили приходилось править руками. + +## Что сделано + +### 1. `cf_tunnel_sync.py` (ops/scripts) + +За один прогон: + +1. читает текущий URL туннеля с VDS **через WireGuard** (`10.88.0.1`) — + публичный SSH из дома блокируется DPI, WG работает; +2. сравнивает с `ops/vpn/cf-host.txt`; +3. при смене — обновляет `cf-host.txt` и **6 клиентских профилей**: + добавляет/обновляет outbound `proxy-cf` (VLESS+WS+TLS, путь `/buryan-cf`), + включает его в `observatory` и балансировщик `auto` (leastPing); +4. проверяет туннель снаружи (`/buryan-cf` → 400 — ждёт WebSocket); +5. при изменениях уведомляет в ALERT. + +### 2. Задание Hermes + +`cf-tunnel-sync` — каждые 5 минут. + +### 3. Проверка ротации (реальный тест) + +``` +до: https://eden-processing-hit-latino.trycloudflare.com +restart cf-tunnel на VDS +после: https://enjoyed-architects-bidder-deluxe.trycloudflare.com + +синхронизатор: URL изменился: True +профилей обновлено: 6 +туннель /buryan-cf: 400 +ALERT: «CF-туннель: новый адрес» (17:12) +``` + +## Что это даёт клиенту + +В профиле теперь 4 канала: `proxy-tls`, `proxy-xhttp`, `proxy-reality`, +`proxy-cf`. Балансировщик `auto` (leastPing) сам выбирает живой: + +* когда прямой канал работает — идёт через него (быстрее); +* когда DPI режет TLS к нашему IP — проба через CF жива, и трафик уходит + через Cloudflare (медленнее ~500 мс, но работает). + +## Ограничения (честно) + +* URL всё ещё меняется при **перезапуске туннеля**; синхронизация + подхватывает за ≤5 минут, но клиенту нужен свежий профиль. + Профили лежат в `ops/vpn/build/profiles/` (git игнорирует их — там ключи). +* Cloudflare в РФ может душиться по скорости: +500 мс, быстрый туннель + без гарантий. Это **запасной** канал, не основной. +* Раздача профилей пока ручная (файл). При желании могу сделать отправку + обновлённого профиля владельцу в Matrix при смене URL. + +## Ловушки + +| Ловушка | Что было | +|---|---| +| SSH дом→VDS | DPI рвёт `banner exchange`; туннель и xray живут на VDS — доступ только по WG `10.88.0.1` | +| путь конфига xray | на VDS `/usr/local/etc/xray/config.json`, не `/etc/xray` | +| UUID CF-инбаунда | читается скриптом на VDS (`/root/cf-uuid.py`), кэшируется в `/root/.cf-uuid` | +| профили под git | `.gitignore` — ключи не попадут в репозиторий | +| быстрый туннель | перезапуск = новый URL; без синхронизации клиенты ломаются | diff --git a/ops/automations/registry.yaml b/ops/automations/registry.yaml index 45c2a11..74e00d7 100644 --- a/ops/automations/registry.yaml +++ b/ops/automations/registry.yaml @@ -1,10 +1,10 @@ # Реестр автоматизаций Buryans Hub -# Сгенерировано: 2026-11-16 19:55 (ops/scripts/build_automations_registry.py) -total: 162 +# Сгенерировано: 2026-11-16 20:13 (ops/scripts/build_automations_registry.py) +total: 163 by_source: cron.d: 49 crontab: 15 - hermes: 55 + hermes: 56 systemd: 43 items: - {"source": "crontab", "line": "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"} @@ -169,3 +169,4 @@ items: - {"source": "hermes", "job": "check-certs", "schedule": "daily 08:30", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/check_certs.py"} - {"source": "hermes", "job": "morning-digest", "schedule": "daily 08:00", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/morning_digest.py"} - {"source": "hermes", "job": "selfcheck-platform", "schedule": "every 21600s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/selfcheck_platform.py"} +- {"source": "hermes", "job": "cf-tunnel-sync", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/cf_tunnel_sync.py"} diff --git a/ops/scripts/cf_tunnel_sync.py b/ops/scripts/cf_tunnel_sync.py new file mode 100755 index 0000000..7521cec --- /dev/null +++ b/ops/scripts/cf_tunnel_sync.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Синхронизация быстрого Cloudflare-туннеля (URL меняется при перезапуске). + +Что делает за один прогон: + 1. читает текущий URL туннеля с VDS через WireGuard (10.88.0.1); + 2. сравнивает с ops/vpn/cf-host.txt; + 3. при смене — обновляет cf-host.txt и клиентские профили: + добавляет/обновляет отк��ут proxy-cf (VLESS+WS+TLS к *.trycloudflare.com), + включает его в observatory и balancer — переключение автоматическое; + 4. проверяет туннель снаружи (path /buryan-cf должен отвечать 400); + 5. при изменениях уведомляет в ALERT. + +Запуск: python3 cf_tunnel_sync.py [--dry-run] +Hermes: cf-tunnel-sync каждые 5 минут. +""" +import glob +import json +import os +import re +import shutil +import subprocess +import sys +import time + +REPO = "/root/buryan-infra" +CF_HOST_FILE = REPO + "/ops/vpn/cf-host.txt" +PROFILES = REPO + "/ops/vpn/build/profiles/vpn-*.json" +STATE = "/var/lib/cf-tunnel/last-url" +UUID_FILE = "/root/.cf-uuid" +VDS = "10.88.0.1" +PATH = "/buryan-cf" + + +def sh(cmd, timeout=40): + r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) + return ((r.stdout or "") + (r.stderr or "")).strip() + + +def vds(cmd): + return sh("ssh -o BatchMode=yes -o ConnectTimeout=8 root@%s '%s'" % (VDS, cmd.replace("'", "'\\''")), timeout=45) + + +def get_url(): + out = vds("journalctl -u cf-tunnel -n 400 --no-pager 2>/dev/null | " + "grep -oE 'https://[a-z0-9-]+\\.trycloudflare\\.com' | tail -1") + m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", out) + return m.group(0) if m else "" + + +def get_uuid(): + try: + u = open(UUID_FILE, encoding="utf-8").read().strip() + if re.match(r"^[0-9a-f-]{36}$", u): + return u + except Exception: + pass + out = vds("python3 /root/cf-uuid.py") + m = re.search(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", out) + if m: + try: + open(UUID_FILE, "w", encoding="utf-8").write(m.group(0)) + os.chmod(UUID_FILE, 0o600) + except Exception: + pass + return m.group(0) + return "" + + +def make_outbound(host, uuid): + return { + "tag": "proxy-cf", + "protocol": "vless", + "settings": {"vnext": [{"address": host, "port": 443, + "users": [{"id": uuid, "encryption": "none"}]}]}, + "streamSettings": { + "network": "ws", + "security": "tls", + "tlsSettings": {"serverName": host, "fingerprint": "firefox", + "allowInsecure": False}, + "wsSettings": {"path": PATH}, + }, + } + + +def update_profile(path, host, uuid, dry=False): + d = json.load(open(path, encoding="utf-8")) + ob = next((o for o in d.get("outbounds", []) if o.get("tag") == "proxy-cf"), None) + changed = False + if ob is None: + new = make_outbound(host, uuid) + outs = d.get("outbounds", []) + idx = next((i for i, o in enumerate(outs) if o.get("tag") == "direct"), len(outs)) + outs.insert(idx, new) + d["outbounds"] = outs + changed = True + else: + vn = (ob.get("settings") or {}).get("vnext") or [{}] + if vn[0].get("address") != host: + vn[0]["address"] = host + changed = True + tls = (ob.get("streamSettings") or {}).get("tlsSettings") or {} + if tls.get("serverName") != host: + tls["serverName"] = host + ob["streamSettings"]["tlsSettings"] = tls + changed = True + + obs = d.setdefault("observatory", {}) + sel = obs.setdefault("subjectSelector", []) + if "proxy-cf" not in sel: + sel.append("proxy-cf") + changed = True + for b in (d.get("routing") or {}).get("balancers") or []: + s = b.setdefault("selector", []) + if "proxy-cf" not in s: + s.append("proxy-cf") + changed = True + if changed and not dry: + shutil.copy2(path, path + ".bak-cf") + json.dump(d, open(path, "w", encoding="utf-8"), ensure_ascii=False, indent=1) + return changed + + +def notify(title, text, priority="high"): + try: + subprocess.run(["/usr/bin/python3", "/opt/buryan-hub/scripts/notify.py", + "--priority", priority, "--title", title, text], + capture_output=True, text=True, timeout=120) + except Exception: + pass + + +def main(): + dry = "--dry-run" in sys.argv + url = get_url() + if not url: + notify("CF-туннель", "Не удалось получить URL туннеля с VDS (WG).", "high") + print("URL не получен") + return 1 + host = url.replace("https://", "") + + try: + old = open(CF_HOST_FILE, encoding="utf-8").read().strip() + except Exception: + old = "" + changed_url = old != url + + uuid = get_uuid() + + print("URL:", url, "| изменился:", changed_url, "| uuid:", "есть" if uuid else "НЕТ") + if changed_url and not dry: + open(CF_HOST_FILE, "w", encoding="utf-8").write(url + "\n") + + touched = [] + if uuid: + for p in sorted(glob.glob(PROFILES)): + try: + if update_profile(p, host, uuid, dry): + touched.append(os.path.basename(p)) + except Exception as e: + print(" ошибка профиля", p, e) + print("профилей обновлено:", len(touched), touched[:6]) + + # проверка снаружи: /buryan-cf без WebSocket → 400 + code = sh("curl -s -o /dev/null -w '%%{http_code}' -m 12 '%s%s'" % (url, PATH), timeout=20) + print("туннель /buryan-cf:", code) + healthy = code in ("400", "426") + + if changed_url and not dry: + try: + os.makedirs(os.path.dirname(STATE), exist_ok=True) + open(STATE, "w", encoding="utf-8").write(url) + except Exception: + pass + if touched: + notify("CF-туннель: новый адрес", + "URL: %s\nПрофилей обновлено: %d\nПроверка: %s" + % (url, len(touched), code)) + if not healthy: + notify("CF-туннель не отвечает", "URL: %s, код: %s" % (url, code), "high") + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ops/vpn/cf-host.txt b/ops/vpn/cf-host.txt index 37b7375..b81a5fb 100644 --- a/ops/vpn/cf-host.txt +++ b/ops/vpn/cf-host.txt @@ -1 +1 @@ -https://eden-processing-hit-latino.trycloudflare.com +https://enjoyed-architects-bidder-deluxe.trycloudflare.com