#!/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). # # No traffic of its own through the tunnel: OpenVPN Connect sends none, and a # periodic URL test shows up in the logs of the site it opens (a HEAD from a Go # client every minute). With the kit core the watchdog reads the tunnel state # from the mihomo API instead; only "probe" (by hand) opens CHECK_URL. Other # cores report no state: there the cron check probes, rarely and at random moments. # # 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) and # refresh a dead tunnel (cron, once a minute; no traffic with the kit core) # 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 [DAYS] | days DAYS: work-hours schedule # (MSK; DAYS 12345 | weekdays | weekend | all), 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, the tunnel state (no traffic) # bmstu-otp.sh probe open CHECK_URL through the tunnel (a request the site can log) # 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_DAYS: weekdays the window opens on, digits 1 (Mon) .. 7 (Sun); a window # past midnight belongs to the day it starts on. : "${OVPN_SCHED:=0}" "${OVPN_SCHED_START:=09:00}" "${OVPN_SCHED_END:=17:00}" "${OVPN_SCHED_JITTER:=10}" : "${OVPN_SCHED_DAYS:=1234567}" # what "probe" opens through the tunnel: OVPN_CHECK_URL of the profiles (LuCI) : "${CHECK_URL:=$(sed -n 's/^OVPN_CHECK_URL=//p' /etc/nikki/profiles.d/common.env 2>/dev/null | tail -n 1 | tr -d "'\"")}" : "${CHECK_URL:=https://eu.bmstu.ru}" # ms, must exceed HANDSHAKE_TIMEOUT (max 32767) : "${CHECK_TIMEOUT:=25000}" # cores without the tunnel state: the cron check probes at most every PROBE_EVERY # seconds, after a random pause of up to PROBE_SPREAD seconds : "${PROBE_EVERY:=600}" "${PROBE_SPREAD:=45}" # kit core: a tunnel that has not come up for this long gets a fresh OTP (it # reconnects by itself meanwhile) : "${DOWN_GRACE:=300}" # 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 - : "${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 ... block from the .ovpn, YAML-indented, no comments ovpn_block() { awk -v tag="$1" ' $0 ~ "^<" tag ">" { on = 1; next } $0 ~ "^" { 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 } # HTTP check through the tunnel. The site sees it (HEAD from a Go client), so it # runs only by hand and for cores that report no tunnel state. probe() { api GET "/proxies/$GROUP_NAME/delay" -G \ --data-urlencode "url=$CHECK_URL" --data-urlencode "timeout=$CHECK_TIMEOUT" 2>/dev/null } # tunnel state from the kit core, no traffic: _cs_since (unix, 0 = down), # _cs_failed (true once the server rejected the credentials), _cs_err (last # connect error). Non-zero when the core reports none (stock / official core, # OVPN_MIMIC=mihomo without auto-connect, no such proxy, API down). core_state() { _j=$(api GET "/providers/proxies/$PROVIDER_NAME/$PROXY_NAME" 2>/dev/null) || return 1 [ "$(jsonfilter -s "$_j" -e '@.openvpn.auto_connect' 2>/dev/null)" = true ] || return 1 _cs_since=$(jsonfilter -s "$_j" -e '@.openvpn.connected_since' 2>/dev/null) _cs_failed=$(jsonfilter -s "$_j" -e '@.openvpn.auth_failed' 2>/dev/null) _cs_err=$(jsonfilter -s "$_j" -e '@.openvpn.last_error' 2>/dev/null) case "$_cs_since" in '' | *[!0-9]*) _cs_since=0 ;; esac return 0 } # wait_up : 0 once the kit core reports the tunnel up, 1 when it is still down # after seconds or the credentials were rejected, 2 when the core reports no state wait_up() { _i=0 while :; do core_state || return 2 [ "$_cs_since" -gt 0 ] && return 0 [ "$_cs_failed" = true ] && return 1 [ "$_i" -ge "$1" ] && return 1 sleep 1 _i=$((_i + 1)) done } # is the tunnel up: the core's state (allowing a handshake in progress to # finish), or a probe for cores without it tunnel_ok() { wait_up "$((HANDSHAKE_TIMEOUT + 5))" case $? in 0) return 0 ;; 1) return 1 ;; esac probe >/dev/null } # 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 -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)" rm -f "$DOWN_SINCE" # the handshake has to happen now, while the OTP is valid: the kit core # starts it by itself, other cores dial on the first request (the probe) _cs_err= if tunnel_ok; then log "tunnel is up" else log "tunnel did not come up after refresh (${_cs_err:-check nikki log})" return 1 fi } # kit core, steady state (cron): it reconnects by itself with the session # token. A fresh OTP is needed once the server rejected the token, or when the # tunnel has stayed down for DOWN_GRACE seconds. DOWN_SINCE=${DOWN_SINCE:-/tmp/bmstu-otp.down} watch_core() { if [ "$_cs_since" -gt 0 ]; then rm -f "$DOWN_SINCE" return 0 fi if [ "$_cs_failed" = true ]; then log "the server rejected the session (${_cs_err:-AUTH_FAILED}), new OTP" refresh return fi _now=$(date +%s) _d=$(cat "$DOWN_SINCE" 2>/dev/null) case "$_d" in '' | *[!0-9]*) _d=$_now && echo "$_d" > "$DOWN_SINCE" ;; esac [ $((_now - _d)) -ge "$DOWN_GRACE" ] || return 0 log "tunnel down for $((_now - _d)) s (${_cs_err:-no error}), new OTP" refresh } # other cores (no tunnel state): probe CHECK_URL, but only every PROBE_EVERY # seconds and not on the minute mark, so it does not look like a clock PROBE_LAST=${PROBE_LAST:-/tmp/bmstu-otp.probe} watch_probe() { _now=$(date +%s) _last=$(cat "$PROBE_LAST" 2>/dev/null) case "$_last" in '' | *[!0-9]*) _last=0 ;; esac [ $((_now - _last)) -ge "$PROBE_EVERY" ] || return 0 echo "$_now" > "$PROBE_LAST" sleep $(($(od -An -N2 -tu2 /dev/urandom | tr -d ' ') % (PROBE_SPREAD + 1))) probe >/dev/null && return 0 # a single lost probe on a long chain (whitelist: RU node + tunnel) is not a # dead tunnel; refreshing then would break a working one log "probe failed, checking again" sleep 10 probe >/dev/null && return 0 log "tunnel is down (2 failed probes), refreshing" refresh } # --- 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"))) } # weekday of YYYY-MM-DD, 1 (Mon) .. 7 (Sun), plain arithmetic (Sakamoto) dow_of() { _y=${1%%-*} _mo=${1#*-} _dd=${1##*-} _mo=${_mo%-*} _mo=${_mo#0} _dd=${_dd#0} [ "$_mo" -lt 3 ] && _y=$((_y - 1)) set -- 0 3 2 5 0 3 5 1 4 6 2 4 shift $((_mo - 1)) _w=$(((_y + _y / 4 - _y / 100 + _y / 400 + $1 + _dd) % 7)) echo $((_w == 0 ? 7 : _w)) } # day_on <1..7>: the window opens on that weekday (OVPN_SCHED_DAYS) day_on() { case "$OVPN_SCHED_DAYS" in *"$1"*) return 0 ;; esac; return 1; } # days_norm <1234567 | weekdays | weekend | all | digits>: sorted digits 1..7, or nothing days_norm() { case "$1" in all | '') set -- 1234567 ;; weekdays) set -- 12345 ;; weekend) set -- 67 ;; *[!1-7]*) return 1 ;; esac _o="" for _x in 1 2 3 4 5 6 7; do case "$1" in *"$_x"*) _o=$_o$_x ;; esac done echo "$_o" } # 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, its # part after midnight belongs to the previous day (OVPN_SCHED_DAYS). # 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 _dw=$(dow_of "$_day") if [ "$_s" -le "$_e" ]; then day_on "$_dw" && [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] elif [ "$_now" -ge "$_s" ]; then day_on "$_dw" elif [ "$_now" -lt "$_e" ]; then day_on $((_dw == 1 ? 7 : _dw - 1)) else return 1 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 change after now -> _next (epoch) _next_to (on|off). Walks the # candidate moments (midnight and the jittered edges of each day, up to 8 days # ahead: weekdays may be skipped) and asks in_window, so both always agree. 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 _cur=0 in_window "$1" "$_m" && _cur=1 _k=0 while [ "$_k" -le 8 ]; do _d=$1 [ "$_k" -gt 0 ] && _d=$(date -d "@$((_mid + _k * 86400 + 3600))" +%F) sched_edges "$_d" if [ "$_s" -le "$_e" ]; then _cs="0 $_s $_e"; else _cs="0 $_e $_s"; fi for _c in $_cs; do [ "$_c" -ge 0 ] && [ "$_c" -le 1439 ] || continue [ "$_k" -eq 0 ] && [ "$_c" -le "$_m" ] && continue _on=0 in_window "$_d" "$_c" && _on=1 if [ "$_on" != "$_cur" ]; then _next=$((_mid + _k * 86400 + _c * 60)) _next_to=off [ "$_on" = 1 ] && _next_to=on return 0 fi done _k=$((_k + 1)) done return 1 } # 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) # link closed | up | connecting | rejected | unknown: the kit core's tunnel # state, no traffic (unknown: the core reports none) # up_since when the tunnel came up (epoch, 0 = not up), up_hm, up_day # err the core's last connect error, single-quoted # 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 sched_days 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" _link=unknown _cs_since=0 if tunnel_is_down; then echo "tunnel=down" _link=closed else echo "tunnel=up" if core_state; then if [ "$_cs_since" -gt 0 ]; then _link=up elif [ "$_cs_failed" = true ]; then _link=rejected else _link=connecting fi # quotes and shell specials dropped: the line is eval'ed [ -n "$_cs_err" ] && echo "err='$(printf '%s' "$_cs_err" | tr -d "'\"\`\\\\\$\n" | cut -c1-200)'" fi fi echo "link=$_link" echo "up_since=$_cs_since" if [ "$_cs_since" -gt 0 ]; then set -- $(when "$_cs_since") echo "up_hm=$1" echo "up_day=$2" fi 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 "sched_days=$OVPN_SCHED_DAYS" 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 if core_state; then watch_core else watch_probe fi elif tunnel_ok; 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 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 " 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 " ;; 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 [DAYS]" (and enable) | # "sched days DAYS"; DAYS: digits 1 (Mon) .. 7 (Sun), weekdays, weekend, all. # 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, days $OVPN_SCHED_DAYS, 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 ;; days) _dz=$(days_norm "${3:-}") && [ -n "$_dz" ] || die "usage: bmstu-otp.sh sched days 12345 | weekdays | weekend | all" sched_set OVPN_SCHED_DAYS "$_dz" ;; [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)" if [ -n "${4:-}" ]; then _dz=$(days_norm "$4") && [ -n "$_dz" ] || die "days: digits 1 (Mon) .. 7 (Sun), weekdays, weekend or all" sched_set OVPN_SCHED_DAYS "$_dz" fi 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 [DAYS] | days DAYS" ;; esac wait_api reconcile ;; state) state ;; probe) tunnel_is_down && die "the tunnel is closed" wait_api if r=$(probe); then echo "$CHECK_URL through the tunnel: $(jsonfilter -s "$r" -e '@.delay' 2>/dev/null || echo '?') ms" else echo "$CHECK_URL does not open through the tunnel" exit 1 fi ;; 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, days $sched_days, today $win (jitter +-$jitter min)" [ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day" fi case "$link" in closed) echo "tunnel closed" ;; up) echo "tunnel up since $up_hm $up_day" ;; connecting) echo "tunnel connecting${err:+ (last error: $err)}" ;; rejected) echo "the server rejected the session: the cron check gets a new OTP within a minute" ;; *) echo "tunnel state unknown: this core does not report it (bmstu-otp.sh probe opens $CHECK_URL)" ;; esac [ "$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