mihomo-kit/router/bmstu-otp.sh
2026-10-15 13:57:32 +03:00

704 lines
25 KiB
Bash
Executable File

#!/bin/sh
# OpenVPN (BMSTU) + TOTP for mihomo / nikki on OpenWrt.
#
# mihomo has no static-challenge support: the password in the proxy config is
# 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 bring the tunnel up if it should be up and does not answer
# bmstu-otp.sh write only regenerate the provider and routes (nikki init, before mihomo starts)
# bmstu-otp.sh check reconcile to the desired state (timer/manual/schedule); the
# two-probe test refreshes a dead tunnel (cron, once a minute)
# 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 off close the tunnel and keep it closed (sticky, wins over the schedule,
# cancels a timer; BMSTU traffic goes without it); frees the single
# server session (the kit core sends EXIT; other cores leave it until
# ping-restart, ~5 min)
# 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
set -u
ENV_FILE="${ENV_FILE:-/etc/nikki/bmstu.env}"
[ -f "$ENV_FILE" ] && . "$ENV_FILE"
: "${OVPN_FILE:=/etc/nikki/bmstu.ovpn}"
: "${PROVIDER_FILE:=/etc/nikki/run/providers/bmstu.yaml}"
: "${PROVIDER_NAME:=bmstu}"
: "${PROXY_NAME:=bmstu-ovpn}"
: "${GROUP_NAME:=BMSTU}"
# API address/secret: from nikki's mixin settings unless set in the env file
uci_get() { uci -q get "$1" 2>/dev/null; }
# api_listen is host:port; a wildcard/empty host means loopback works
api_from_uci() {
l=$(uci_get nikki.mixin.api_listen)
port=${l##*:} host=${l%:*}
case "$port" in '' | *[!0-9]*) port=9090 ;; esac
case "$host" in '' | 0.0.0.0 | '[::]' | '::' | '*' | "$l") host=127.0.0.1 ;; esac
echo "http://$host:$port"
}
: "${API:=$(api_from_uci)}"
: "${API_SECRET:=$(uci_get nikki.mixin.api_secret)}"
# while this file exists the tunnel stays off (bmstu-otp.sh off/on); it is the
# sticky manual off and wins over the schedule
: "${OFF_FLAG:=/etc/nikki/bmstu.off}"
# timer (bmstu-otp.sh for N): holds an epoch; the tunnel stays up until then,
# overriding the schedule, then this file is removed and the schedule resumes
: "${UNTIL_FLAG:=/etc/nikki/bmstu.until}"
# schedule: with OVPN_SCHED=1 the tunnel is up only inside [START,END] local time
# (the router is MSK). A deterministic per-day jitter of up to OVPN_SCHED_JITTER
# minutes is added to each edge so the on/off moments are not identical every day.
: "${OVPN_SCHED:=0}" "${OVPN_SCHED_START:=09:00}" "${OVPN_SCHED_END:=17:00}" "${OVPN_SCHED_JITTER:=10}"
: "${CHECK_URL:=https://www.bmstu.ru}"
# ms, must exceed HANDSHAKE_TIMEOUT (max 32767)
: "${CHECK_TIMEOUT:=25000}"
# scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU
# profile): SCRV1:b64(pass):b64(otp)
# otp-last - <password><otp> (the server accepts it too)
# otp-first - <otp><password>
: "${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)
: "${TOTP_MIN_LEFT:=8}"
# 0 = omit (handshake errors then show up in "dial ... error:" log lines)
: "${HANDSHAKE_TIMEOUT:=20}"
# nikki mixed port and its login, used by "debug"
: "${MIXED_PORT:=$(uci_get nikki.mixin.mixed_port || echo 7890)}"
: "${MIXED_AUTH:=$(u=$(uci_get 'nikki.@authentication[0].username') && echo "$u:$(uci_get 'nikki.@authentication[0].password')")}"
log() { logger -t bmstu-otp "$*" 2>/dev/null; echo "$*" >&2; }
die() { log "error: $*"; exit 1; }
# --- TOTP (RFC 6238, HMAC-SHA1) --------------------------------------------
base32_to_hex() {
echo "$1" | tr -d ' =-' | tr 'a-z' 'A-Z' | awk '
BEGIN { a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" }
{
bits = ""
for (i = 1; i <= length($0); i++) {
v = index(a, substr($0, i, 1)) - 1
if (v < 0) { print "bad base32" > "/dev/stderr"; exit 1 }
for (b = 16; b >= 1; b /= 2) { bits = bits (v >= b ? "1" : "0"); if (v >= b) v -= b }
}
out = ""
for (i = 1; i + 7 <= length(bits); i += 8) {
n = 0
for (j = 0; j < 8; j++) n = n * 2 + substr(bits, i + j, 1)
out = out sprintf("%02x", n)
}
print out
}'
}
totp() {
now=$(date +%s)
if command -v oathtool >/dev/null 2>&1; then
oathtool --totp -b -d "$TOTP_DIGITS" -s "${TOTP_PERIOD}s" "$TOTP_SECRET"
return
fi
command -v openssl >/dev/null 2>&1 || die "need oathtool or openssl (opkg install oath-toolkit | openssl-util)"
key=$(base32_to_hex "$TOTP_SECRET") || die "TOTP_SECRET is not valid base32"
counter=$((now / TOTP_PERIOD))
# 8-byte big-endian counter as octal escapes (busybox printf has no \x)
esc="" i=7
while [ $i -ge 0 ]; do
esc="$esc$(printf '\\%03o' $(( (counter >> (i * 8)) & 255 )))"
i=$((i - 1))
done
mac=$(printf "$esc" | openssl dgst -sha1 -mac HMAC -macopt "hexkey:$key" | awk '{print $NF}')
off=$(( 0x$(echo "$mac" | cut -c40) * 2 + 1 ))
word=$(echo "$mac" | cut -c"$off-$((off + 7))")
mod=1 i=0
while [ $i -lt "$TOTP_DIGITS" ]; do mod=$((mod * 10)); i=$((i + 1)); done
printf "%0${TOTP_DIGITS}d\n" $(( (0x$word & 0x7fffffff) % mod ))
}
# wait for a fresh window if the current code is about to expire
fresh_totp() {
left=$((TOTP_PERIOD - $(date +%s) % TOTP_PERIOD))
[ "$left" -lt "$TOTP_MIN_LEFT" ] && sleep "$left"
totp
}
b64() { printf '%s' "$1" | openssl base64 -A 2>/dev/null || printf '%s' "$1" | base64 | tr -d '\n'; }
make_password() {
otp=$1
case "$PASS_FORMAT" in
scrv1) echo "SCRV1:$(b64 "$VPN_PASSWORD"):$(b64 "$otp")" ;;
otp-first) echo "$otp$VPN_PASSWORD" ;;
otp-last) echo "$VPN_PASSWORD$otp" ;;
*) die "unknown PASS_FORMAT=$PASS_FORMAT" ;;
esac
}
# --- provider generation ----------------------------------------------------
# print inline <tag>...</tag> block from the .ovpn, YAML-indented, no comments
ovpn_block() {
awk -v tag="$1" '
$0 ~ "^<" tag ">" { on = 1; next }
$0 ~ "^</" tag ">" { on = 0; next }
on && $0 !~ /^#/ && NF { print " " $0 }
' "$OVPN_FILE"
}
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() {
[ -f "$OVPN_FILE" ] || die "no $OVPN_FILE"
[ -n "${VPN_USERNAME:-}" ] || die "VPN_USERNAME is empty"
[ -n "${VPN_PASSWORD:-}" ] || die "VPN_PASSWORD is empty"
[ -n "${TOTP_SECRET:-}" ] || die "TOTP_SECRET is empty"
# first "remote host port proto" line
set -- $(ovpn_opt remote)
host=$1 port=${2:-1194} proto=${3:-udp}
case "$proto" in tcp*) proto=tcp ;; *) proto=udp ;; esac
fallback=$(ovpn_opt data-ciphers-fallback)
pass=$(make_password "$(fresh_totp)") || exit 1
mkdir -p "$(dirname "$PROVIDER_FILE")"
# 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 "proxies:"
echo " - name: $PROXY_NAME"
echo " type: openvpn"
echo " server: $host"
echo " port: $port"
echo " proto: $proto"
echo " udp: true"
echo " username: $(yaml_str "$VPN_USERNAME")"
echo " password: $(yaml_str "$pass")"
# the server pushes AES-256-GCM
echo " data-ciphers: [AES-256-GCM, AES-128-GCM]"
[ -n "$fallback" ] && echo " data-ciphers-fallback: $fallback"
# 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"
done
kd=$(ovpn_opt key-direction)
[ -n "$kd" ] && echo " key-direction: \"$kd\""
true
} > "$tmp" && chmod 600 "$tmp" && mv "$tmp" "$PROVIDER_FILE"
}
# --- mihomo API -------------------------------------------------------------
api() {
method=$1 path=$2
shift 2
if [ -n "$API_SECRET" ]; then
curl -fsS -m 30 -X "$method" -H "Authorization: Bearer $API_SECRET" "$@" "$API$path"
else
curl -fsS -m 30 -X "$method" "$@" "$API$path"
fi
}
# right after "nikki restart" the API is not up yet
wait_api() {
i=0
until api GET /version >/dev/null 2>&1; do
i=$((i + 1))
[ "$i" -ge "${API_WAIT:-30}" ] && die "mihomo API not reachable at $API (nikki running? check nikki.mixin.api_listen)"
sleep 1
done
}
alive() {
api GET "/proxies/$GROUP_NAME/delay" -G \
--data-urlencode "url=$CHECK_URL" --data-urlencode "timeout=$CHECK_TIMEOUT" >/dev/null 2>&1
}
# provider with a single direct proxy: the old tunnel gets closed with the
# outdated proxy, and BMSTU traffic goes without it (public resources still
# open; on street the provider's dialer-proxy sends it through OVPN-EXIT)
write_off_provider() {
mkdir -p "$(dirname "$PROVIDER_FILE")"
printf '# bmstu-otp.sh off\nproxies:\n - name: %s-off\n type: direct\n' "$PROVIDER_NAME" > "$PROVIDER_FILE"
}
# 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
ROUTES=${ROUTES:-$(dirname "$PROVIDER_FILE")/$PROVIDER_NAME-routes}
routes_body() {
if [ "$1" = off ]; then
echo 'payload: []'
elif [ -f "$ROUTES.all" ]; then
echo 'payload:'
while read -r r; do [ -n "$r" ] && echo " - '$r'"; done < "$ROUTES.all"
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 ||
log "warning: routes reload failed (API $API), applies on the next nikki restart"
}
refresh() {
write_provider
wait_api
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
# handshake right now, while the OTP is valid
if alive; then
log "tunnel is up"
else
log "tunnel did not come up after refresh (check nikki log)"
return 1
fi
}
# --- schedule / timer -------------------------------------------------------
# "HH:MM" -> minutes since midnight on stdout; non-zero on a malformed value
hhmm_to_min() {
case "$1" in
[0-9][0-9]:[0-9][0-9]) : ;;
*) return 1 ;;
esac
_h=${1%:*} _m=${1#*:}
# strip one leading zero so 08/09 are not read as octal, without the
# bash-only 10# radix (busybox ash lacks it)
_h=${_h#0} _m=${_m#0}
_h=${_h:-0} _m=${_m:-0}
[ "$_h" -le 23 ] && [ "$_m" -le 59 ] || return 1
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),
# so each edge shifts by a fixed amount for the whole day and differs day to day
jitter_min() {
[ "${OVPN_SCHED_JITTER:-0}" -gt 0 ] 2>/dev/null || { echo 0; return; }
_span=$((OVPN_SCHED_JITTER * 2 + 1))
_hex=$(printf '%s' "$1" | md5sum 2>/dev/null | cut -c1-6)
[ -n "$_hex" ] || { echo 0; return; }
echo $((0x$_hex % _span - OVPN_SCHED_JITTER))
}
# jittered window edges of a day (YYYY-MM-DD) in minutes since its midnight ->
# _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() {
_day=${1:-${SCHED_DAY:-$(date +%F)}}
_now=${2:-${NOW_MIN:-$(hhmm_to_min "$(date +%H:%M)")}}
sched_edges "$_day" || return 0
if [ "$_s" -le "$_e" ]; then
[ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ]
else
[ "$_now" -ge "$_s" ] || [ "$_now" -lt "$_e" ]
fi
}
# end of the running timer (epoch) on stdout; an expired or broken one is removed
timer_until() {
[ -f "$UNTIL_FLAG" ] || return 1
_u=$(cat "$UNTIL_FLAG" 2>/dev/null)
case "$_u" in
'' | *[!0-9]*) ;;
*) [ "$(date +%s)" -lt "$_u" ] && { echo "$_u"; return 0; } ;;
esac
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
}
# 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,
# so the cron and the init hook that source the file pick the change up
sched_set() {
eval "$1=\$2"
[ -f "$ENV_FILE" ] || { umask 077; : > "$ENV_FILE"; }
_tmp=$(mktemp "$ENV_FILE.XXXXXX") || die "mktemp failed"
grep -v "^$1=" "$ENV_FILE" > "$_tmp" 2>/dev/null
# values here are simple (0/1 or HH:MM); single-quote so the file stays sourceable
echo "$1='$2'" >> "$_tmp"
chmod 600 "$_tmp" && mv "$_tmp" "$ENV_FILE"
}
# the provider currently holds the direct "off" proxy (tunnel torn down)
tunnel_is_down() { grep -q "name: $PROVIDER_NAME-off" "$PROVIDER_FILE" 2>/dev/null; }
# tear the tunnel down without touching OFF_FLAG (used by off and by the
# schedule): the kit core sends the server EXIT when the provider is replaced
tunnel_down() {
write_off_provider
wait_api
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
routes_set off
}
# bring the desired state about, routes included. "repair" uses the two-probe
# test before a refresh of an already-up tunnel (steady-state cron); otherwise
# act at once.
reconcile() {
if want_up; then
routes_set on
if tunnel_is_down; then
log "bringing the tunnel up"
refresh
elif [ "${1:-}" = repair ]; then
alive && return 0
log "probe failed, checking again"
sleep 10
alive && return 0
log "tunnel is down (2 failed probes), refreshing"
refresh
elif alive; then
log "tunnel is up"
else
refresh
fi
elif tunnel_is_down; then
routes_set off
else
log "OpenVPN should be off now ($(base_state | cut -d' ' -f2)), taking the tunnel down"
tunnel_down
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
otp) totp ;;
# auth-user-pass file for testing with the real openvpn client
authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;;
refresh)
lock_wait
want_up || die "OpenVPN is off now ($(base_state | cut -d' ' -f2)): bmstu-otp.sh on, or for <min>"
routes_set on
refresh
;;
up)
lock_wait
want_up || { log "OpenVPN is off now ($(base_state | cut -d' ' -f2)), staying down"; exit 0; }
wait_api
reconcile
;;
write)
# init-script hook: before mihomo starts, a fresh-OTP provider (or the off
# one) and the matching routes, only where OpenVPN is set up
[ -f "$PROVIDER_FILE" ] || exit 0
if want_up; then
routes_set on file
write_provider
else
routes_set off file
write_off_provider
fi
;;
# 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
;;
off)
lock_wait
touch "$OFF_FLAG"
rm -f "$UNTIL_FLAG"
tunnel_down
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)
lock_wait
rm -f "$OFF_FLAG" "$UNTIL_FLAG"
wait_api
reconcile
;;
# bring the tunnel up for N minutes, over the manual off and the schedule;
# then whatever was in force before holds again (the cron applies it)
for)
case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for <minutes>" ;; esac
lock_wait
echo "$(($(date +%s) + $2 * 60))" > "$UNTIL_FLAG"
wait_api
reconcile
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).
# Persists to the env file so the cron and the init hook read the same thing.
sched)
case "${2:-}" in
'' | show)
if [ "${OVPN_SCHED:-0}" = 1 ]; then
echo "schedule on: $OVPN_SCHED_START-$OVPN_SCHED_END MSK, jitter +-$OVPN_SCHED_JITTER min"
else
echo "schedule off"
fi
exit 0
;;
esac
lock_wait
case "$2" in
off) sched_set OVPN_SCHED 0 ;;
on) sched_set OVPN_SCHED 1 ;;
[0-9][0-9]:[0-9][0-9])
_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_END "$3"
sched_set OVPN_SCHED 1
;;
*) die "usage: bmstu-otp.sh sched off | on | HH:MM HH:MM" ;;
esac
wait_api
reconcile
;;
state) state ;;
status)
eval "$(state)"
case "$mode" in
timer) echo "on by timer until $until_hm $until_day, then $after ($why)" ;;
manual) echo "off (manual, until bmstu-otp.sh on)" ;;
always) echo "on (no schedule)" ;;
schedule)
[ "$want" = 1 ] && echo "on by schedule" || echo "off by schedule"
;;
esac
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
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,
# one request through the mixed port so the dial error gets logged
debug)
HANDSHAKE_TIMEOUT=0 write_provider
api PATCH /configs -H 'Content-Type: application/json' -d '{"log-level":"debug"}' >/dev/null
api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
echo "password format: $PASS_FORMAT, length $(sed -n 's/^ password: "\(.*\)"$/\1/p' "$PROVIDER_FILE" | wc -c)"
curl -skS -m 25 -o /dev/null -w "request via mihomo: http %{http_code}\n" \
${MIXED_AUTH:+--proxy-user "$MIXED_AUTH"} \
-x "http://127.0.0.1:$MIXED_PORT" "${DEBUG_URL:-https://195.19.34.102/}"
# let LAN clients trigger a handshake and hit the 5s dial timeout
sleep 20
echo "--- log ---"
{ cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -iE "openvpn|bmstu" | tail -n 30
echo "--- handshake errors ---"
{ cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -E "OpenVPN" | tail -n 5
;;
*) echo "usage: $0 otp|authfile|refresh|check|on|off|status|debug" >&2; exit 2 ;;
esac