Improvec ovpn luci

This commit is contained in:
Sam Latsin 2026-10-15 13:57:32 +03:00
parent 00d0ffafcb
commit b49756d7bc
6 changed files with 481 additions and 148 deletions

View File

@ -64,19 +64,27 @@ mihomo-kit.sh use foreign # за рубежом: российское чер
bmstu-otp.sh off # OpenVPN выключить: освободить сессию для другого устройства bmstu-otp.sh off # OpenVPN выключить: освободить сессию для другого устройства
bmstu-otp.sh on # включить обратно bmstu-otp.sh on # включить обратно
bmstu-otp.sh for 60 # поднять на 60 минут, потом само выключится bmstu-otp.sh for 60 # поднять на 60 минут, потом вернуть как было
bmstu-otp.sh sched 09:00 17:00 # работать только в эти часы (МСК); sched off — отключить bmstu-otp.sh sched 09:00 17:00 # работать только в эти часы (МСК); sched off — отключить
bmstu-otp.sh status bmstu-otp.sh status # что решает сейчас, когда следующее переключение, отвечает ли туннель
``` ```
Эти же кнопки и поле расписания есть на странице LuCI (Службы → mihomo-kit). Эти же кнопки и поле расписания есть на странице LuCI (Службы → mihomo-kit). Там же видно,
что решает сейчас («включён по расписанию», «выключен вручную», «включён таймером до 15:30»)
и что будет дальше («выключится сегодня в 17:06», «потом снова действует ручное „Выключить“»).
Приоритеты: ручное «Выключить» держится поверх расписания, пока не нажмёшь «Включить». Кто главнее: таймер (`for`) → ручное «Выключить» → расписание.
Таймер (`for`) и расписание поднимают туннель, но ручной офф их перебивает. По истечении - «Выключить» держится, пока не нажмёшь «Включить»: расписание его не снимает.
таймера управление возвращается расписанию. Вне рабочих часов поднять туннель можно - Таймер поднимает туннель поверх всего, а когда истекает, возвращает то, что было до него:
таймером — обычное «Включить» расписание тут же погасит. Время — локальное на роутере (МСК); ручное выключение или расписание. «Выключить» во время таймера его отменяет.
у границ окна добавляется разброс до ±10 минут, свой на каждый день, чтобы включение и - «Включить» снимает ручное выключение и таймер, дальше решает расписание: вне окна туннель
выключение не приходились каждый раз на одну и ту же секунду. останется выключенным, поднять его там можно таймером. Без расписания туннель включён всегда.
Время — локальное на роутере (МСК). Границы окна каждый день сдвигаются на случайные, но
постоянные в течение дня ±10 минут (`OVPN_SCHED_JITTER`), чтобы включение и выключение не
приходились каждый раз на одну и ту же секунду. Поэтому окно короче 20 минут (или длиннее
23 ч 40 мин) не принимается. Маршруты BMSTU (`OVPN_ROUTES`) следуют за туннелем: пока он
выключен по любой причине, они убраны.
На сервере BMSTU одна сессия на пользователя. `off` закрывает туннель в mihomo и не даёт На сервере BMSTU одна сессия на пользователя. `off` закрывает туннель в mihomo и не даёт
cron поднять его снова, и убирает его подсети (`OVPN_ROUTES`) из маршрутизации: они лежат в cron поднять его снова, и убирает его подсети (`OVPN_ROUTES`) из маршрутизации: они лежат в
@ -102,13 +110,17 @@ mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=2
те же строки в том же порядке, что в логе Connect; те же строки в том же порядке, что в логе Connect;
- протокол: в ответ на `IV_PROTO=8094` сервер включает `tls-ekm` (ключи из TLS-экспортёра), - протокол: в ответ на `IV_PROTO=8094` сервер включает `tls-ekm` (ключи из TLS-экспортёра),
`dyn-tls-crypt` (свой tls-crypt-ключ для rekey) и `aead-epoch` (формат данных OpenVPN 2.7), `dyn-tls-crypt` (свой tls-crypt-ключ для rekey) и `aead-epoch` (формат данных OpenVPN 2.7),
и ядро kit их поддерживает; и ядро kit их поддерживает. Ещё 8094 объявляет `AUTH_FAIL_TEMP` (временный отказ — ядро
повторяет позже, а не считает пароль отклонённым), `DNS_OPTION_V2` (DNS из `dns server …`
ядро берёт так же, как из `dhcp-option DNS`), `AUTH_PENDING_KW` и `PUSH_UPDATE` (сообщения,
которые ядро пропускает);
- пароль в формате `SCRV1`, как отправляет Connect при `static-challenge`; - пароль в формате `SCRV1`, как отправляет Connect при `static-challenge`;
- `ping 60`, `ping-restart 300` — то, что присылает сервер; - `ping 60`, `ping-restart 300` — то, что присылает сервер;
- туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу - туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу
при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo
пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро через 2 с пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро через 2 с
переподключается само, с auth-token сессии вместо пароля и OTP. Если сервер токен не переподключается само, с auth-token сессии вместо пароля и OTP; если не вышло, пауза
удваивается до минуты, чтобы недоступный сервер не забивал лог. Если сервер токен не
принял (AUTH_FAILED), ядро больше не пробует — как Connect, который тогда просит новый принял (AUTH_FAILED), ядро больше не пробует — как Connect, который тогда просит новый
OTP, — и туннель поднимает cron (`bmstu-otp.sh check`) со свежим OTP; OTP, — и туннель поднимает cron (`bmstu-otp.sh check`) со свежим OTP;
- при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT - при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT

View File

@ -35,6 +35,47 @@ function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children)); return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
} }
// OpenVPN: what decides the tunnel now and what happens next, from
// bmstu-otp.sh state (via ovpn_status) -> { now, next, pending }
function ovpnMode(o) {
var at = function(hm, day) {
return (day == 'today' ? 'сегодня' : day == 'tomorrow' ? 'завтра' : day) + ' в ' + hm;
};
var r = {};
switch (o.mode) {
case 'timer':
r.now = 'включён таймером до ' + o.until_hm +
(o.until_day == 'today' ? '' : o.until_day == 'tomorrow' ? ' завтра' : ' ' + o.until_day);
if (o.after == 'off')
r.next = 'потом выключится: ' + (o.why == 'manual'
? 'снова действует ручное «Выключить»'
: 'это вне расписания' + (o.next && o.next_to == 'on' ? ', включится ' + at(o.next_hm, o.next_day) : ''));
else
r.next = 'потом останется включённым: ' + (o.why == 'always' ? 'расписание выключено' : 'это внутри расписания');
break;
case 'manual':
r.now = 'выключен вручную';
r.next = 'сам не включится: расписание не действует, пока не нажмёшь «Включить» (или «на 1 ч»)';
break;
case 'schedule':
r.now = o.want ? 'включён по расписанию' : 'выключен по расписанию';
if (o.next)
r.next = (o.next_to == 'off' ? 'выключится ' : 'включится ') + at(o.next_hm, o.next_day);
break;
case 'always':
r.now = 'включён постоянно';
r.next = 'сам не выключится: расписание выключено';
break;
default:
r.now = 'неизвестно';
}
if (o.want && o.tunnel == 'down')
r.pending = 'туннель ещё закрыт, cron поднимет в течение минуты';
else if (!o.want && o.tunnel == 'up')
r.pending = 'туннель ещё открыт, cron закроет в течение минуты';
return r;
}
// form helpers for the settings section // form helpers for the settings section
function text(value, placeholder, type) { function text(value, placeholder, type) {
return E('input', { 'type': type || 'text', 'class': 'cbi-input-text', 'style': 'width:100%', return E('input', { 'type': type || 'text', 'class': 'cbi-input-text', 'style': 'width:100%',
@ -268,6 +309,8 @@ return view.extend({
if (st.openvpn) { if (st.openvpn) {
var ovpnState = E('span', '—'); var ovpnState = E('span', '—');
var otp = E('span', '—'); var otp = E('span', '—');
var modeNow = E('span', '—');
var modeNext = E('span', '—');
var schedInfo = E('span', '—'); var schedInfo = E('span', '—');
var schedOn = E('input', { 'type': 'checkbox' }); var schedOn = E('input', { 'type': 'checkbox' });
var schedStart = E('input', { 'type': 'time', 'value': '09:00' }); var schedStart = E('input', { 'type': 'time', 'value': '09:00' });
@ -284,9 +327,14 @@ return view.extend({
if (o.url) if (o.url)
ovpnState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', o.url ])); ovpnState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', o.url ]));
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—'); dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
var bits = [ o.sched ? 'расписание ' + o.sched_start + '–' + o.sched_end + ' MSK' : 'расписание выключено' ]; var m = ovpnMode(o);
if (o.until) bits.push('таймер ещё ' + Math.max(1, Math.round((o.until * 1000 - Date.now()) / 60000)) + ' мин'); dom.content(modeNow, [ E('strong', m.now) ].concat(m.pending
dom.content(schedInfo, bits.join(', ')); ? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : []));
dom.content(modeNext, m.next || '—');
dom.content(schedInfo, o.sched
? 'с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter +
' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '')
: 'выключено');
if (!schedFilled) { if (!schedFilled) {
schedOn.checked = !!o.sched; schedOn.checked = !!o.sched;
if (o.sched_start) schedStart.value = o.sched_start; if (o.sched_start) schedStart.value = o.sched_start;
@ -301,20 +349,26 @@ return view.extend({
row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, ovpnCheck) }, 'Проверить') ]), 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Проверить') ]),
row('OTP сейчас', otp), row('OTP сейчас', otp),
row('Режим', schedInfo) row('Сейчас', modeNow),
row('Дальше', modeNext),
row('Расписание', schedInfo)
]), ]),
E('div', { 'class': 'cbi-page-actions' }, [ E('div', { 'class': 'cbi-page-actions' }, [
this.button('Включить', 'positive', 'ovpn-on'), ' ', this.button('Включить', 'positive', 'ovpn-on'), ' ',
this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'), ' ', this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'), ' ',
this.button('Выключить', 'negative', 'ovpn-off', null, this.button('Выключить', 'negative', 'ovpn-off', null,
'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ', 'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить»? ' +
'С ядром kit сессия на сервере освобождается сразу, с другим ядром — через ~5 минут.'), ' ',
this.button('Переподключить', 'action', 'ovpn-refresh') this.button('Переподключить', 'action', 'ovpn-refresh')
]), ]),
field('Расписание (MSK)', [ schedOn, ' ', schedStart, ' – ', schedEnd, ' ', field('Расписание (MSK)', [ schedOn, ' ', schedStart, ' – ', schedEnd, ' ',
this.button('Сохранить', 'action', 'ovpn-sched', function() { this.button('Сохранить', 'action', 'ovpn-sched', function() {
return schedOn.checked ? schedStart.value + ' ' + schedEnd.value : 'off'; return schedOn.checked ? schedStart.value + ' ' + schedEnd.value : 'off';
}) ], }) ],
'Туннель работает только в эти часы (±10 мин разброс). Ручное «Выключить» держится поверх расписания до «Включить». «на 1 ч» поднимает вне окна.') 'Туннель работает только в эти часы. Кто главнее: «на 1 ч» → «Выключить» → расписание. ' +
'«Выключить» держится, пока не нажмёшь «Включить», расписание его не снимает. ' +
'«на 1 ч» поднимает туннель поверх всего, а по окончании возвращает как было: ручное выключение или расписание. ' +
'«Включить» снимает ручное выключение и таймер, дальше решает расписание (вне окна туннель останется выключенным).')
])); ]));
} }

View File

@ -33,11 +33,6 @@ envval() {
sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\"" sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\""
} }
# bmstuval VAR -> value from bmstu.env (OpenVPN schedule lives there)
bmstuval() {
sed -n "s/^$1=//p" "$NIKKI_DIR/bmstu.env" 2>/dev/null | tail -n 1 | tr -d "'\""
}
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; } q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; } job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; }
@ -126,7 +121,17 @@ delay_check() {
m_ovpn_status() { m_ovpn_status() {
json_init json_init
if [ -f "$NIKKI_DIR/bmstu.off" ]; then # what decides the tunnel now and the next change (bmstu-otp.sh state); only
# known keys with plain values get through to eval
eval "$(bmstu-otp.sh state 2>/dev/null |
sed -En 's/^(mode|want|tunnel|until|until_hm|until_day|after|why|next|next_to|next_hm|next_day|win|sched|sched_start|sched_end|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p')"
for k in mode tunnel until_hm until_day after why next_to next_hm next_day win sched_start sched_end; do
eval "json_add_string $k \"\${st_$k:-}\""
done
for k in want until next sched jitter; do
eval "json_add_int $k \"\${st_$k:-0}\""
done
if [ "${st_tunnel:-}" = down ]; then
json_add_string state off json_add_string state off
else else
prof=$(uci -q get nikki.config.profile) prof=$(uci -q get nikki.config.profile)
@ -136,12 +141,6 @@ m_ovpn_status() {
fi fi
json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)" json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)"
json_add_int otp_left "$((30 - $(date +%s) % 30))" json_add_int otp_left "$((30 - $(date +%s) % 30))"
json_add_boolean sched "$(b test "$(bmstuval OVPN_SCHED)" = 1)"
json_add_string sched_start "$(bmstuval OVPN_SCHED_START)"
json_add_string sched_end "$(bmstuval OVPN_SCHED_END)"
_until=$(cat "$NIKKI_DIR/bmstu.until" 2>/dev/null)
case "$_until" in '' | *[!0-9]*) _until=0 ;; esac
[ "$_until" -gt "$(date +%s)" ] && json_add_int until "$_until" || json_add_int until 0
json_dump json_dump
} }

View File

@ -14,17 +14,21 @@
# bmstu-otp.sh otp print the current TOTP code # 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 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 refresh regenerate provider with fresh OTP, reload, warm up
# bmstu-otp.sh up refresh unless the tunnel already answers # bmstu-otp.sh up bring the tunnel up if it should be up and does not answer
# bmstu-otp.sh write only regenerate the provider (nikki init, before mihomo starts) # bmstu-otp.sh write only regenerate the provider and routes (nikki init, before mihomo starts)
# bmstu-otp.sh check reconcile to the desired state (schedule/timer/manual); the # bmstu-otp.sh check reconcile to the desired state (timer/manual/schedule); the
# two-probe test refreshes a dead tunnel (cron, once a minute) # two-probe test refreshes a dead tunnel (cron, once a minute)
# bmstu-otp.sh for N bring the tunnel up for N minutes, then let the schedule resume # bmstu-otp.sh for N up for N minutes over the manual off and the schedule, then back
# to whatever held before
# bmstu-otp.sh sched ... off | on | HH:MM HH:MM: work-hours schedule (MSK), persisted # bmstu-otp.sh sched ... off | on | HH:MM HH:MM: work-hours schedule (MSK), persisted
# bmstu-otp.sh off close the tunnel and keep it closed (sticky, wins over the schedule; # bmstu-otp.sh off close the tunnel and keep it closed (sticky, wins over the schedule,
# BMSTU traffic goes without it); frees the single server session (the # cancels a timer; BMSTU traffic goes without it); frees the single
# kit core sends EXIT; other cores leave it until ping-restart, ~5 min) # server session (the kit core sends EXIT; other cores leave it until
# bmstu-otp.sh on allow the tunnel again and bring it up # ping-restart, ~5 min)
# bmstu-otp.sh status on/off and whether the tunnel answers # bmstu-otp.sh on drop the manual off and the timer: the schedule (if any) decides
# bmstu-otp.sh status what decides now, the next change, whether the tunnel answers
# bmstu-otp.sh state the same as key=value lines (LuCI)
# bmstu-otp.sh want exit code: should the tunnel be up now
# bmstu-otp.sh debug show the real handshake error in the nikki log # bmstu-otp.sh debug show the real handshake error in the nikki log
set -u set -u
@ -198,7 +202,8 @@ write_provider() {
pass=$(make_password "$(fresh_totp)") || exit 1 pass=$(make_password "$(fresh_totp)") || exit 1
mkdir -p "$(dirname "$PROVIDER_FILE")" mkdir -p "$(dirname "$PROVIDER_FILE")"
tmp="$PROVIDER_FILE.tmp" # per process: the init hook can write while a cron refresh does
tmp="$PROVIDER_FILE.tmp.$$"
{ {
echo "# generated by bmstu-otp.sh at $(date '+%F %T') - do not edit" echo "# generated by bmstu-otp.sh at $(date '+%F %T') - do not edit"
echo "proxies:" echo "proxies:"
@ -271,23 +276,27 @@ write_off_provider() {
# rule-provider <PROVIDER_NAME>-routes (written by mihomo-kit.sh build): with the # rule-provider <PROVIDER_NAME>-routes (written by mihomo-kit.sh build): with the
# tunnel off it is emptied, so BMSTU addresses follow the normal rules # tunnel off it is emptied, so BMSTU addresses follow the normal rules
ROUTES=${ROUTES:-$(dirname "$PROVIDER_FILE")/$PROVIDER_NAME-routes} ROUTES=${ROUTES:-$(dirname "$PROVIDER_FILE")/$PROVIDER_NAME-routes}
routes_set() { routes_body() {
if [ "$1" = off ]; then if [ "$1" = off ]; then
echo 'payload: []' > "$ROUTES.yaml" echo 'payload: []'
elif [ -f "$ROUTES.all" ]; then elif [ -f "$ROUTES.all" ]; then
{ echo 'payload:'
echo 'payload:' while read -r r; do [ -n "$r" ] && echo " - '$r'"; done < "$ROUTES.all"
while read -r r; do [ -n "$r" ] && echo " - '$r'"; done < "$ROUTES.all"
} > "$ROUTES.yaml"
else
return 0
fi fi
}
# routes_set on|off [file]: write the routes for that state and reload them in
# mihomo if they changed ("file": only write, mihomo is not running yet)
routes_set() {
_body=$(routes_body "$1")
[ -n "$_body" ] || return 0
[ "$(cat "$ROUTES.yaml" 2>/dev/null)" = "$_body" ] && return 0
printf '%s\n' "$_body" > "$ROUTES.yaml"
[ "${2:-}" = file ] && return 0
api PUT "/providers/rules/$PROVIDER_NAME-routes" >/dev/null || api PUT "/providers/rules/$PROVIDER_NAME-routes" >/dev/null ||
log "warning: routes reload failed (API $API), applies on the next nikki restart" log "warning: routes reload failed (API $API), applies on the next nikki restart"
} }
refresh() { refresh() {
[ -f "$OFF_FLAG" ] && die "OpenVPN is off (bmstu-otp.sh on)"
write_provider write_provider
wait_api wait_api
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
@ -317,6 +326,12 @@ hhmm_to_min() {
echo $((_h * 60 + _m)) echo $((_h * 60 + _m))
} }
# minutes since midnight (may be out of 0..1439 by the jitter) -> HH:MM
min_to_hhmm() {
_x=$((($1 % 1440 + 1440) % 1440))
printf '%02d:%02d\n' $((_x / 60)) $((_x % 60))
}
# deterministic offset in [-JITTER, +JITTER] minutes for a seed (date + edge), # deterministic offset in [-JITTER, +JITTER] minutes for a seed (date + edge),
# so each edge shifts by a fixed amount for the whole day and differs day to day # so each edge shifts by a fixed amount for the whole day and differs day to day
jitter_min() { jitter_min() {
@ -327,15 +342,22 @@ jitter_min() {
echo $((0x$_hex % _span - OVPN_SCHED_JITTER)) echo $((0x$_hex % _span - OVPN_SCHED_JITTER))
} }
# true when now is inside the (jittered) schedule window; handles a window that # jittered window edges of a day (YYYY-MM-DD) in minutes since its midnight ->
# wraps past midnight (END <= START). NOW_MIN/SCHED_DAY override the clock in tests. # _s _e; non-zero on a malformed setting
sched_edges() {
_s=$(hhmm_to_min "$OVPN_SCHED_START") || { log "bad OVPN_SCHED_START=$OVPN_SCHED_START"; return 1; }
_e=$(hhmm_to_min "$OVPN_SCHED_END") || { log "bad OVPN_SCHED_END=$OVPN_SCHED_END"; return 1; }
_s=$((_s + $(jitter_min "$1 start")))
_e=$((_e + $(jitter_min "$1 end")))
}
# in_window [day minute]: true when that moment (default: now) is inside the
# jittered window of the day; a window with END < START wraps past midnight.
# A malformed setting counts as inside. NOW_MIN/SCHED_DAY override the clock in tests.
in_window() { in_window() {
_now=${NOW_MIN:-$(hhmm_to_min "$(date +%H:%M)")} _day=${1:-${SCHED_DAY:-$(date +%F)}}
_day=${SCHED_DAY:-$(date +%F)} _now=${2:-${NOW_MIN:-$(hhmm_to_min "$(date +%H:%M)")}}
_s=$(hhmm_to_min "$OVPN_SCHED_START") || { log "bad OVPN_SCHED_START=$OVPN_SCHED_START"; return 0; } sched_edges "$_day" || return 0
_e=$(hhmm_to_min "$OVPN_SCHED_END") || { log "bad OVPN_SCHED_END=$OVPN_SCHED_END"; return 0; }
_s=$((_s + $(jitter_min "$_day start")))
_e=$((_e + $(jitter_min "$_day end")))
if [ "$_s" -le "$_e" ]; then if [ "$_s" -le "$_e" ]; then
[ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ]
else else
@ -343,19 +365,126 @@ in_window() {
fi fi
} }
# desired state: should the tunnel be up now? (prints nothing, sets exit code) # end of the running timer (epoch) on stdout; an expired or broken one is removed
want_up() { timer_until() {
[ -f "$OFF_FLAG" ] && return 1 [ -f "$UNTIL_FLAG" ] || return 1
if [ -f "$UNTIL_FLAG" ]; then _u=$(cat "$UNTIL_FLAG" 2>/dev/null)
_until=$(cat "$UNTIL_FLAG" 2>/dev/null) case "$_u" in
case "$_until" in '' | *[!0-9]*) rm -f "$UNTIL_FLAG" ;; esac '' | *[!0-9]*) ;;
if [ -n "$_until" ] && [ "$(date +%s)" -lt "$_until" ]; then *) [ "$(date +%s)" -lt "$_u" ] && { echo "$_u"; return 0; } ;;
return 0 esac
fi rm -f "$UNTIL_FLAG"
rm -f "$UNTIL_FLAG" return 1
}
# the state without a timer, at [day minute] (default: now):
# "off manual" | "on always" | "on schedule" | "off schedule"
base_state() {
if [ -f "$OFF_FLAG" ]; then
echo "off manual"
elif [ "${OVPN_SCHED:-0}" != 1 ]; then
echo "on always"
elif in_window "$@"; then
echo "on schedule"
else
echo "off schedule"
fi fi
[ "${OVPN_SCHED:-0}" = 1 ] || return 0 }
in_window
# desired state: should the tunnel be up now? Priority: the timer (for N), then
# the manual off, then the schedule. The timer lifts a manual off only while it
# runs: when it ends, the off holds again.
want_up() {
timer_until >/dev/null && return 0
case "$(base_state)" in on*) return 0 ;; esac
return 1
}
# next schedule edge after now -> _next (epoch) _next_to (on|off); the window
# check of sched keeps today's and tomorrow's windows the same shape
sched_next() {
_t=$(date +%s)
set -- $(date -d "@$_t" '+%F %H:%M %S')
_m=$(hhmm_to_min "$2") || return 1
_mid=$((_t - _m * 60 - ${3#0}))
sched_edges "$1" || return 1
_s0=$_s _e0=$_e
sched_edges "$(date -d "@$((_mid + 86400 + 3600))" +%F)" || return 1
if [ "$_s0" -le "$_e0" ]; then
if [ "$_m" -lt "$_s0" ]; then
_next=$((_mid + _s0 * 60)) _next_to=on
elif [ "$_m" -lt "$_e0" ]; then
_next=$((_mid + _e0 * 60)) _next_to=off
else
_next=$((_mid + 86400 + _s * 60)) _next_to=on
fi
elif [ "$_m" -lt "$_e0" ]; then
_next=$((_mid + _e0 * 60)) _next_to=off
elif [ "$_m" -lt "$_s0" ]; then
_next=$((_mid + _s0 * 60)) _next_to=on
else
_next=$((_mid + 86400 + _e * 60)) _next_to=off
fi
}
# epoch -> "HH:MM today|tomorrow|YYYY-MM-DD" in router-local time
when() {
_d=$(date -d "@$1" +%F)
if [ "$_d" = "$(date +%F)" ]; then
_d=today
elif [ "$_d" = "$(date -d "@$(($(date +%s) + 86400))" +%F)" ]; then
_d=tomorrow
fi
echo "$(date -d "@$1" +%H:%M) $_d"
}
# the whole picture as key=value lines (for status and LuCI):
# mode timer | manual | schedule | always: what decides now
# want 1 when the tunnel should be up now
# tunnel up | down: whether the provider holds the tunnel (not a probe)
# until timer end (epoch, 0 = none), until_hm, until_day (today|tomorrow|date)
# after on | off once the timer ends, why: manual | schedule | always
# next next schedule change (epoch, 0 = none), next_to on | off, next_hm, next_day
# win today's window with the jitter, HH:MM-HH:MM
# sched sched_start sched_end jitter: the settings
state() {
_until=$(timer_until) || _until=0
set -- $(base_state)
if [ "$_until" -gt 0 ]; then
_mode=timer _want=1
set -- $(date -d "@$_until" '+%F %H:%M')
set -- $(base_state "$1" "$(hhmm_to_min "$2")")
_after=$1 _why=$2
set -- $(when "$_until")
echo "until=$_until"
echo "until_hm=$1"
echo "until_day=$2"
echo "after=$_after"
echo "why=$_why"
else
_mode=$2 _want=0
[ "$1" = on ] && _want=1
echo "until=0"
fi
echo "mode=$_mode"
echo "want=$_want"
tunnel_is_down && echo "tunnel=down" || echo "tunnel=up"
if [ "${OVPN_SCHED:-0}" = 1 ] && sched_next; then
set -- $(when "$_next")
echo "next=$_next"
echo "next_to=$_next_to"
echo "next_hm=$1"
echo "next_day=$2"
else
echo "next=0"
fi
if sched_edges "$(date +%F)"; then
echo "win=$(min_to_hhmm "$_s")-$(min_to_hhmm "$_e")"
fi
echo "sched=${OVPN_SCHED:-0}"
echo "sched_start=$OVPN_SCHED_START"
echo "sched_end=$OVPN_SCHED_END"
echo "jitter=$OVPN_SCHED_JITTER"
} }
# persist KEY=value in the env file (bmstu.env) and apply it to this process, # persist KEY=value in the env file (bmstu.env) and apply it to this process,
@ -382,13 +511,14 @@ tunnel_down() {
routes_set off routes_set off
} }
# bring the desired state about. repair=1 uses the two-probe test before a # bring the desired state about, routes included. "repair" uses the two-probe
# refresh of an already-up tunnel (steady-state cron); otherwise act at once. # test before a refresh of an already-up tunnel (steady-state cron); otherwise
# act at once.
reconcile() { reconcile() {
if want_up; then if want_up; then
routes_set on
if tunnel_is_down; then if tunnel_is_down; then
log "bringing the tunnel up" log "bringing the tunnel up"
routes_set on
refresh refresh
elif [ "${1:-}" = repair ]; then elif [ "${1:-}" = repair ]; then
alive && return 0 alive && return 0
@ -397,72 +527,100 @@ reconcile() {
alive && return 0 alive && return 0
log "tunnel is down (2 failed probes), refreshing" log "tunnel is down (2 failed probes), refreshing"
refresh refresh
elif alive; then
log "tunnel is up"
else else
alive || refresh refresh
fi fi
elif tunnel_is_down; then
routes_set off
else else
if ! tunnel_is_down; then log "OpenVPN should be off now ($(base_state | cut -d' ' -f2)), taking the tunnel down"
log "schedule: outside the window, taking the tunnel down" tunnel_down
tunnel_down
fi
fi fi
} }
# one state change at a time (cron check, LuCI buttons, use): lock_take <wait s>
LOCK=${LOCK:-/tmp/bmstu-otp.lock}
lock_take() {
_w=0
until mkdir "$LOCK" 2>/dev/null; do
_p=$(cat "$LOCK/pid" 2>/dev/null)
# a holder that died; an empty pid is one that has not written it yet
if [ -n "$_p" ] && ! kill -0 "$_p" 2>/dev/null; then
rm -rf "$LOCK"
continue
fi
[ "$_w" -ge "$1" ] && return 1
sleep 1
_w=$((_w + 1))
done
echo $$ > "$LOCK/pid"
trap 'rm -rf "$LOCK"' EXIT
}
# a check with two probes and a refresh takes up to ~2 min
lock_wait() { lock_take 150 || die "busy: another bmstu-otp.sh run holds $LOCK"; }
case "${1:-}" in case "${1:-}" in
otp) totp ;; otp) totp ;;
# auth-user-pass file for testing with the real openvpn client # auth-user-pass file for testing with the real openvpn client
authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;; authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;;
refresh) refresh ;; refresh)
up) lock_wait
[ -f "$OFF_FLAG" ] && exit 0 want_up || die "OpenVPN is off now ($(base_state | cut -d' ' -f2)): bmstu-otp.sh on, or for <min>"
wait_api routes_set on
alive && { log "tunnel is up"; exit 0; }
want_up || { log "schedule: outside the window, staying down"; exit 0; }
refresh refresh
;; ;;
write) up)
# init-script hook: write a fresh-OTP provider before mihomo starts, but lock_wait
# only where OpenVPN is set up and the tunnel should be up now want_up || { log "OpenVPN is off now ($(base_state | cut -d' ' -f2)), staying down"; exit 0; }
[ -f "$OFF_FLAG" ] || [ ! -f "$PROVIDER_FILE" ] && exit 0 wait_api
want_up || { write_off_provider; exit 0; } reconcile
write_provider
;; ;;
check) write)
[ -f "$OFF_FLAG" ] && exit 0 # init-script hook: before mihomo starts, a fresh-OTP provider (or the off
# one run at a time: two slow probes can outlast the cron minute # one) and the matching routes, only where OpenVPN is set up
lock=/tmp/bmstu-otp.lock [ -f "$PROVIDER_FILE" ] || exit 0
if ! mkdir "$lock" 2>/dev/null; then if want_up; then
kill -0 "$(cat "$lock/pid" 2>/dev/null)" 2>/dev/null && exit 0 routes_set on file
rm -rf "$lock" write_provider
mkdir "$lock" || exit 0 else
routes_set off file
write_off_provider
fi fi
echo $$ > "$lock/pid" ;;
trap 'rm -rf "$lock"' EXIT # exit code only: should the tunnel be up now (mihomo-kit.sh build, routes)
want) want_up ;;
check)
# one run at a time: two slow probes can outlast the cron minute
lock_take 0 || exit 0
reconcile repair reconcile repair
;; ;;
off) off)
lock_wait
touch "$OFF_FLAG" touch "$OFF_FLAG"
rm -f "$UNTIL_FLAG" rm -f "$UNTIL_FLAG"
write_off_provider tunnel_down
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 kit core tells the server (EXIT), other cores leave the session until 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) on)
lock_wait
rm -f "$OFF_FLAG" "$UNTIL_FLAG" rm -f "$OFF_FLAG" "$UNTIL_FLAG"
wait_api wait_api
reconcile reconcile
;; ;;
# bring the tunnel up for N minutes, then let the schedule resume (overrides # bring the tunnel up for N minutes, over the manual off and the schedule;
# the schedule while it runs; the cron takes it down when the timer expires) # then whatever was in force before holds again (the cron applies it)
for) for)
case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for <minutes>" ;; esac case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for <minutes>" ;; esac
rm -f "$OFF_FLAG" lock_wait
echo "$(( $(date +%s) + $2 * 60 ))" > "$UNTIL_FLAG" echo "$(($(date +%s) + $2 * 60))" > "$UNTIL_FLAG"
wait_api wait_api
reconcile reconcile
log "OpenVPN on for $2 min (until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || date '+%H:%M'))" rc=$?
eval "$(state)"
log "OpenVPN on for $2 min, until $until_hm; then $after ($why)"
exit $rc
;; ;;
# schedule: "sched off" | "sched on" | "sched HH:MM HH:MM" (and enable). # schedule: "sched off" | "sched on" | "sched HH:MM HH:MM" (and enable).
# Persists to the env file so the cron and the init hook read the same thing. # Persists to the env file so the cron and the init hook read the same thing.
@ -476,10 +634,19 @@ case "${1:-}" in
fi fi
exit 0 exit 0
;; ;;
esac
lock_wait
case "$2" in
off) sched_set OVPN_SCHED 0 ;; off) sched_set OVPN_SCHED 0 ;;
on) sched_set OVPN_SCHED 1 ;; on) sched_set OVPN_SCHED 1 ;;
[0-9][0-9]:[0-9][0-9]) [0-9][0-9]:[0-9][0-9])
hhmm_to_min "$2" >/dev/null && hhmm_to_min "${3:-}" >/dev/null || die "usage: bmstu-otp.sh sched HH:MM HH:MM" _a=$(hhmm_to_min "$2") && _b=$(hhmm_to_min "${3:-}") || die "usage: bmstu-otp.sh sched HH:MM HH:MM"
# the jittered edges must not cross, or the window flips between
# almost the whole day and nothing from day to day
_j=$((${OVPN_SCHED_JITTER:-0} * 2))
_len=$(((_b - _a + 1440) % 1440))
[ "$_len" -gt "$_j" ] && [ "$_len" -lt $((1440 - _j)) ] ||
die "the window must be longer than $_j min and shorter than 24 h minus $_j min (jitter +-${OVPN_SCHED_JITTER:-0} min)"
sched_set OVPN_SCHED_START "$2" sched_set OVPN_SCHED_START "$2"
sched_set OVPN_SCHED_END "$3" sched_set OVPN_SCHED_END "$3"
sched_set OVPN_SCHED 1 sched_set OVPN_SCHED 1
@ -489,18 +656,31 @@ case "${1:-}" in
wait_api wait_api
reconcile reconcile
;; ;;
state) state ;;
status) status)
if [ -f "$OFF_FLAG" ]; then eval "$(state)"
echo "off (manual)" case "$mode" in
elif [ -f "$UNTIL_FLAG" ] && [ "$(date +%s)" -lt "$(cat "$UNTIL_FLAG" 2>/dev/null || echo 0)" ]; then timer) echo "on by timer until $until_hm $until_day, then $after ($why)" ;;
echo "on by timer until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || echo '?'), $(alive && echo 'tunnel up' || echo 'tunnel down')" manual) echo "off (manual, until bmstu-otp.sh on)" ;;
elif ! want_up; then always) echo "on (no schedule)" ;;
echo "off by schedule ($OVPN_SCHED_START-$OVPN_SCHED_END MSK)" schedule)
elif alive; then [ "$want" = 1 ] && echo "on by schedule" || echo "off by schedule"
echo "on, tunnel is up" ;;
else esac
echo "on, tunnel is down (cron brings it up within a minute)" if [ "$next" -gt 0 ]; then
echo "schedule: $sched_start-$sched_end MSK, today $win (jitter +-$jitter min)"
[ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day"
fi fi
if [ "$tunnel" = down ]; then
echo "tunnel closed"
elif alive; then
echo "tunnel is up"
else
echo "tunnel does not answer (the cron check refreshes it)"
fi
[ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute"
[ "$want" = 0 ] && [ "$tunnel" = up ] && echo "the cron check takes it down within a minute"
true
;; ;;
# show the real handshake error: no handshake-timeout, debug log, # show the real handshake error: no handshake-timeout, debug log,
# one request through the mixed port so the dial error gets logged # one request through the mixed port so the dial error gets logged

View File

@ -484,7 +484,8 @@ cmd_render() {
# OpenVPN routes for the rule-provider <OVPN_PROVIDER>-routes (templates/rule-providers): # OpenVPN routes for the rule-provider <OVPN_PROVIDER>-routes (templates/rule-providers):
# <name>.all - the list (bmstu-otp.sh on puts it back), <name>.yaml - what mihomo # <name>.all - the list (bmstu-otp.sh on puts it back), <name>.yaml - what mihomo
# reads: the list, or empty while the tunnel is off (bmstu.off) # reads: the list, or empty while the tunnel should be off (manual off, timer,
# schedule: bmstu-otp.sh want)
ovpn_routes_write() { ovpn_routes_write() {
( (
[ -f "$PROFILES_D/common.env" ] && load_env "$PROFILES_D/common.env" [ -f "$PROFILES_D/common.env" ] && load_env "$PROFILES_D/common.env"
@ -492,7 +493,13 @@ ovpn_routes_write() {
_r=$NIKKI_DIR/run/providers/$OVPN_PROVIDER-routes _r=$NIKKI_DIR/run/providers/$OVPN_PROVIDER-routes
mkdir -p "${_r%/*}" mkdir -p "${_r%/*}"
printf '%s\n' $OVPN_ROUTES > "$_r.all" printf '%s\n' $OVPN_ROUTES > "$_r.all"
if [ -f "$NIKKI_DIR/bmstu.off" ]; then _on=1
if command -v bmstu-otp.sh >/dev/null 2>&1; then
bmstu-otp.sh want 2>/dev/null || _on=0
elif [ -f "$NIKKI_DIR/bmstu.off" ]; then
_on=0
fi
if [ "$_on" = 0 ]; then
echo 'payload: []' echo 'payload: []'
else else
echo 'payload:' echo 'payload:'
@ -588,10 +595,11 @@ cmd_use() {
# OpenVPN of this profile: common.env, overridden by <name>.env # OpenVPN of this profile: common.env, overridden by <name>.env
_ov=$(cat "$PROFILES_D/common.env" "$PROFILES_D/$1.env" 2>/dev/null | sed -n 's/^OPENVPN=//p' | tail -n 1 | tr -d "'\"") _ov=$(cat "$PROFILES_D/common.env" "$PROFILES_D/$1.env" 2>/dev/null | sed -n 's/^OPENVPN=//p' | tail -n 1 | tr -d "'\"")
[ "$_ov" = 1 ] && command -v bmstu-otp.sh >/dev/null 2>&1 || return 0 [ "$_ov" = 1 ] && command -v bmstu-otp.sh >/dev/null 2>&1 || return 0
if [ -f "$NIKKI_DIR/bmstu.off" ]; then # off now (manual, schedule): up says so and does nothing
log "OpenVPN is off (bmstu-otp.sh on to start it)" bmstu-otp.sh want || {
bmstu-otp.sh up
return 0 return 0
fi }
# the init script wrote a fresh OTP and the kit core is already connecting: refresh # 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 # only if the tunnel does not answer; if it does not come up, cron
# (bmstu-otp.sh check) retries # (bmstu-otp.sh check) retries

View File

@ -1,5 +1,5 @@
diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go
index 3c7b1e6..88760d0 100644 index 3c7b1e6..4401994 100644
--- a/adapter/outbound/openvpn.go --- a/adapter/outbound/openvpn.go
+++ b/adapter/outbound/openvpn.go +++ b/adapter/outbound/openvpn.go
@@ -35,6 +35,14 @@ type OpenVPN struct { @@ -35,6 +35,14 @@ type OpenVPN struct {
@ -47,7 +47,7 @@ index 3c7b1e6..88760d0 100644
PingInterval: time.Duration(option.Ping) * time.Second, PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second, PingRestart: time.Duration(option.PingRestart) * time.Second,
TransitionWindow: transitionWindow, TransitionWindow: transitionWindow,
@@ -152,9 +168,100 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { @@ -152,9 +168,112 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
} }
outbound.dialer = option.NewDialer(outbound.DialOptions()) outbound.dialer = option.NewDialer(outbound.DialOptions())
outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background()) outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background())
@ -105,12 +105,18 @@ index 3c7b1e6..88760d0 100644
+ wg.Wait() + wg.Wait()
+} +}
+ +
+// openVPNRestartDelay is OpenVPN Connect's pause before a reconnect. +// openVPNRestartDelay is OpenVPN Connect's pause before a reconnect; it
+const openVPNRestartDelay = 2 * time.Second +// doubles after each failed connect up to openVPNRestartMax and starts over
+// once a tunnel comes up.
+const (
+ openVPNRestartDelay = 2 * time.Second
+ openVPNRestartMax = time.Minute
+)
+ +
+var errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones") +var errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones")
+ +
+func (o *OpenVPN) autoConnect() { +func (o *OpenVPN) autoConnect() {
+ delay := openVPNRestartDelay
+ for o.runCtx.Err() == nil { + for o.runCtx.Err() == nil {
+ _, _, err := o.run(o.runCtx) + _, _, err := o.run(o.runCtx)
+ if o.runCtx.Err() != nil { + if o.runCtx.Err() != nil {
@ -121,8 +127,9 @@ index 3c7b1e6..88760d0 100644
+ return + return
+ } + }
+ if err != nil { + if err != nil {
+ log.Warnln("[OpenVPN](%s) connect failed, retrying in %s: %v", o.name, openVPNRestartDelay, err) + log.Warnln("[OpenVPN](%s) connect failed, retrying in %s: %v", o.name, delay, err)
+ } else { + } else {
+ delay = openVPNRestartDelay
+ var down chan struct{} + var down chan struct{}
+ if o.runLock.Acquire(o.runCtx, 1) == nil { + if o.runLock.Acquire(o.runCtx, 1) == nil {
+ down = o.linkDown + down = o.linkDown
@ -138,17 +145,22 @@ index 3c7b1e6..88760d0 100644
+ } + }
+ } + }
+ select { + select {
+ case <-time.After(openVPNRestartDelay): + case <-time.After(delay):
+ case <-o.runCtx.Done(): + case <-o.runCtx.Done():
+ return + return
+ } + }
+ if err != nil {
+ if delay *= 2; delay > openVPNRestartMax {
+ delay = openVPNRestartMax
+ }
+ }
+ } + }
+} +}
+ +
func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) { func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
tunDevice, r, err := o.run(ctx) tunDevice, r, err := o.run(ctx)
if err != nil { if err != nil {
@@ -234,6 +341,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool { @@ -234,6 +353,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool {
} }
func (o *OpenVPN) Close() error { func (o *OpenVPN) Close() error {
@ -171,7 +183,7 @@ index 3c7b1e6..88760d0 100644
if o.runCancel != nil { if o.runCancel != nil {
o.runCancel() o.runCancel()
} }
@@ -278,6 +401,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) { @@ -278,6 +413,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) {
} }
return o.tunDevice, o.resolver, nil return o.tunDevice, o.resolver, nil
} }
@ -181,7 +193,7 @@ index 3c7b1e6..88760d0 100644
if o.runCtx.Err() != nil { if o.runCtx.Err() != nil {
return nil, nil, o.runCtx.Err() return nil, nil, o.runCtx.Err()
} }
@@ -318,7 +444,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R @@ -318,7 +456,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err) return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err)
} }
@ -200,11 +212,12 @@ index 3c7b1e6..88760d0 100644
if err != nil { if err != nil {
_ = packetIO.Close() _ = packetIO.Close()
return nil, nil, err return nil, nil, err
@@ -326,6 +462,13 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R @@ -326,6 +474,14 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
push, err := client.Handshake(handshakeCtx) push, err := client.Handshake(handshakeCtx)
if err != nil { if err != nil {
_ = client.Close() _ = client.Close()
+ if o.option.AutoConnect && ovpn.IsAuthFailed(err) { + // AUTH_FAILED,TEMP is a retry-later, not a rejection
+ if o.option.AutoConnect && ovpn.IsAuthFailed(err) && !ovpn.IsAuthFailedTemp(err) {
+ // Connect drops a rejected token and, with a static challenge, + // Connect drops a rejected token and, with a static challenge,
+ // waits for the user's next OTP: here a new proxy from the provider. + // waits for the user's next OTP: here a new proxy from the provider.
+ o.tokenUser, o.tokenPass = "", "" + o.tokenUser, o.tokenPass = "", ""
@ -214,7 +227,7 @@ index 3c7b1e6..88760d0 100644
return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", 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) 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 @@ -347,6 +503,7 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R
o.client = client o.client = client
o.tunDevice = tunDevice o.tunDevice = tunDevice
o.running = true o.running = true
@ -222,7 +235,7 @@ index 3c7b1e6..88760d0 100644
if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil { if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil {
nss := append([]dns.NameServer(nil), o.dns...) nss := append([]dns.NameServer(nil), o.dns...)
for i := range nss { for i := range nss {
@@ -393,6 +537,7 @@ func (o *OpenVPN) startPacketLoops() { @@ -393,6 +550,7 @@ func (o *OpenVPN) startPacketLoops() {
runCtx, runCancel := context.WithCancel(o.runCtx) runCtx, runCancel := context.WithCancel(o.runCtx)
client := o.client client := o.client
tunDevice := o.tunDevice tunDevice := o.tunDevice
@ -230,7 +243,7 @@ index 3c7b1e6..88760d0 100644
var stopOnce sync.Once var stopOnce sync.Once
stop := func() { stop := func() {
stopOnce.Do(func() { stopOnce.Do(func() {
@@ -405,7 +550,11 @@ func (o *OpenVPN) startPacketLoops() { @@ -405,7 +563,11 @@ func (o *OpenVPN) startPacketLoops() {
o.tunDevice = nil o.tunDevice = nil
o.running = false o.running = false
} }
@ -290,7 +303,7 @@ index 796face..a7df5cd 100644
tproxy.CleanupTProxyIPTables() tproxy.CleanupTProxyIPTables()
resolver.StoreFakePoolState() resolver.StoreFakePoolState()
diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go
index 053b0bf..868b445 100644 index 053b0bf..c7e7848 100644
--- a/transport/openvpn/client.go --- a/transport/openvpn/client.go
+++ b/transport/openvpn/client.go +++ b/transport/openvpn/client.go
@@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { @@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
@ -353,7 +366,7 @@ index 053b0bf..868b445 100644
c.installDataChannel(newData) c.installDataChannel(newData)
c.captureAuthToken(push) c.captureAuthToken(push)
c.markSend() c.markSend()
@@ -387,6 +387,123 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { @@ -387,6 +387,130 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) {
return push, nil return push, nil
} }
@ -473,11 +486,18 @@ index 053b0bf..868b445 100644
+func IsAuthFailed(err error) bool { +func IsAuthFailed(err error) bool {
+ return errors.Is(err, errAuthFailed) + return errors.Is(err, errAuthFailed)
+} +}
+
+// IsAuthFailedTemp reports whether err is a temporary AUTH_FAILED
+// ("AUTH_FAILED,TEMP[...]", IV_PROTO_AUTH_FAIL_TEMP): the client should retry
+// later with the same credentials instead of treating them as rejected.
+func IsAuthFailedTemp(err error) bool {
+ return IsAuthFailed(err) && strings.Contains(err.Error(), "AUTH_FAILED,TEMP")
+}
+ +
// consumeRekeyPush updates the cached push state after an authenticated // consumeRekeyPush updates the cached push state after an authenticated
// rekey: it inherits the previous peer-id and applies any fresh auth-token // 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 // 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 { @@ -1652,6 +1776,10 @@ func mergePushReply(prev, next *PushReply) *PushReply {
if !next.BlockIPv6 { if !next.BlockIPv6 {
next.BlockIPv6 = prev.BlockIPv6 next.BlockIPv6 = prev.BlockIPv6
} }
@ -488,7 +508,7 @@ index 053b0bf..868b445 100644
if next.AuthTokenPass == "" { if next.AuthTokenPass == "" {
next.AuthTokenPass = prev.AuthTokenPass next.AuthTokenPass = prev.AuthTokenPass
} }
@@ -1768,6 +1889,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) { @@ -1768,6 +1896,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) {
// servers rekey the control channel at regular intervals (default 1h). // servers rekey the control channel at regular intervals (default 1h).
Renegotiation: tls.RenegotiateFreelyAsClient, Renegotiation: tls.RenegotiateFreelyAsClient,
} }
@ -502,17 +522,20 @@ index 053b0bf..868b445 100644
keyPEM := bytes.TrimSpace(c.config.Key) keyPEM := bytes.TrimSpace(c.config.Key)
if len(certPEM) > 0 && len(keyPEM) > 0 { if len(certPEM) > 0 && len(keyPEM) > 0 {
diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go
index 51690c3..13b115e 100644 index 51690c3..0c5e373 100644
--- a/transport/openvpn/config.go --- a/transport/openvpn/config.go
+++ b/transport/openvpn/config.go +++ b/transport/openvpn/config.go
@@ -55,6 +55,13 @@ type ClientConfig struct { @@ -55,6 +55,16 @@ type ClientConfig struct {
Password string Password string
PeerInfo map[string]string PeerInfo map[string]string
+ // PeerInfoRaw replaces the generated peer-info verbatim (lines in the + // PeerInfoRaw replaces the generated peer-info verbatim (lines in the
+ // given order, e.g. copied from another client's log). Its IV_PROTO must + // given order, e.g. copied from another client's log). The server turns on
+ // announce only features this client implements: DATA_V2, REQUEST_PUSH, + // what its IV_PROTO announces. Implemented: DATA_V2, REQUEST_PUSH,
+ // TLS_KEY_EXPORT, AUTH_PENDING_KW, DYN_TLS_CRYPT, DATA_EPOCH. + // TLS_KEY_EXPORT, DYN_TLS_CRYPT, DATA_EPOCH, CC_EXIT_NOTIFY,
+ // AUTH_FAIL_TEMP (retried, not a rejection) and DNS_OPTION_V2 (the
+ // "dns server" addresses). Tolerated, as they only add messages this
+ // client ignores: AUTH_PENDING_KW, PUSH_UPDATE. Announce nothing else.
+ PeerInfoRaw string + PeerInfoRaw string
+ // OptionsString replaces the generated key-method 2 options string. + // OptionsString replaces the generated key-method 2 options string.
+ OptionsString string + OptionsString string
@ -1392,7 +1415,7 @@ index 8f2c104..b451163 100644
if s == "" { if s == "" {
return binary.BigEndian.AppendUint16(out, 0) return binary.BigEndian.AppendUint16(out, 0)
diff --git a/transport/openvpn/push.go b/transport/openvpn/push.go diff --git a/transport/openvpn/push.go b/transport/openvpn/push.go
index df84904..ae17dcb 100644 index df84904..419695a 100644
--- a/transport/openvpn/push.go --- a/transport/openvpn/push.go
+++ b/transport/openvpn/push.go +++ b/transport/openvpn/push.go
@@ -29,6 +29,14 @@ type PushReply struct { @@ -29,6 +29,14 @@ type PushReply struct {
@ -1410,7 +1433,26 @@ index df84904..ae17dcb 100644
// AuthToken is the most recently pushed auth-token / auth-token-user // AuthToken is the most recently pushed auth-token / auth-token-user
// pair. Empty when the server does not rotate credentials. // pair. Empty when the server does not rotate credentials.
AuthTokenUser string AuthTokenUser string
@@ -144,6 +152,23 @@ func parsePushReplyInner(message string) (*PushReply, error) { @@ -119,6 +127,18 @@ func parsePushReplyInner(message string) (*PushReply, error) {
reply.DNS = append(reply.DNS, addr)
}
}
+ case "dns":
+ // "dns server <priority> address <addr>[:port] ..." (--dns, pushed
+ // instead of dhcp-option DNS to peers announcing DNS_OPTION_V2)
+ if len(fields) >= 5 && fields[1] == "server" && fields[3] == "address" {
+ for _, a := range fields[4:] {
+ if addr, err := netip.ParseAddr(a); err == nil {
+ reply.DNS = append(reply.DNS, addr)
+ } else if ap, err := netip.ParseAddrPort(a); err == nil {
+ reply.DNS = append(reply.DNS, ap.Addr())
+ }
+ }
+ }
case "peer-id":
if len(fields) >= 2 {
id, err := strconv.ParseUint(fields[1], 10, 24)
@@ -144,6 +164,23 @@ func parsePushReplyInner(message string) (*PushReply, error) {
if len(fields) >= 2 { if len(fields) >= 2 {
reply.Cipher = strings.TrimSpace(fields[1]) reply.Cipher = strings.TrimSpace(fields[1])
} }
@ -1434,3 +1476,41 @@ index df84904..ae17dcb 100644
case "auth-token": case "auth-token":
if len(fields) >= 2 { if len(fields) >= 2 {
reply.AuthTokenPass = strings.TrimSpace(fields[1]) reply.AuthTokenPass = strings.TrimSpace(fields[1])
diff --git a/transport/openvpn/push_mimic_test.go b/transport/openvpn/push_mimic_test.go
new file mode 100644
index 0000000..7149f3c
--- /dev/null
+++ b/transport/openvpn/push_mimic_test.go
@@ -0,0 +1,32 @@
+package openvpn
+
+import (
+ "fmt"
+ "net/netip"
+ "testing"
+)
+
+func TestParsePushDNSServerOption(t *testing.T) {
+ reply, err := parsePushReplyInner("PUSH_REPLY,dns server 0 address 10.8.0.1 [fd00::1]:53,dns search-domains bmstu.ru,protocol-flags cc-exit tls-ekm dyn-tls-crypt aead-epoch")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []netip.Addr{netip.MustParseAddr("10.8.0.1"), netip.MustParseAddr("fd00::1")}
+ if fmt.Sprint(reply.DNS) != fmt.Sprint(want) {
+ t.Fatalf("DNS = %v, want %v", reply.DNS, want)
+ }
+ if !reply.CCExit || !reply.TLSEKM || !reply.DynTLSCrypt || !reply.AEADEpoch {
+ t.Fatalf("protocol-flags not parsed: %+v", reply)
+ }
+}
+
+func TestAuthFailedTemp(t *testing.T) {
+ temp := authFailedError([]byte("AUTH_FAILED,TEMP[backoff 30]:busy\x00"))
+ if !IsAuthFailed(temp) || !IsAuthFailedTemp(temp) {
+ t.Fatalf("temp = %v", temp)
+ }
+ hard := authFailedError([]byte("AUTH_FAILED\x00"))
+ if !IsAuthFailed(hard) || IsAuthFailedTemp(hard) {
+ t.Fatalf("hard = %v", hard)
+ }
+}