From 3c7d575992b03668da5844924ab29156716864b1 Mon Sep 17 00:00:00 2001 From: Sam Latsin Date: Thu, 15 Oct 2026 12:54:36 +0300 Subject: [PATCH] Fixed ovpn fingerprint for connect app --- README.md | 78 +- router/bmstu-otp.sh | 73 +- router/bmstu.env.example | 6 +- router/mihomo-kit.sh | 30 +- tools/core/openvpn-connect-mimic.patch | 1436 ++++++++++++++++++++++++ 5 files changed, 1589 insertions(+), 34 deletions(-) create mode 100644 tools/core/openvpn-connect-mimic.patch diff --git a/README.md b/README.md index ce957c7..c848c65 100644 --- a/README.md +++ b/README.md @@ -71,12 +71,48 @@ bmstu-otp.sh status cron поднять его снова, и убирает его подсети (`OVPN_ROUTES`) из маршрутизации: они лежат в rule-provider `bmstu-routes`, который `off` очищает, а `on` возвращает, без перезапуска nikki. Адреса BMSTU тогда идут по обычным правилам, как любые другие сайты: публичные открываются, -внутренние (`172.x`) — нет. mihomo не отправляет -серверу EXIT, поэтому сервер держит старую сессию до своего `ping-restart` — до ~5 минут, -потом можно подключаться с другого устройства. +внутренние (`172.x`) — нет. Ядро kit при закрытии туннеля отправляет серверу EXIT, как +Connect, и сессия освобождается за секунды — можно сразу подключаться с другого устройства. +С другим ядром EXIT не уходит, и сервер держит сессию до своего `ping-restart` (~5 минут). На `whitelist` OpenVPN идёт через группу `OVPN-EXIT` — один раз выбрать в дашборде RU-ноду. +### OpenVPN под видом OpenVPN Connect + +Для сервера BMSTU роутер выглядит как OpenVPN Connect 3.7.1 (5558) на macOS. Обычный +mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=22`, своя строка опций), и в +логах сервера это видно. Маскировку дают ядро kit (правка +`tools/core/openvpn-connect-mimic.patch`) и `bmstu-otp.sh`, который пишет в провайдер +поля `options-string` и `peer-info-raw`. + +Совпадает с Connect: +- строка опций (`V4,dev-type tun,link-mtu 1541,…,cipher BF-CBC,auth SHA1,…`) и peer-info + (`IV_VER=3.11.1`, `IV_PLAT=mac`, `IV_PROTO=8094`, `IV_GUI_VER=OCmacOS_3.7.1-5558`, …) — + те же строки в том же порядке, что в логе Connect; +- протокол: в ответ на `IV_PROTO=8094` сервер включает `tls-ekm` (ключи из TLS-экспортёра), + `dyn-tls-crypt` (свой tls-crypt-ключ для rekey) и `aead-epoch` (формат данных OpenVPN 2.7), + и ядро kit их поддерживает; +- пароль в формате `SCRV1`, как отправляет Connect при `static-challenge`; +- `ping 60`, `ping-restart 300` — то, что присылает сервер; +- туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу + при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo + пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро через 2 с + переподключается само, с auth-token сессии вместо пароля и OTP. Если сервер токен не + принял (AUTH_FAILED), ядро больше не пробует — как Connect, который тогда просит новый + OTP, — и туннель поднимает cron (`bmstu-otp.sh check`) со свежим OTP; +- при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT + (`cc-exit`) и сразу освобождает сессию. + +Отличается только TLS-рукопожатие управляющего канала: его делает Go (`crypto/tls`), а не +OpenSSL, поэтому набор шифров и расширений в ClientHello другой (JA3/JA4). Это видно при +разборе трафика, в логах сервера — нет. + +Без ядра kit (`stock`, `official`) эти поля игнорируются, и сервер снова видит mihomo. +Выключить маскировку: `OVPN_MIMIC=mihomo` в `bmstu.env`. После обновления Connect — взять +новые строки `Tunnel Options` и `Sending Peer Info` из его лога +(`~/Library/Application Support/OpenVPN Connect/log/ovpn.log`) и поправить +`mimic_connect_mac` в `router/bmstu-otp.sh`. + ## Обслуживание ```sh @@ -152,12 +188,13 @@ MagicDNS (админка Tailscale → DNS). | Фикс | Зачем | |---|---| -| ядро mihomo `v1.19.32` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие | +| ядро kit `v1.19.32-ts2` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие; Tailscale через `dialer-proxy` и маскировка OpenVPN — только в ядре kit | | `TS_FORCE_NOISE_443=true` в `/etc/init.d/nikki` | провайдер ломает control-соединение Tailscale на порту 80, вход зависает | | убрать `100.64.0.0/10`, `172.16.0.0/12` из `nikki.proxy.reserved_ip` | иначе nikki пускает Tailscale и внутренние сети BMSTU мимо mihomo | | `ts.net` в `rebind_domain` dnsmasq | иначе защита от DNS rebinding отбрасывает адреса 100.x тейлнета | | metric: `wan`/`wan6` — 10, остальные выходы (модемы, wifi-клиент) — 50, 60, … (если не заданы руками) | при живом проводе интернет идёт по проводу, модемы — запасные | -| cron `bmstu-otp.sh check` раз в минуту | поднимает OpenVPN со свежим OTP, если туннель упал | +| cron `bmstu-otp.sh check` раз в минуту | поднимает OpenVPN со свежим OTP, если туннель упал и токен сессии не принят | +| `bmstu-otp.sh write` в `/etc/init.d/nikki` | провайдер OpenVPN со свежим OTP перед стартом mihomo: ядро kit подключается сразу | | переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` | ## Телефон (FlClash) @@ -200,15 +237,14 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`, [MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit -ставит своё ядро `v1.19.32-ts1` — официальный v1.19.32 с правкой +ставит своё ядро `v1.19.32-ts2` — официальный v1.19.32 с правкой `tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает. -Сборка ядра: `tools/core/build.sh v1.19.32 ts1` → `tools/core/dist/*.gz` → релиз -`core-v1.19.32-ts1` в репозитории kit (`MIHOMO_VERSION` / `MIHOMO_BASE` в -`router/mihomo-kit.sh`). Если ядро не скачалось, `fix` оставляет текущее и запускает -nikki. +Вторая правка того же ядра — `tools/core/openvpn-connect-mimic.patch`, маскировка OpenVPN +под OpenVPN Connect (см. «OpenVPN под видом OpenVPN Connect»). Как собрать — в «Разработке». +Если ядро не скачалось, `fix` оставляет текущее и запускает nikki. Какое ядро на конкретном роутере — селект в «Обслуживании» (или `mihomo-kit.sh core stock|official|kit`), выбор хранится в `/etc/nikki/kit.env` как `CORE=`: @@ -226,7 +262,7 @@ nikki. - **OpenVPN** `tunnel did not come up`: `bmstu-otp.sh debug` покажет настоящую ошибку. `read hard reset response` — до сервера не доходят пакеты (zeroblock, правило для IP - сервера); `AUTH_FAILED` — формат пароля (`PASS_FORMAT` в `bmstu.env`, сейчас `otp-last`). + сервера); `AUTH_FAILED` — формат пароля (`PASS_FORMAT` в `bmstu.env`, сейчас `scrv1`, как у OpenVPN Connect). - **Tailscale** без ссылки: `mihomo-kit.sh ts-login`. Ссылка пишется в лог один раз и только на уровне `info` (у nikki по умолчанию `warning`), а неудачный первый запуск оставляет в `/etc/nikki/run/tailscale` состояние, с которым нода молчит — команда @@ -263,6 +299,26 @@ tests/fixtures/ профили для test.sh (фиктивные секре `openvpn`, `tailscale`, `ts_exit`, `hy2`. Значения по умолчанию — `set_defaults` в `router/mihomo-kit.sh` и `DEFAULTS` в `web/engine.js` (держать одинаковыми). +### Ядро kit + +Официальный mihomo плюс правки из `tools/core/*.patch` (Tailscale через `dialer-proxy`, +маскировка OpenVPN). Нужны git и Go. + +1. `tools/core/build.sh v1.19.32 ts2` — клонирует mihomo `v1.19.32`, накладывает патчи и + собирает `tools/core/dist/mihomo-linux--v1.19.32-ts2.gz` для arm64, amd64, armv7, + mips-softfloat, mipsle-softfloat. +2. В репозитории kit создать релиз с тегом `core-v1.19.32-ts2` и приложить все `.gz`, не + переименовывая: роутер качает `$MIHOMO_BASE/mihomo-linux--<версия>.gz`. +3. `CORE_KIT` в `router/mihomo-kit.sh` — та же версия. Пушить кит только после релиза: + роутеры берут кит из `main` и иначе не найдут ядро. +4. На роутере: `mihomo-kit.sh update` (новый кит; ядро меняется, если версия другая), + `mihomo-kit.sh fix` (ядро и init-скрипт nikki: свежий OTP перед стартом mihomo), затем + `bmstu-otp.sh refresh` (провайдер OpenVPN с новыми полями). Проверить: + `mihomo-kit.sh core-info`, `bmstu-otp.sh status`. + +Новая версия mihomo или новая правка — следующий суффикс (`ts3`) в шагах 1–3. Патчи +применяются по алфавиту; если не накладываются, поправить их на новом теге. + После правки шаблонов или движка: ```sh diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh index 1dac738..edc195c 100755 --- a/router/bmstu-otp.sh +++ b/router/bmstu-otp.sh @@ -2,20 +2,24 @@ # OpenVPN (BMSTU) + TOTP for mihomo / nikki on OpenWrt. # # mihomo has no static-challenge support: the password in the proxy config is -# static, and the tunnel is started lazily on first use. This script builds the -# file proxy-provider from the .ovpn with a fresh OTP baked into the password, -# reloads the provider via the mihomo API and immediately warms the tunnel up -# (delay test) while the code is still valid. After that the server's -# auth-token (if pushed) keeps rekeys alive without an OTP. +# static. This script builds the file proxy-provider from the .ovpn with a fresh +# OTP baked into the password, reloads the provider via the mihomo API and brings +# the tunnel up while the code is still valid. After that the server's auth-token +# keeps rekeys alive without an OTP. With the kit core (auto-connect, as OpenVPN +# Connect) the tunnel comes up as soon as the provider loads, reconnects by itself +# with the auth-token, and sends the server EXIT when closed; once the token is +# rejected it waits for a provider with a fresh OTP (cron check). # # Usage: # bmstu-otp.sh otp print the current TOTP code # bmstu-otp.sh authfile print username/password lines (openvpn auth-user-pass file) # bmstu-otp.sh refresh regenerate provider with fresh OTP, reload, warm up +# bmstu-otp.sh up refresh unless the tunnel already answers +# bmstu-otp.sh write only regenerate the provider (nikki init, before mihomo starts) # bmstu-otp.sh check warm-up test; refresh only if two probes fail (cron) # bmstu-otp.sh off close the tunnel and keep it closed (BMSTU traffic goes without it); -# frees the single server session for another client -# (the server drops the old session after its ping-restart, up to ~5 min) +# frees the single server session for another client (the kit core +# sends EXIT; other cores leave it until the server's ping-restart, ~5 min) # bmstu-otp.sh on allow the tunnel again and bring it up # bmstu-otp.sh status on/off and whether the tunnel answers # bmstu-otp.sh debug show the real handshake error in the nikki log @@ -47,10 +51,17 @@ api_from_uci() { : "${CHECK_URL:=https://www.bmstu.ru}" # ms, must exceed HANDSHAKE_TIMEOUT (max 32767) : "${CHECK_TIMEOUT:=25000}" -# otp-last - (what the BMSTU server accepts) +# scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU +# profile): SCRV1:b64(pass):b64(otp) +# otp-last - (the server accepts it too) # otp-first - -# scrv1 - what openvpn sends for "static-challenge ... 1": SCRV1:b64(pass):b64(otp) -: "${PASS_FORMAT:=otp-last}" +: "${PASS_FORMAT:=scrv1}" +# client the server sees (key-method 2 options string and peer-info): +# connect-mac - OpenVPN Connect 3.7.1 (5558) for macOS, as its log shows them +# mihomo - what mihomo sends itself (IV_VER=mihomo-openvpn) +# connect-mac needs the kit core (v1.19.32-ts2+): it announces IV_PROTO=8094, and the +# server then turns on tls-ekm, dyn-tls-crypt and aead-epoch. Other cores ignore the fields. +: "${OVPN_MIMIC:=connect-mac}" : "${TOTP_DIGITS:=6}" : "${TOTP_PERIOD:=30}" # do not use a code that expires sooner than this (seconds) @@ -141,6 +152,24 @@ ovpn_block() { ovpn_opt() { awk -v k="$1" '$1 == k { $1 = ""; sub(/^ /, ""); print; exit }' "$OVPN_FILE"; } +# OpenVPN Connect 3.7.1 (5558) for macOS: "Tunnel Options" and "Sending Peer Info" from +# its log. link-mtu is openvpn3's tun-mtu + overhead of its default BF-CBC/SHA1 (+2 on TCP). +mimic_connect_mac() { + case "$1" in + tcp) p=TCPv4_CLIENT mtu=1543 ;; + *) p=UDPv4 mtu=1541 ;; + esac + echo " options-string: \"V4,dev-type tun,link-mtu $mtu,tun-mtu 1500,proto $p,cipher BF-CBC,auth SHA1,keysize 128,key-method 2,tls-client\"" + # up right away, reconnect with the auth-token, EXIT on close (kit core) + echo " auto-connect: true" + echo " peer-info-raw: |" + for l in IV_VER=3.11.1 IV_PLAT=mac IV_NCP=2 IV_TCPNL=1 IV_PROTO=8094 IV_MTU=1600 \ + IV_CIPHERS=AES-128-CBC:AES-192-CBC:AES-256-CBC:AES-128-GCM:AES-192-GCM:AES-256-GCM:CHACHA20-POLY1305 \ + IV_GUI_VER=OCmacOS_3.7.1-5558 IV_SSO=webauth,crtext IV_BS64DL=1; do + echo " $l" + done +} + yaml_str() { printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"; } write_provider() { @@ -173,9 +202,16 @@ write_provider() { # the server pushes AES-256-GCM echo " data-ciphers: [AES-256-GCM, AES-128-GCM]" [ -n "$fallback" ] && echo " data-ciphers-fallback: $fallback" - echo " ping: 10" - echo " ping-restart: 60" + # what the server pushes (and OpenVPN Connect uses); mihomo ignores pushed ping. + # A dead tunnel is noticed by the cron check sooner than by ping-restart. + echo " ping: 60" + echo " ping-restart: 300" [ "$HANDSHAKE_TIMEOUT" -gt 0 ] && echo " handshake-timeout: $HANDSHAKE_TIMEOUT" + case "$OVPN_MIMIC" in + connect-mac) mimic_connect_mac "$proto" ;; + mihomo) ;; + *) die "unknown OVPN_MIMIC=$OVPN_MIMIC" ;; + esac for t in ca cert key tls-crypt tls-auth; do body=$(ovpn_block "$t") [ -n "$body" ] && printf ' %s: |\n%s\n' "$t" "$body" @@ -258,6 +294,17 @@ case "${1:-}" in # auth-user-pass file for testing with the real openvpn client authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;; refresh) refresh ;; + up) + [ -f "$OFF_FLAG" ] && exit 0 + wait_api + alive && { log "tunnel is up"; exit 0; } + refresh + ;; + write) + # only where OpenVPN is set up and on + [ -f "$OFF_FLAG" ] || [ ! -f "$PROVIDER_FILE" ] && exit 0 + write_provider + ;; check) [ -f "$OFF_FLAG" ] && exit 0 # one run at a time: two slow probes can outlast the cron minute @@ -284,7 +331,7 @@ case "${1:-}" in wait_api api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" routes_set off - log "OpenVPN off: tunnel closed and its routes dropped, the server frees the session within its ping-restart (~5 min)" + log "OpenVPN off: tunnel closed and its routes dropped; the kit core tells the server (EXIT), other cores leave the session until its ping-restart (~5 min)" ;; on) rm -f "$OFF_FLAG" diff --git a/router/bmstu.env.example b/router/bmstu.env.example index 55eb98c..81e5cdf 100644 --- a/router/bmstu.env.example +++ b/router/bmstu.env.example @@ -3,8 +3,10 @@ VPN_USERNAME="username" VPN_PASSWORD="your-password" # base32 secret from the TOTP QR (otpauth://totp/...?secret=XXXX) TOTP_SECRET="XXXXXXXXXXXXXXXX" -# otp-last (default: ) | otp-first | scrv1 -#PASS_FORMAT=otp-last +# scrv1 (default, as OpenVPN Connect: SCRV1:b64(pass):b64(otp)) | otp-last | otp-first +#PASS_FORMAT=scrv1 +# connect-mac (default: present as OpenVPN Connect 3.7.1 for macOS) | mihomo +#OVPN_MIMIC=connect-mac # nikki API: read from uci (nikki.mixin.api_listen / api_secret) unless set here #API="http://192.168.1.1:9090" diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index 0d5dc1a..4330252 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -41,10 +41,11 @@ PROFILES_OUT="$NIKKI_DIR/profiles" # mihomo core: the choice CORE in /etc/nikki/kit.env (LuCI select, "core ") # stock the core of the mihomo package (/usr/libexec/mihomo), nothing downloaded # official MetaCubeX release CORE_OFFICIAL -# kit own build CORE_KIT (official + tools/core/*.patch: Tailscale through dialer-proxy) +# kit own build CORE_KIT (official + tools/core/*.patch: Tailscale through dialer-proxy, +# OpenVPN presenting as OpenVPN Connect) # An explicit MIHOMO_VERSION in kit.env wins (e.g. MIHOMO_VERSION=v1.19.29). CORE_OFFICIAL=v1.19.32 -CORE_KIT=v1.19.32-ts1 +CORE_KIT=v1.19.32-ts2 STOCK_CORE=/usr/libexec/mihomo KIT_ENV=${KIT_ENV:-/etc/nikki/kit.env} [ -f "$KIT_ENV" ] && . "$KIT_ENV" @@ -591,9 +592,11 @@ cmd_use() { log "OpenVPN is off (bmstu-otp.sh on to start it)" return 0 fi - # a fresh OTP right away; if it does not come up, cron (bmstu-otp.sh check) retries + # the init script wrote a fresh OTP and the kit core is already connecting: refresh + # only if the tunnel does not answer; if it does not come up, cron + # (bmstu-otp.sh check) retries sleep 5 - bmstu-otp.sh refresh || log "warning: OpenVPN did not come up yet, the cron check retries within a minute" + bmstu-otp.sh up || log "warning: OpenVPN did not come up yet, the cron check retries within a minute" return 0 } @@ -741,15 +744,26 @@ core_install() { } # Tailscale control over port 80 gets broken by the ISP: force 443. +# OpenVPN: a provider with a fresh OTP right before mihomo starts, since the kit +# core connects as soon as it loads the provider (auto-connect). patch_init() { f=/etc/init.d/nikki + _anchor="procd_append_param env SKIP_SYSTEM_IPV6_CHECK" + if ! grep -q "$_anchor" "$f"; then + log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' and '/usr/bin/bmstu-otp.sh write' by hand" + return 0 + fi if grep -q TS_FORCE_NOISE_443 "$f"; then log "init script already has TS_FORCE_NOISE_443" - elif grep -q "procd_append_param env SKIP_SYSTEM_IPV6_CHECK" "$f"; then - sed -i '/procd_append_param env SKIP_SYSTEM_IPV6_CHECK/a\ procd_append_param env TS_FORCE_NOISE_443=true' "$f" - log "added TS_FORCE_NOISE_443 to $f" else - log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' by hand" + sed -i "/$_anchor/a\\ procd_append_param env TS_FORCE_NOISE_443=true" "$f" + log "added TS_FORCE_NOISE_443 to $f" + fi + if grep -q "bmstu-otp.sh write" "$f"; then + log "init script already writes the OpenVPN provider" + else + sed -i "/$_anchor/a\\ [ -x /usr/bin/bmstu-otp.sh ] \\&\\& /usr/bin/bmstu-otp.sh write >/dev/null 2>\\&1" "$f" + log "added bmstu-otp.sh write to $f" fi } diff --git a/tools/core/openvpn-connect-mimic.patch b/tools/core/openvpn-connect-mimic.patch new file mode 100644 index 0000000..41274af --- /dev/null +++ b/tools/core/openvpn-connect-mimic.patch @@ -0,0 +1,1436 @@ +diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go +index 3c7b1e6..88760d0 100644 +--- a/adapter/outbound/openvpn.go ++++ b/adapter/outbound/openvpn.go +@@ -35,6 +35,14 @@ type OpenVPN struct { + runCancel context.CancelFunc + runLock *semaphore.Weighted + running bool ++ ++ // auto-connect state, guarded by runLock: the session auth-token reused ++ // on reconnect, credentials the server rejected, and the channel closed ++ // when the current tunnel goes down. ++ tokenUser string ++ tokenPass string ++ authFailed bool ++ linkDown chan struct{} + } + + type OpenVPNOption struct { +@@ -59,12 +67,18 @@ type OpenVPNOption struct { + Username string `proxy:"username,omitempty"` + Password string `proxy:"password,omitempty"` + PeerInfo map[string]string `proxy:"peer-info,omitempty"` ++ PeerInfoRaw string `proxy:"peer-info-raw,omitempty"` ++ OptionsString string `proxy:"options-string,omitempty"` + Ping int `proxy:"ping,omitempty"` + PingRestart int `proxy:"ping-restart,omitempty"` + TranWindow *int `proxy:"tran-window,omitempty"` + HandshakeTimeout int `proxy:"handshake-timeout,omitempty"` +- MTU int `proxy:"mtu,omitempty"` +- UDP bool `proxy:"udp,omitempty"` ++ // AutoConnect keeps the tunnel up like OpenVPN Connect: connect when the ++ // proxy is created, reconnect 2 s after the link drops with the session ++ // auth-token, stop after AUTH_FAILED until new credentials (a new proxy). ++ AutoConnect bool `proxy:"auto-connect,omitempty"` ++ MTU int `proxy:"mtu,omitempty"` ++ UDP bool `proxy:"udp,omitempty"` + + IPStack IPStackOption `proxy:"ip-stack,omitempty"` + +@@ -117,6 +131,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { + Username: option.Username, + Password: option.Password, + PeerInfo: option.PeerInfo, ++ PeerInfoRaw: option.PeerInfoRaw, ++ OptionsString: option.OptionsString, + PingInterval: time.Duration(option.Ping) * time.Second, + PingRestart: time.Duration(option.PingRestart) * time.Second, + TransitionWindow: transitionWindow, +@@ -152,9 +168,100 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { + } + outbound.dialer = option.NewDialer(outbound.DialOptions()) + outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background()) ++ registerOpenVPN(outbound) ++ if option.AutoConnect { ++ go outbound.autoConnect() ++ } + return outbound, nil + } + ++// openVPNInstances are the live OpenVPN proxies: closed on shutdown so they ++// send the exit notification, and an auto-connect proxy replaces an older ++// one with the same name and provider (a provider or config reload), as the ++// server allows one session per user. ++var ( ++ openVPNMu sync.Mutex ++ openVPNInstances = map[*OpenVPN]struct{}{} ++) ++ ++func registerOpenVPN(o *OpenVPN) { ++ var replaced []*OpenVPN ++ openVPNMu.Lock() ++ if o.option.AutoConnect { ++ for other := range openVPNInstances { ++ if other.option.AutoConnect && other.name == o.name && other.option.ProviderName == o.option.ProviderName { ++ delete(openVPNInstances, other) ++ replaced = append(replaced, other) ++ } ++ } ++ } ++ openVPNInstances[o] = struct{}{} ++ openVPNMu.Unlock() ++ for _, other := range replaced { ++ _ = other.Close() ++ } ++} ++ ++// CloseOpenVPN closes every OpenVPN proxy, sending the exit notification. ++// Called on shutdown. ++func CloseOpenVPN() { ++ openVPNMu.Lock() ++ all := make([]*OpenVPN, 0, len(openVPNInstances)) ++ for o := range openVPNInstances { ++ all = append(all, o) ++ } ++ openVPNMu.Unlock() ++ var wg sync.WaitGroup ++ for _, o := range all { ++ wg.Add(1) ++ go func(o *OpenVPN) { ++ defer wg.Done() ++ _ = o.Close() ++ }(o) ++ } ++ wg.Wait() ++} ++ ++// openVPNRestartDelay is OpenVPN Connect's pause before a reconnect. ++const openVPNRestartDelay = 2 * time.Second ++ ++var errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones") ++ ++func (o *OpenVPN) autoConnect() { ++ for o.runCtx.Err() == nil { ++ _, _, err := o.run(o.runCtx) ++ if o.runCtx.Err() != nil { ++ return ++ } ++ if errors.Is(err, errOpenVPNAuthRejected) { ++ log.Warnln("[OpenVPN](%s) %v", o.name, err) ++ return ++ } ++ if err != nil { ++ log.Warnln("[OpenVPN](%s) connect failed, retrying in %s: %v", o.name, openVPNRestartDelay, err) ++ } else { ++ var down chan struct{} ++ if o.runLock.Acquire(o.runCtx, 1) == nil { ++ down = o.linkDown ++ o.runLock.Release(1) ++ } ++ if down != nil { ++ select { ++ case <-down: ++ case <-o.runCtx.Done(): ++ return ++ } ++ log.Infoln("[OpenVPN](%s) tunnel down, reconnecting in %s", o.name, openVPNRestartDelay) ++ } ++ } ++ select { ++ case <-time.After(openVPNRestartDelay): ++ case <-o.runCtx.Done(): ++ return ++ } ++ } ++} ++ + func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) { + tunDevice, r, err := o.run(ctx) + if err != nil { +@@ -234,6 +341,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool { + } + + func (o *OpenVPN) Close() error { ++ openVPNMu.Lock() ++ delete(openVPNInstances, o) ++ openVPNMu.Unlock() ++ // Tell the server before the packet loops see the cancel and close the ++ // client. A handshake in progress holds runLock: nothing to notify then. ++ if o.runLock.TryAcquire(1) { ++ client := o.client ++ o.runLock.Release(1) ++ if client != nil { ++ ctx, cancel := context.WithTimeout(context.Background(), time.Second) ++ if err := client.SendExitNotify(ctx); err != nil { ++ log.Debugln("[OpenVPN](%s) exit notify: %v", o.name, err) ++ } ++ cancel() ++ } ++ } + if o.runCancel != nil { + o.runCancel() + } +@@ -278,6 +401,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) { + } + return o.tunDevice, o.resolver, nil + } ++ if o.authFailed { ++ return nil, nil, errOpenVPNAuthRejected ++ } + if o.runCtx.Err() != nil { + return nil, nil, o.runCtx.Err() + } +@@ -318,7 +444,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R + if err != nil { + return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err) + } +- client, err := ovpn.NewClient(o.config, packetIO) ++ config := o.config ++ if o.option.AutoConnect && o.tokenPass != "" { ++ // reconnect with the session token, like OpenVPN Connect ++ withToken := *o.config ++ if o.tokenUser != "" { ++ withToken.Username = o.tokenUser ++ } ++ withToken.Password = o.tokenPass ++ config = &withToken ++ } ++ client, err := ovpn.NewClient(config, packetIO) + if err != nil { + _ = packetIO.Close() + return nil, nil, err +@@ -326,6 +462,13 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R + push, err := client.Handshake(handshakeCtx) + if err != nil { + _ = client.Close() ++ if o.option.AutoConnect && ovpn.IsAuthFailed(err) { ++ // Connect drops a rejected token and, with a static challenge, ++ // waits for the user's next OTP: here a new proxy from the provider. ++ o.tokenUser, o.tokenPass = "", "" ++ o.authFailed = true ++ return nil, nil, fmt.Errorf("%w: %v", errOpenVPNAuthRejected, err) ++ } + return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", err) + } + log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6) +@@ -347,6 +490,7 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R + o.client = client + o.tunDevice = tunDevice + o.running = true ++ o.linkDown = make(chan struct{}) + if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil { + nss := append([]dns.NameServer(nil), o.dns...) + for i := range nss { +@@ -393,6 +537,7 @@ func (o *OpenVPN) startPacketLoops() { + runCtx, runCancel := context.WithCancel(o.runCtx) + client := o.client + tunDevice := o.tunDevice ++ linkDown := o.linkDown + var stopOnce sync.Once + stop := func() { + stopOnce.Do(func() { +@@ -405,7 +550,11 @@ func (o *OpenVPN) startPacketLoops() { + o.tunDevice = nil + o.running = false + } ++ if user, pass, ok := client.AuthToken(); ok { ++ o.tokenUser, o.tokenPass = user, pass ++ } + o.runLock.Release(1) ++ close(linkDown) + }) + } + go func() { +diff --git a/adapter/provider/provider.go b/adapter/provider/provider.go +index fa7d56b..c472539 100644 +--- a/adapter/provider/provider.go ++++ b/adapter/provider/provider.go +@@ -5,6 +5,7 @@ import ( + "errors" + "fmt" + "runtime" ++ "slices" + "strings" + "sync" + "time" +@@ -103,6 +104,13 @@ func (bp *baseProvider) RegisterHealthCheckTask(url string, expectedStatus utils + func (bp *baseProvider) setProxies(proxies []C.Proxy) { + bp.mutex.Lock() + defer bp.mutex.Unlock() ++ // Replaced OpenVPN proxies close now, sending the exit notification and ++ // freeing the server session, instead of whenever the GC finalizes them. ++ for _, old := range bp.proxies { ++ if old.Type() == C.OpenVPN && !slices.Contains(proxies, old) { ++ go old.Close() ++ } ++ } + bp.proxies = proxies + bp.version += 1 + bp.healthCheck.setProxies(proxies) +diff --git a/hub/executor/executor.go b/hub/executor/executor.go +index 796face..a7df5cd 100644 +--- a/hub/executor/executor.go ++++ b/hub/executor/executor.go +@@ -13,6 +13,7 @@ import ( + + "github.com/metacubex/mihomo/adapter" + "github.com/metacubex/mihomo/adapter/inbound" ++ "github.com/metacubex/mihomo/adapter/outbound" + "github.com/metacubex/mihomo/adapter/outboundgroup" + "github.com/metacubex/mihomo/component/auth" + "github.com/metacubex/mihomo/component/ca" +@@ -530,6 +531,8 @@ func updateIPTables(cfg *config.Config) { + } + + func Shutdown() { ++ // OpenVPN tunnels tell the server they are leaving (explicit exit notify) ++ outbound.CloseOpenVPN() + listener.Cleanup() + tproxy.CleanupTProxyIPTables() + resolver.StoreFakePoolState() +diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go +index 053b0bf..868b445 100644 +--- a/transport/openvpn/client.go ++++ b/transport/openvpn/client.go +@@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { + primaryCipher = normalizeCipher(c.config.DataCiphers[0]) + } + +- clientRecord, err := NewClientKeyMethod2Record( +- InstallScriptOptionsString(c.config.Proto, primaryCipher, c.config.Auth, c.config.CompLZO), +- InstallScriptPeerInfo(primaryCipher, c.config.DataCiphers, c.config.CompLZO, c.config.PeerInfo), +- c.authUser, +- c.authPass, +- ) ++ options := InstallScriptOptionsString(c.config.Proto, primaryCipher, c.config.Auth, c.config.CompLZO) ++ if c.config.OptionsString != "" { ++ options = c.config.OptionsString ++ } ++ peerInfo := InstallScriptPeerInfo(primaryCipher, c.config.DataCiphers, c.config.CompLZO, c.config.PeerInfo) ++ if c.config.PeerInfoRaw != "" { ++ peerInfo = RawPeerInfo(c.config.PeerInfoRaw) ++ } ++ clientRecord, err := NewClientKeyMethod2Record(options, peerInfo, c.authUser, c.authPass) + if err != nil { + return nil, err + } +@@ -336,11 +339,7 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { + return nil, fmt.Errorf("negotiate data cipher: %w", err) + } + c.negotiatedCipher = negotiatedCipher +- cipherKeyLen := CipherKeyLength(negotiatedCipher) +- keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] +- keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] +- keyID := c.control.KeyID() +- newData, err := NewDataChannel(keys, negotiatedCipher, c.config.Auth, push.PeerID, keyID) ++ newData, err := c.newDataChannel(keys, push, negotiatedCipher) + if err != nil { + return nil, err + } +@@ -370,16 +369,17 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { + } + c.negotiatedCipher = negotiatedCipher + +- // Slice the derived keys to the negotiated cipher's key length. +- cipherKeyLen := CipherKeyLength(negotiatedCipher) +- keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] +- keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] +- +- keyID := c.control.KeyID() +- newData, err := NewDataChannel(keys, negotiatedCipher, c.config.Auth, push.PeerID, keyID) ++ newData, err := c.newDataChannel(keys, push, negotiatedCipher) + if err != nil { + return nil, err + } ++ // Dynamic tls-crypt: the first key state derives the control-channel ++ // key for all renegotiations (tls_session_generate_dynamic_tls_crypt_key). ++ if push.DynTLSCrypt && c.control.KeyID() == 0 { ++ if err := c.installDynamicTLSCrypt(); err != nil { ++ return nil, err ++ } ++ } + c.installDataChannel(newData) + c.captureAuthToken(push) + c.markSend() +@@ -387,6 +387,123 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { + return push, nil + } + ++// OpenVPN keying material exporter labels (ssl_backend.h). ++const ( ++ exportKeyDataLabel = "EXPORTER-OpenVPN-datakeys" ++ exportDynamicTLSCryptLabel = "EXPORTER-OpenVPN-dynamic-tls-crypt" ++) ++ ++// newDataChannel builds the data channel of the current key state. prf holds ++// the key-method 2 PRF keys; with tls-ekm the TLS keying material exporter ++// replaces them (generate_key_expansion_tls_export). The epoch format takes ++// its E1 secrets from the full cipher key slots. ++func (c *Client) newDataChannel(prf *KeyMaterial, push *PushReply, cipherName string) (*DataChannel, error) { ++ keys := prf ++ if push.TLSEKM { ++ block, err := c.exportKeyingMaterial(exportKeyDataLabel) ++ if err != nil { ++ return nil, err ++ } ++ keys = keyMaterialFromBlock(block, maxCipherKeyLength) ++ } ++ keyID := c.control.KeyID() ++ if push.AEADEpoch { ++ return NewEpochDataChannel(keys, cipherName, push.PeerID, keyID) ++ } ++ cipherKeyLen := CipherKeyLength(cipherName) ++ keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] ++ keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] ++ return NewDataChannel(keys, cipherName, c.config.Auth, push.PeerID, keyID) ++} ++ ++func (c *Client) exportKeyingMaterial(label string) ([]byte, error) { ++ conn := c.tlsConn.Load() ++ if conn == nil { ++ return nil, errors.New("openvpn keying material export: no tls session") ++ } ++ state := conn.ConnectionState() ++ block, err := state.ExportKeyingMaterial(label, nil, keyBlockSize) ++ if err != nil { ++ return nil, fmt.Errorf("openvpn keying material export: %w", err) ++ } ++ return block, nil ++} ++ ++// installDynamicTLSCrypt derives the tls-crypt key for key IDs > 0: the ++// exported key block XORed with the original tls-auth / tls-crypt key. ++func (c *Client) installDynamicTLSCrypt() error { ++ block, err := c.exportKeyingMaterial(exportDynamicTLSCryptLabel) ++ if err != nil { ++ return err ++ } ++ var original []byte ++ switch { ++ case len(c.config.TLSCryptV2Key) > 0: ++ original = c.config.TLSCryptV2Key ++ case len(c.config.TLSCryptKey) > 0: ++ original = c.config.TLSCryptKey ++ case len(c.config.TLSAuthKey) > 0: ++ original = c.config.TLSAuthKey ++ } ++ for i := 0; i < len(original) && i < len(block); i++ { ++ block[i] ^= original[i] ++ } ++ crypt, err := NewTLSCrypt(block, true) ++ if err != nil { ++ return err ++ } ++ c.control.SetRenegCrypt(crypt) ++ return nil ++} ++ ++// OCC explicit-exit-notify data channel message (OCC_STRING + OCC_EXIT). ++var occExitPacket = []byte{ ++ 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81, ++ 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c, ++ 6, ++} ++ ++// SendExitNotify tells the server this client is disconnecting, as OpenVPN ++// Connect does (send_explicit_exit_notify): an EXIT control message when the ++// server pushed cc-exit, the OCC exit data packet otherwise. Only on UDP: a ++// TCP server sees the connection close. ++func (c *Client) SendExitNotify(ctx context.Context) error { ++ if c == nil || c.config.Proto != ProtoUDP { ++ return nil ++ } ++ push := c.push ++ if push == nil { ++ return nil ++ } ++ if !push.CCExit { ++ return c.writeDataPacket(ctx, occExitPacket, false) ++ } ++ conn := c.tlsConn.Load() ++ if conn == nil { ++ return errors.New("openvpn exit notify: no tls session") ++ } ++ if deadline, ok := ctx.Deadline(); ok { ++ _ = conn.SetWriteDeadline(deadline) ++ } ++ _, err := conn.Write([]byte("EXIT\x00")) ++ return err ++} ++ ++// AuthToken returns the session auth-token pushed by the server (with its ++// auth-token-user), which OpenVPN Connect reuses as the password when it ++// reconnects. ++func (c *Client) AuthToken() (user, pass string, ok bool) { ++ if c == nil || c.push == nil || c.push.AuthTokenPass == "" { ++ return "", "", false ++ } ++ return c.authUser, c.authPass, true ++} ++ ++// IsAuthFailed reports whether err is the server's AUTH_FAILED. ++func IsAuthFailed(err error) bool { ++ return errors.Is(err, errAuthFailed) ++} ++ + // consumeRekeyPush updates the cached push state after an authenticated + // rekey: it inherits the previous peer-id and applies any fresh auth-token + // pushed by send_push_reply_auth_token. Must be called only when c.push is +@@ -1652,6 +1769,10 @@ func mergePushReply(prev, next *PushReply) *PushReply { + if !next.BlockIPv6 { + next.BlockIPv6 = prev.BlockIPv6 + } ++ next.TLSEKM = next.TLSEKM || prev.TLSEKM ++ next.DynTLSCrypt = next.DynTLSCrypt || prev.DynTLSCrypt ++ next.AEADEpoch = next.AEADEpoch || prev.AEADEpoch ++ next.CCExit = next.CCExit || prev.CCExit + if next.AuthTokenPass == "" { + next.AuthTokenPass = prev.AuthTokenPass + } +@@ -1768,6 +1889,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) { + // servers rekey the control channel at regular intervals (default 1h). + Renegotiation: tls.RenegotiateFreelyAsClient, + } ++ // The keying material exporter is unavailable with renegotiation ++ // enabled. OpenVPN rekeys with a new TLS session per key ID, never by ++ // TLS renegotiation, so disable it when tls-ekm can be negotiated. ++ if announcesKeyExport(c.config.PeerInfoRaw) { ++ cfg.Renegotiation = tls.RenegotiateNever ++ } + certPEM := bytes.TrimSpace(c.config.Cert) + keyPEM := bytes.TrimSpace(c.config.Key) + if len(certPEM) > 0 && len(keyPEM) > 0 { +diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go +index 51690c3..13b115e 100644 +--- a/transport/openvpn/config.go ++++ b/transport/openvpn/config.go +@@ -55,6 +55,13 @@ type ClientConfig struct { + Password string + + PeerInfo map[string]string ++ // PeerInfoRaw replaces the generated peer-info verbatim (lines in the ++ // given order, e.g. copied from another client's log). Its IV_PROTO must ++ // announce only features this client implements: DATA_V2, REQUEST_PUSH, ++ // TLS_KEY_EXPORT, AUTH_PENDING_KW, DYN_TLS_CRYPT, DATA_EPOCH. ++ PeerInfoRaw string ++ // OptionsString replaces the generated key-method 2 options string. ++ OptionsString string + + PingInterval time.Duration + PingRestart time.Duration +diff --git a/transport/openvpn/control.go b/transport/openvpn/control.go +index bd0f7e7..7cca17b 100644 +--- a/transport/openvpn/control.go ++++ b/transport/openvpn/control.go +@@ -64,6 +64,13 @@ type ControlChannel struct { + // protected control packets, mirroring OpenVPN's packet_id_rec. Soft key + // resets do not replace the outer TLS wrapper or reset its packet IDs. + recReplay replayState ++ // renegCrypt is the dynamic tls-crypt wrapper of key IDs > 0 ++ // (tls_session_get_tls_wrap), with its own packet IDs and replay window ++ // (OpenVPN tls_wrap_reneg). ++ renegCrypt ControlCryptor ++ renegPacketID uint32 ++ renegPacketTime uint32 ++ renegReplay replayState + } + + // replayState is the receive-side OpenVPN long-form packet-id window. +@@ -96,10 +103,22 @@ func reliableMessageBefore(messageID, recvMessage uint32) bool { + // against the anti-replay window. Returns an error for replayed or stale + // packets. Must be called with c.mu held. + func (c *ControlChannel) checkReplayLocked(packetID, unixTime uint32) error { ++ return c.checkReplayStateLocked(&c.recReplay, packetID, unixTime) ++} ++ ++// checkKeyReplayLocked checks against the window of the wrapper that ++// protects keyID: key IDs > 0 have their own with dynamic tls-crypt. ++func (c *ControlChannel) checkKeyReplayLocked(keyID uint8, packetID, unixTime uint32) error { ++ if keyID != 0 && c.renegCrypt != nil { ++ return c.checkReplayStateLocked(&c.renegReplay, packetID, unixTime) ++ } ++ return c.checkReplayStateLocked(&c.recReplay, packetID, unixTime) ++} ++ ++func (c *ControlChannel) checkReplayStateLocked(r *replayState, packetID, unixTime uint32) error { + if packetID == 0 { + return errors.New("openvpn control replay: packet id 0") + } +- r := &c.recReplay + replayClock := c.replayClock + if replayClock == nil { + replayClock = time.Now +@@ -172,6 +191,21 @@ func NewControlChannel(io ControlIO, crypt ControlCryptor, local SessionID) *Con + } + } + ++// SetRenegCrypt installs the dynamic tls-crypt wrapper for key IDs > 0. ++func (c *ControlChannel) SetRenegCrypt(crypt ControlCryptor) { ++ c.mu.Lock() ++ c.renegCrypt = crypt ++ c.mu.Unlock() ++} ++ ++// cryptForLocked returns the wrapper of control packets with keyID. ++func (c *ControlChannel) cryptForLocked(keyID uint8) ControlCryptor { ++ if keyID != 0 && c.renegCrypt != nil { ++ return c.renegCrypt ++ } ++ return c.crypt ++} ++ + func (c *ControlChannel) LocalSessionID() SessionID { + return c.local + } +@@ -543,7 +577,14 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + if err != nil { + return nil, err + } +- packet, packetID, unixTime, err := DecodeControlPacket(c.crypt, raw) ++ c.mu.Lock() ++ crypt := c.crypt ++ if len(raw) > 0 { ++ _, rawKeyID := parseOpcodeKeyID(raw[0]) ++ crypt = c.cryptForLocked(rawKeyID) ++ } ++ c.mu.Unlock() ++ packet, packetID, unixTime, err := DecodeControlPacket(crypt, raw) + if err != nil { + // Invalid control datagrams are packet loss, not TLS stream errors. + // OpenVPN drops malformed/authentication-failed packets and keeps the +@@ -564,8 +605,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + initialReset := (packet.Opcode == PControlHardResetServerV2 || + packet.Opcode == PControlHardResetServerV1) && + packet.KeyID == c.keyID && packet.MessageID == 0 +- if initialReset && c.crypt != nil { +- if err := c.checkReplayLocked(packetID, unixTime); err != nil { ++ if initialReset && crypt != nil { ++ if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { + c.mu.Unlock() + continue + } +@@ -597,8 +638,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + if packet.KeyID == NextKeyID(curKey) && packet.MessageID == 0 && sameSession { + // tls-auth/tls-crypt packet IDs belong to the outer TLS + // session and remain continuous across key-state soft resets. +- if c.crypt != nil { +- if err := c.checkReplayLocked(packetID, unixTime); err != nil { ++ if crypt != nil { ++ if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { + c.mu.Unlock() + continue + } +@@ -625,8 +666,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + // cannot be fed into the new TLS session. + continue + } +- if c.crypt != nil && !replayChecked { +- if err := c.checkReplayLocked(packetID, unixTime); err != nil { ++ if crypt != nil && !replayChecked { ++ if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { + c.mu.Unlock() + continue + } +@@ -642,8 +683,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + continue + } + if softReset { +- if c.crypt != nil { +- if err := c.checkReplayLocked(packetID, unixTime); err != nil { ++ if crypt != nil { ++ if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { + c.mu.Unlock() + continue + } +@@ -652,8 +693,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro + c.mu.Unlock() + return packet, nil + } +- if c.crypt != nil { +- if err := c.checkReplayLocked(packetID, unixTime); err != nil { ++ if crypt != nil { ++ if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { + c.mu.Unlock() + continue + } +@@ -785,16 +826,21 @@ func (c *ControlChannel) writeControlPacketWithAbort(ctx context.Context, packet + // writeControlPacketGranted writes while the caller owns sendGate. + func (c *ControlChannel) writeControlPacketGranted(ctx context.Context, packet *ControlPacket, abortActive bool) error { + c.mu.Lock() +- if c.crypt != nil && c.sendPacketID == ^uint32(0) { ++ crypt := c.cryptForLocked(packet.KeyID) ++ sendPacketID, sendPacketTime := &c.sendPacketID, &c.sendPacketTime ++ if crypt != c.crypt { ++ sendPacketID, sendPacketTime = &c.renegPacketID, &c.renegPacketTime ++ } ++ if crypt != nil && *sendPacketID == ^uint32(0) { + c.mu.Unlock() + return errors.New("openvpn control packet id exhausted; new session required") + } +- if c.crypt != nil && c.sendPacketTime == 0 { +- c.sendPacketTime = uint32(c.clock().Unix()) ++ if crypt != nil && *sendPacketTime == 0 { ++ *sendPacketTime = uint32(c.clock().Unix()) + } +- c.sendPacketID++ +- packetID := c.sendPacketID +- unixTime := c.sendPacketTime ++ *sendPacketID++ ++ packetID := *sendPacketID ++ unixTime := *sendPacketTime + opCtx, cancel := context.WithCancelCause(ctx) + c.writeGeneration++ + generation := c.writeGeneration +@@ -803,7 +849,7 @@ func (c *ControlChannel) writeControlPacketGranted(ctx context.Context, packet * + c.mu.Unlock() + defer c.finishWrite(generation, cancel) + +- encoded, err := packet.Encode(c.crypt, packetID, unixTime) ++ encoded, err := packet.Encode(crypt, packetID, unixTime) + if err != nil { + return err + } +diff --git a/transport/openvpn/data.go b/transport/openvpn/data.go +index 51e171d..8a674f1 100644 +--- a/transport/openvpn/data.go ++++ b/transport/openvpn/data.go +@@ -79,6 +79,28 @@ type DataChannel struct { + randMu sync.Mutex + randBuf []byte + randOffset int ++ ++ // epoch is set for the epoch data key format (aead-epoch); it replaces ++ // the AEAD keys and packet ID above. Guarded by d.mu. ++ epoch *epochState ++} ++ ++// NewEpochDataChannel creates a data channel in the epoch data key format. ++// keys must hold at least the first 32 bytes of each cipher key slot. ++func NewEpochDataChannel(keys *KeyMaterial, cipherName string, peerID uint32, keyID uint8) (*DataChannel, error) { ++ if keys == nil { ++ return nil, errors.New("nil openvpn key material") ++ } ++ epoch, err := newEpochState(cipherName, keys.SendCipherKey, keys.RecvCipherKey) ++ if err != nil { ++ return nil, err ++ } ++ return &DataChannel{ ++ epoch: epoch, ++ keyID: keyID & KeyIDMask, ++ peerID: peerID, ++ header: dataHeader(peerID, keyID), ++ }, nil + } + + func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32, keyID uint8) (*DataChannel, error) { +@@ -198,6 +220,9 @@ func (d *DataChannel) Encrypt(packet []byte) ([]byte, error) { + if d == nil { + return nil, errors.New("nil openvpn data channel") + } ++ if d.epoch != nil { ++ return d.encryptEpoch(packet) ++ } + + packetID, err := d.nextPacketID() + if err != nil { +@@ -265,6 +290,9 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) { + if err != nil { + return nil, err + } ++ if d.epoch != nil { ++ return d.decryptEpoch(packet, headerSize) ++ } + if d.recvAEAD != nil { + return d.decryptAEAD(packet, headerSize) + } +diff --git a/transport/openvpn/data_epoch.go b/transport/openvpn/data_epoch.go +new file mode 100644 +index 0000000..ac241b2 +--- /dev/null ++++ b/transport/openvpn/data_epoch.go +@@ -0,0 +1,300 @@ ++package openvpn ++ ++import ( ++ "crypto/cipher" ++ "crypto/hmac" ++ "crypto/sha256" ++ "encoding/binary" ++ "errors" ++ "fmt" ++) ++ ++// Epoch data keys (OpenVPN 2.7 crypto_epoch.c, pushed as "protocol-flags ++// aead-epoch" to peers announcing IV_PROTO_DATA_EPOCH). The packet ID is ++// 64 bits (16-bit epoch + 48-bit counter), the AEAD tag follows the ++// ciphertext, and every epoch has its own key derived with ++// OVPN-Expand-Label from a per-direction epoch secret. ++ ++const ( ++ // future receive keys kept ahead of the current one (init_epoch_keys) ++ epochFutureKeys = 4 ++ epochSecretSize = 32 ++ epochPacketIDSize = 8 ++ epochCounterMax = uint64(1)<<48 - 1 ++ // AES-GCM usage limit q + s <= 2^36 - 1 blocks (cipher_get_aead_limits); ++ // ChaCha20-Poly1305 has none. ++ epochAESGCMBlockLimit = uint64(1)<<36 - 1 ++) ++ ++type epochKey struct { ++ epoch uint16 ++ aead cipher.AEAD ++ iv [DataChannelIVSize]byte ++ blocks uint64 ++ replay epochReplay ++} ++ ++// epochReplay is the per-key receive window (packet_id_rec, 64 packets). ++type epochReplay struct { ++ highest uint64 ++ window uint64 ++ seen bool ++} ++ ++type epochState struct { ++ cipherName string ++ limit uint64 ++ ++ sendSecret [epochSecretSize]byte ++ sendEpoch uint16 ++ send *epochKey ++ sendCounter uint64 ++ ++ // recvSecret is the secret of the highest generated receive epoch. ++ recvSecret [epochSecretSize]byte ++ recvEpoch uint16 ++ recv *epochKey ++ retiring *epochKey ++ future []*epochKey ++} ++ ++// ovpnHKDFExpand is HKDF-Expand (RFC 5869) with HMAC-SHA256 (ovpn_hkdf_expand). ++func ovpnHKDFExpand(secret, info []byte, size int) []byte { ++ out := make([]byte, 0, size+sha256.Size) ++ var prev []byte ++ for block := byte(1); len(out) < size; block++ { ++ mac := hmac.New(sha256.New, secret) ++ mac.Write(prev) ++ mac.Write(info) ++ mac.Write([]byte{block}) ++ prev = mac.Sum(nil) ++ out = append(out, prev...) ++ } ++ return out[:size] ++} ++ ++// ovpnExpandLabel is OVPN-Expand-Label(secret, label, "", size): the TLS 1.3 ++// HkdfLabel layout with the "ovpn " prefix and an empty context. ++func ovpnExpandLabel(secret []byte, label string, size int) []byte { ++ info := make([]byte, 0, 2+1+5+len(label)+1) ++ info = binary.BigEndian.AppendUint16(info, uint16(size)) ++ info = append(info, byte(5+len(label))) ++ info = append(info, "ovpn "...) ++ info = append(info, label...) ++ info = append(info, 0) ++ return ovpnHKDFExpand(secret, info, size) ++} ++ ++// E_n+1 = OVPN-Expand-Label(E_n, "datakey upd", "", 32) ++func epochIterate(secret *[epochSecretSize]byte) { ++ copy(secret[:], ovpnExpandLabel(secret[:], "datakey upd", epochSecretSize)) ++} ++ ++func newEpochKey(cipherName string, secret []byte, epoch uint16) (*epochKey, error) { ++ aead, err := newDataChannelAEAD(cipherName, ovpnExpandLabel(secret, "data_key", CipherKeyLength(cipherName))) ++ if err != nil { ++ return nil, err ++ } ++ k := &epochKey{epoch: epoch, aead: aead} ++ copy(k.iv[:], ovpnExpandLabel(secret, "data_iv", DataChannelIVSize)) ++ return k, nil ++} ++ ++// newEpochState starts both directions at epoch 1. The E1 secrets are the ++// first 32 bytes of the cipher key slots of the key2 block (init_epoch_keys). ++func newEpochState(cipherName string, sendSecret, recvSecret []byte) (*epochState, error) { ++ if !isDataChannelAEAD(cipherName) { ++ return nil, fmt.Errorf("openvpn epoch data keys need an AEAD cipher, got %q", cipherName) ++ } ++ if len(sendSecret) < epochSecretSize || len(recvSecret) < epochSecretSize { ++ return nil, errors.New("openvpn epoch key material is too short") ++ } ++ s := &epochState{cipherName: cipherName, sendEpoch: 1, recvEpoch: 1} ++ if cipherName != CipherChaCha20Poly1305 { ++ s.limit = epochAESGCMBlockLimit ++ } ++ copy(s.sendSecret[:], sendSecret) ++ copy(s.recvSecret[:], recvSecret) ++ var err error ++ if s.send, err = newEpochKey(cipherName, s.sendSecret[:], 1); err != nil { ++ return nil, err ++ } ++ if s.recv, err = newEpochKey(cipherName, s.recvSecret[:], 1); err != nil { ++ return nil, err ++ } ++ return s, s.fillFuture() ++} ++ ++// fillFuture keeps keys for epochs recv+1 .. recv+epochFutureKeys ++// (epoch_generate_future_receive_keys). ++func (s *epochState) fillFuture() error { ++ kept := s.future[:0] ++ for _, k := range s.future { ++ if k.epoch > s.recv.epoch { ++ kept = append(kept, k) ++ } ++ } ++ s.future = kept ++ for s.recvEpoch < s.recv.epoch+epochFutureKeys && s.recvEpoch < ^uint16(0) { ++ epochIterate(&s.recvSecret) ++ s.recvEpoch++ ++ k, err := newEpochKey(s.cipherName, s.recvSecret[:], s.recvEpoch) ++ if err != nil { ++ return err ++ } ++ s.future = append(s.future, k) ++ } ++ return nil ++} ++ ++// advanceSend moves the send key to epoch (epoch_iterate_send_key); the ++// packet counter restarts for the new key. ++func (s *epochState) advanceSend(epoch uint16) error { ++ for s.sendEpoch < epoch { ++ epochIterate(&s.sendSecret) ++ s.sendEpoch++ ++ } ++ k, err := newEpochKey(s.cipherName, s.sendSecret[:], s.sendEpoch) ++ if err != nil { ++ return err ++ } ++ s.send = k ++ s.sendCounter = 0 ++ return nil ++} ++ ++// lookup returns the receive key of epoch (epoch_lookup_decrypt_key). ++func (s *epochState) lookup(epoch uint16) *epochKey { ++ if s.recv.epoch == epoch { ++ return s.recv ++ } ++ if s.retiring != nil && s.retiring.epoch == epoch { ++ return s.retiring ++ } ++ // at the edge of the epoch space the window cannot move any further ++ if epoch > ^uint16(0)-epochFutureKeys-1 { ++ return nil ++ } ++ for _, k := range s.future { ++ if k.epoch == epoch { ++ return k ++ } ++ } ++ return nil ++} ++ ++// promote makes an authenticated future key the current receive key and ++// follows the peer with the send key (epoch_replace_update_recv_key). ++func (s *epochState) promote(k *epochKey) error { ++ if s.send.epoch < k.epoch { ++ if err := s.advanceSend(k.epoch); err != nil { ++ return err ++ } ++ } ++ s.retiring = s.recv ++ s.recv = k ++ return s.fillFuture() ++} ++ ++func (r *epochReplay) accept(id uint64) error { ++ if !r.seen { ++ *r = epochReplay{highest: id, window: 1, seen: true} ++ return nil ++ } ++ if id > r.highest { ++ shift := id - r.highest ++ if shift >= dataChannelReplayWindow { ++ r.window = 1 ++ } else { ++ r.window = r.window<= dataChannelReplayWindow || r.window&mask != 0 { ++ return fmt.Errorf("openvpn replayed data packet id %d", id) ++ } ++ r.window |= mask ++ return nil ++} ++ ++func epochNonce(iv [DataChannelIVSize]byte, packetID []byte) [DataChannelIVSize]byte { ++ for i, b := range packetID { ++ iv[i] ^= b ++ } ++ return iv ++} ++ ++func (d *DataChannel) encryptEpoch(packet []byte) ([]byte, error) { ++ s := d.epoch ++ d.mu.Lock() ++ // epoch_check_send_iterate: a fresh key before the usage limit or the ++ // 48-bit counter runs out ++ if (s.limit != 0 && s.send.blocks >= s.limit) || s.sendCounter >= epochCounterMax { ++ if s.sendEpoch == ^uint16(0) { ++ d.mu.Unlock() ++ return nil, errDataPacketIDExhausted ++ } ++ if err := s.advanceSend(s.sendEpoch + 1); err != nil { ++ d.mu.Unlock() ++ return nil, err ++ } ++ } ++ s.sendCounter++ ++ key := s.send ++ key.blocks += uint64(epochPacketIDSize+len(packet)+DataChannelTagSize+15) / 16 ++ var packetID [epochPacketIDSize]byte ++ binary.BigEndian.PutUint64(packetID[:], uint64(key.epoch)<<48|s.sendCounter) ++ d.mu.Unlock() ++ ++ header := d.header ++ nonce := epochNonce(key.iv, packetID[:]) ++ out := make([]byte, 0, len(header)+epochPacketIDSize+len(packet)+DataChannelTagSize) ++ out = append(out, header...) ++ out = append(out, packetID[:]...) ++ return key.aead.Seal(out, nonce[:], packet, aeadAdditionalData(header, packetID[:])), nil ++} ++ ++func (d *DataChannel) decryptEpoch(packet []byte, headerSize int) ([]byte, error) { ++ if len(packet) < headerSize+epochPacketIDSize+DataChannelTagSize+1 { ++ return nil, errors.New("openvpn data packet too short") ++ } ++ header := packet[:headerSize] ++ packetID := packet[headerSize : headerSize+epochPacketIDSize] ++ id := binary.BigEndian.Uint64(packetID) ++ epoch := uint16(id >> 48) ++ if epoch == 0 { ++ return nil, errors.New("openvpn data packet with epoch 0") ++ } ++ s := d.epoch ++ d.mu.Lock() ++ key := s.lookup(epoch) ++ d.mu.Unlock() ++ if key == nil { ++ return nil, fmt.Errorf("openvpn data packet with unknown epoch %d", epoch) ++ } ++ nonce := epochNonce(key.iv, packetID) ++ plain, err := key.aead.Open(nil, nonce[:], packet[headerSize+epochPacketIDSize:], aeadAdditionalData(header, packetID)) ++ if err != nil { ++ return nil, err ++ } ++ ++ d.mu.Lock() ++ defer d.mu.Unlock() ++ // The peer authenticated a packet with a newer epoch: move to it. Lookup ++ // again, a concurrent packet may have promoted it already. ++ if key != s.recv && key != s.retiring { ++ if s.lookup(epoch) != key { ++ return nil, fmt.Errorf("openvpn data packet with stale epoch %d", epoch) ++ } ++ if err := s.promote(key); err != nil { ++ return nil, err ++ } ++ } ++ if err := key.replay.accept(id & epochCounterMax); err != nil { ++ return nil, err ++ } ++ return plain, nil ++} +diff --git a/transport/openvpn/data_epoch_test.go b/transport/openvpn/data_epoch_test.go +new file mode 100644 +index 0000000..a675846 +--- /dev/null ++++ b/transport/openvpn/data_epoch_test.go +@@ -0,0 +1,263 @@ ++package openvpn ++ ++import ( ++ "bytes" ++ "context" ++ "encoding/binary" ++ "testing" ++) ++ ++// Vectors from OpenVPN tests/unit_tests/openvpn/test_crypto.c. ++ ++func TestOVPNHKDFExpandVector(t *testing.T) { ++ prk := []byte{0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, ++ 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, ++ 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5} ++ info := []byte{0x00, 0x1b, 0x0e, 0x6f, 0x76, 0x70, 0x6e, 0x20, 0x75, ++ 0x6e, 0x69, 0x74, 0x20, 0x74, 0x65, 0x73, 0x74, 0x00} ++ want := []byte{0x87, 0x5a, 0x8e, 0xec, 0x18, 0x55, 0x63, 0x80, 0xb8, ++ 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8, 0xe8, 0xec, ++ 0xcf, 0x49, 0x72, 0xe6, 0x83, 0xf0, 0x6a, 0x83, 0xac} ++ if got := ovpnHKDFExpand(prk, info, len(want)); !bytes.Equal(got, want) { ++ t.Fatalf("hkdf expand = %x, want %x", got, want) ++ } ++ // the info above is the HkdfLabel of "unit test" with length 27 ++ if got := ovpnExpandLabel(prk, "unit test", len(want)); !bytes.Equal(got, want) { ++ t.Fatalf("expand label = %x, want %x", got, want) ++ } ++} ++ ++func TestOVPNExpandLabelVector(t *testing.T) { ++ secret := []byte{0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, ++ 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, ++ 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5} ++ want := []byte{0x18, 0x5e, 0xaa, 0x1c, 0x7f, 0x22, 0x8a, 0xb8, ++ 0xeb, 0x29, 0x77, 0x32, 0x14, 0xd9, 0x20, 0x46} ++ if got := ovpnExpandLabel(secret, "unit test", 16); !bytes.Equal(got, want) { ++ t.Fatalf("expand label = %x, want %x", got, want) ++ } ++} ++ ++func TestEpochDataKeyDeriveVector(t *testing.T) { ++ secret := make([]byte, epochSecretSize) ++ secret[0], secret[1] = 19, 12 ++ wantKey := []byte{0xed, 0x85, 0x33, 0xdb, 0x1c, 0x28, 0xac, 0xe4, ++ 0x18, 0xe9, 0x00, 0x6a, 0xb2, 0x9c, 0x17, 0x41, ++ 0x7d, 0x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf, 0x0a} ++ wantIV := []byte{0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32, ++ 0xcb, 0x59, 0xf4, 0xcf, 0xa3, 0x4e} ++ if got := ovpnExpandLabel(secret, "data_key", CipherKeyLength(CipherAES192GCM)); !bytes.Equal(got, wantKey) { ++ t.Fatalf("data key = %x, want %x", got, wantKey) ++ } ++ k, err := newEpochKey(CipherAES192GCM, secret, 17) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !bytes.Equal(k.iv[:], wantIV) { ++ t.Fatalf("implicit iv = %x, want %x", k.iv, wantIV) ++ } ++} ++ ++func newEpochPair(t *testing.T, cipherName string) (client, server *DataChannel) { ++ t.Helper() ++ c2s := bytes.Repeat([]byte{0x23}, maxCipherKeyLength) ++ s2c := bytes.Repeat([]byte{0x27}, maxCipherKeyLength) ++ client, err := NewEpochDataChannel(&KeyMaterial{SendCipherKey: c2s, RecvCipherKey: s2c}, cipherName, 7, 0) ++ if err != nil { ++ t.Fatal(err) ++ } ++ server, err = NewEpochDataChannel(&KeyMaterial{SendCipherKey: s2c, RecvCipherKey: c2s}, cipherName, 7, 0) ++ if err != nil { ++ t.Fatal(err) ++ } ++ return client, server ++} ++ ++func TestEpochDataChannelWireFormat(t *testing.T) { ++ client, server := newEpochPair(t, CipherAES256GCM) ++ payload := []byte("epoch data channel payload") ++ packet, err := client.Encrypt(payload) ++ if err != nil { ++ t.Fatal(err) ++ } ++ // P_DATA_V2 header, 16-bit epoch + 48-bit counter, ciphertext, tag at the end ++ if want := 4 + 8 + len(payload) + DataChannelTagSize; len(packet) != want { ++ t.Fatalf("packet length %d, want %d", len(packet), want) ++ } ++ if id := binary.BigEndian.Uint64(packet[4:12]); id != 1<<48|1 { ++ t.Fatalf("packet id %x, want epoch 1 counter 1", id) ++ } ++ plain, err := server.Decrypt(packet) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !bytes.Equal(plain, payload) { ++ t.Fatalf("plaintext %q", plain) ++ } ++ if _, err := server.Decrypt(packet); err == nil { ++ t.Fatal("replayed packet accepted") ++ } ++ tampered := cloneBytes(packet) ++ tampered[2] ^= 1 // peer-id is authenticated ++ if _, err := server.Decrypt(tampered); err == nil { ++ t.Fatal("tampered header accepted") ++ } ++} ++ ++func TestEpochDataChannelFollowsPeerEpoch(t *testing.T) { ++ for _, cipherName := range []string{CipherAES128GCM, CipherChaCha20Poly1305} { ++ client, server := newEpochPair(t, cipherName) ++ old, err := server.Encrypt([]byte("epoch 1")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ server.mu.Lock() ++ if err := server.epoch.advanceSend(3); err != nil { ++ t.Fatal(err) ++ } ++ server.mu.Unlock() ++ packet, err := server.Encrypt([]byte("epoch 3")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if epoch := binary.BigEndian.Uint16(packet[4:6]); epoch != 3 { ++ t.Fatalf("server epoch %d", epoch) ++ } ++ if plain, err := client.Decrypt(packet); err != nil || string(plain) != "epoch 3" { ++ t.Fatalf("decrypt epoch 3: %q %v", plain, err) ++ } ++ // the retiring epoch still decrypts after the switch ++ if plain, err := client.Decrypt(old); err != nil || string(plain) != "epoch 1" { ++ t.Fatalf("decrypt retiring epoch: %q %v", plain, err) ++ } ++ reply, err := client.Encrypt([]byte("reply")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if epoch := binary.BigEndian.Uint16(reply[4:6]); epoch != 3 { ++ t.Fatalf("client did not follow to epoch 3, sent %d", epoch) ++ } ++ if id := binary.BigEndian.Uint64(reply[4:12]) & epochCounterMax; id != 1 { ++ t.Fatalf("counter did not restart: %d", id) ++ } ++ if plain, err := server.Decrypt(reply); err != nil || string(plain) != "reply" { ++ t.Fatalf("server decrypt: %q %v", plain, err) ++ } ++ // beyond the future window ++ server.mu.Lock() ++ if err := server.epoch.advanceSend(3 + epochFutureKeys + 1); err != nil { ++ t.Fatal(err) ++ } ++ server.mu.Unlock() ++ far, _ := server.Encrypt([]byte("far")) ++ if _, err := client.Decrypt(far); err == nil { ++ t.Fatal("epoch outside the future window accepted") ++ } ++ } ++} ++ ++func TestEpochSendKeyIteratesAtUsageLimit(t *testing.T) { ++ client, server := newEpochPair(t, CipherAES256GCM) ++ client.mu.Lock() ++ client.epoch.send.blocks = client.epoch.limit ++ client.mu.Unlock() ++ packet, err := client.Encrypt([]byte("x")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if epoch := binary.BigEndian.Uint16(packet[4:6]); epoch != 2 { ++ t.Fatalf("epoch %d, want 2", epoch) ++ } ++ if _, err := server.Decrypt(packet); err != nil { ++ t.Fatal(err) ++ } ++} ++ ++func TestPushReplyProtocolFlags(t *testing.T) { ++ reply, err := ParsePushReply("PUSH_REPLY,ifconfig 172.16.192.3 255.255.252.0,peer-id 7,cipher AES-256-GCM,protocol-flags cc-exit tls-ekm dyn-tls-crypt aead-epoch,tun-mtu 1500") ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !reply.TLSEKM || !reply.DynTLSCrypt || !reply.AEADEpoch || !reply.CCExit { ++ t.Fatalf("flags not parsed: %+v", reply) ++ } ++ legacy, err := ParsePushReply("PUSH_REPLY,ifconfig 10.8.0.2 255.255.255.0,key-derivation tls-ekm") ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !legacy.TLSEKM || legacy.DynTLSCrypt || legacy.AEADEpoch { ++ t.Fatalf("key-derivation: %+v", legacy) ++ } ++ // a token-only rekey push keeps the negotiated features ++ merged := mergePushReply(reply, &PushReply{PeerID: PeerIDUnset}) ++ if !merged.TLSEKM || !merged.DynTLSCrypt || !merged.AEADEpoch || !merged.CCExit { ++ t.Fatalf("merge lost flags: %+v", merged) ++ } ++} ++ ++func TestRawPeerInfo(t *testing.T) { ++ got := RawPeerInfo("IV_VER=3.11.1\r\n IV_PLAT=mac\n\nIV_PROTO=8094") ++ if want := "IV_VER=3.11.1\nIV_PLAT=mac\nIV_PROTO=8094\n"; got != want { ++ t.Fatalf("raw peer info %q, want %q", got, want) ++ } ++} ++ ++func TestDynamicTLSCryptWrapsRenegotiations(t *testing.T) { ++ clientIO, serverIO := newMemoryPacketPair() ++ defer clientIO.Close() ++ defer serverIO.Close() ++ base, err := NewTLSCrypt(testStaticKey(), true) ++ if err != nil { ++ t.Fatal(err) ++ } ++ dynKey := bytes.Repeat([]byte{0x5a}, staticKeySize) ++ dyn, err := NewTLSCrypt(dynKey, true) ++ if err != nil { ++ t.Fatal(err) ++ } ++ var id SessionID ++ copy(id[:], "client01") ++ channel := NewControlChannel(clientIO, base, id) ++ ctx := context.Background() ++ send := func(keyID uint8) []byte { ++ t.Helper() ++ packet := &ControlPacket{Opcode: PAckV1, KeyID: keyID, LocalSession: id, AckIDs: []uint32{1}} ++ if err := channel.writeControlPacket(ctx, packet); err != nil { ++ t.Fatal(err) ++ } ++ raw, err := serverIO.ReadPacket(ctx) ++ if err != nil { ++ t.Fatal(err) ++ } ++ return raw ++ } ++ send(0) ++ channel.SetRenegCrypt(dyn) ++ ++ serverBase, _ := NewTLSCrypt(testStaticKey(), false) ++ serverDyn, _ := NewTLSCrypt(dynKey, false) ++ if _, packetID, _, _, err := serverBase.Unwrap(send(0)); err != nil || packetID != 2 { ++ t.Fatalf("key 0 after dyn: id %d err %v", packetID, err) ++ } ++ raw := send(1) ++ if _, _, _, _, err := serverBase.Unwrap(raw); err == nil { ++ t.Fatal("key 1 wrapped with the original tls-crypt key") ++ } ++ // tls_wrap_reneg has its own packet ID sequence ++ if _, packetID, _, _, err := serverDyn.Unwrap(raw); err != nil || packetID != 1 { ++ t.Fatalf("key 1: id %d err %v", packetID, err) ++ } ++ ++ channel.mu.Lock() ++ defer channel.mu.Unlock() ++ if err := channel.checkKeyReplayLocked(0, 50, 1000); err != nil { ++ t.Fatal(err) ++ } ++ // the reneg window is separate: id 1 is fresh there ++ if err := channel.checkKeyReplayLocked(1, 1, 2000); err != nil { ++ t.Fatal(err) ++ } ++ if err := channel.checkKeyReplayLocked(0, 49, 1000); err != nil { ++ t.Fatalf("key 0 window disturbed by key 1: %v", err) ++ } ++} +diff --git a/transport/openvpn/keymethod.go b/transport/openvpn/keymethod.go +index 8f2c104..b451163 100644 +--- a/transport/openvpn/keymethod.go ++++ b/transport/openvpn/keymethod.go +@@ -11,6 +11,7 @@ import ( + "fmt" + "hash" + "sort" ++ "strconv" + "strings" + ) + +@@ -238,6 +239,12 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se + return nil, err + } + ++ return keyMaterialFromBlock(keyBlock, cipherKeyLen), nil ++} ++ ++// keyMaterialFromBlock splits an OpenVPN key2 block (two cipher+HMAC slots, ++// client-to-server first) into the client's send and receive keys. ++func keyMaterialFromBlock(keyBlock []byte, cipherKeyLen int) *KeyMaterial { + clientToServer := keyBlock[:maxCipherKeyLength+maxHMACKeyLength] + serverToClient := keyBlock[maxCipherKeyLength+maxHMACKeyLength:] + return &KeyMaterial{ +@@ -245,7 +252,7 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se + SendHMACKey: cloneBytes(clientToServer[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]), + RecvCipherKey: cloneBytes(serverToClient[:cipherKeyLen]), + RecvHMACKey: cloneBytes(serverToClient[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]), +- }, nil ++ } + } + + func InstallScriptOptionsString(proto, cipher, auth string, compLZO string) string { +@@ -311,6 +318,37 @@ func InstallScriptPeerInfo(cipher string, dataCiphers []string, compLZO string, + return info + } + ++// RawPeerInfo normalizes a verbatim peer-info block: one KEY=value per line, ++// blank lines dropped, each line newline-terminated like OpenVPN sends it. ++func RawPeerInfo(raw string) string { ++ var b strings.Builder ++ for _, line := range strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n") { ++ line = strings.TrimSpace(line) ++ if line == "" { ++ continue ++ } ++ b.WriteString(line) ++ b.WriteByte('\n') ++ } ++ return b.String() ++} ++ ++// IV_PROTO_TLS_KEY_EXPORT: the server derives the data keys with the TLS ++// keying material exporter. ++const ivProtoTLSKeyExport = 1 << 3 ++ ++// announcesKeyExport reports whether a raw peer-info announces ++// IV_PROTO_TLS_KEY_EXPORT. ++func announcesKeyExport(peerInfo string) bool { ++ for _, line := range strings.Split(peerInfo, "\n") { ++ if value, ok := strings.CutPrefix(strings.TrimSpace(line), "IV_PROTO="); ok { ++ proto, err := strconv.Atoi(value) ++ return err == nil && proto&ivProtoTLSKeyExport != 0 ++ } ++ } ++ return false ++} ++ + func appendOpenVPNString(out []byte, s string) []byte { + if s == "" { + return binary.BigEndian.AppendUint16(out, 0) +diff --git a/transport/openvpn/push.go b/transport/openvpn/push.go +index df84904..ae17dcb 100644 +--- a/transport/openvpn/push.go ++++ b/transport/openvpn/push.go +@@ -29,6 +29,14 @@ type PushReply struct { + // option (legacy or fallback). + Cipher string + ++ // Negotiated protocol features ("protocol-flags", or the older ++ // "key-derivation tls-ekm"). The server enables them for the bits the ++ // client announced in IV_PROTO. ++ TLSEKM bool // data keys from the TLS keying material exporter ++ DynTLSCrypt bool // control packets of key IDs > 0 use a derived tls-crypt key ++ AEADEpoch bool // epoch data key format ++ CCExit bool // exit notification as an EXIT control message ++ + // AuthToken is the most recently pushed auth-token / auth-token-user + // pair. Empty when the server does not rotate credentials. + AuthTokenUser string +@@ -144,6 +152,23 @@ func parsePushReplyInner(message string) (*PushReply, error) { + if len(fields) >= 2 { + reply.Cipher = strings.TrimSpace(fields[1]) + } ++ case "key-derivation": ++ if len(fields) >= 2 && fields[1] == "tls-ekm" { ++ reply.TLSEKM = true ++ } ++ case "protocol-flags": ++ for _, flag := range fields[1:] { ++ switch flag { ++ case "tls-ekm": ++ reply.TLSEKM = true ++ case "dyn-tls-crypt": ++ reply.DynTLSCrypt = true ++ case "aead-epoch": ++ reply.AEADEpoch = true ++ case "cc-exit": ++ reply.CCExit = true ++ } ++ } + case "auth-token": + if len(fields) >= 2 { + reply.AuthTokenPass = strings.TrimSpace(fields[1])