#!/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 refresh unless the tunnel already answers # bmstu-otp.sh write only regenerate the provider (nikki init, before mihomo starts) # bmstu-otp.sh check reconcile to the desired state (schedule/timer/manual); the # 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 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 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 allow the tunnel again and bring it up # bmstu-otp.sh status on/off and whether the tunnel answers # bmstu-otp.sh debug show the real handshake error in the nikki log 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 - (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")" 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 -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_set() { if [ "$1" = off ]; then echo 'payload: []' > "$ROUTES.yaml" elif [ -f "$ROUTES.all" ]; then { echo 'payload:' while read -r r; do [ -n "$r" ] && echo " - '$r'"; done < "$ROUTES.all" } > "$ROUTES.yaml" else return 0 fi api PUT "/providers/rules/$PROVIDER_NAME-routes" >/dev/null || log "warning: routes reload failed (API $API), applies on the next nikki restart" } refresh() { [ -f "$OFF_FLAG" ] && die "OpenVPN is off (bmstu-otp.sh on)" 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#*:} _h=$((10#$_h)) _m=$((10#$_m)) [ "$_h" -le 23 ] && [ "$_m" -le 59 ] || return 1 echo $((_h * 60 + _m)) } # 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)) } # true when now is inside the (jittered) schedule window; handles a window that # wraps past midnight (END <= START). NOW_MIN/SCHED_DAY override the clock in tests. in_window() { _now=${NOW_MIN:-$((10#$(date +%H) * 60 + 10#$(date +%M)))} _day=${SCHED_DAY:-$(date +%F)} _s=$(hhmm_to_min "$OVPN_SCHED_START") || { log "bad OVPN_SCHED_START=$OVPN_SCHED_START"; 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 [ "$_now" -ge "$_s" ] && [ "$_now" -lt "$_e" ] else [ "$_now" -ge "$_s" ] || [ "$_now" -lt "$_e" ] fi } # desired state: should the tunnel be up now? (prints nothing, sets exit code) want_up() { [ -f "$OFF_FLAG" ] && return 1 if [ -f "$UNTIL_FLAG" ]; then _until=$(cat "$UNTIL_FLAG" 2>/dev/null) case "$_until" in '' | *[!0-9]*) rm -f "$UNTIL_FLAG" ;; esac if [ -n "$_until" ] && [ "$(date +%s)" -lt "$_until" ]; then return 0 fi rm -f "$UNTIL_FLAG" fi [ "${OVPN_SCHED:-0}" = 1 ] || return 0 in_window } # 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. repair=1 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 if tunnel_is_down; then log "bringing the tunnel up" routes_set on 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 else alive || refresh fi else if ! tunnel_is_down; then log "schedule: outside the window, taking the tunnel down" tunnel_down fi fi } 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) refresh ;; up) [ -f "$OFF_FLAG" ] && exit 0 wait_api alive && { log "tunnel is up"; exit 0; } want_up || { log "schedule: outside the window, staying down"; exit 0; } refresh ;; write) # init-script hook: write a fresh-OTP provider before mihomo starts, but # only where OpenVPN is set up and the tunnel should be up now [ -f "$OFF_FLAG" ] || [ ! -f "$PROVIDER_FILE" ] && exit 0 want_up || { write_off_provider; exit 0; } write_provider ;; check) [ -f "$OFF_FLAG" ] && exit 0 # one run at a time: two slow probes can outlast the cron minute lock=/tmp/bmstu-otp.lock if ! mkdir "$lock" 2>/dev/null; then kill -0 "$(cat "$lock/pid" 2>/dev/null)" 2>/dev/null && exit 0 rm -rf "$lock" mkdir "$lock" || exit 0 fi echo $$ > "$lock/pid" trap 'rm -rf "$lock"' EXIT reconcile repair ;; off) touch "$OFF_FLAG" rm -f "$UNTIL_FLAG" write_off_provider 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)" ;; on) rm -f "$OFF_FLAG" "$UNTIL_FLAG" wait_api reconcile ;; # bring the tunnel up for N minutes, then let the schedule resume (overrides # the schedule while it runs; the cron takes it down when the timer expires) for) case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh for " ;; esac rm -f "$OFF_FLAG" echo "$(( $(date +%s) + $2 * 60 ))" > "$UNTIL_FLAG" wait_api reconcile log "OpenVPN on for $2 min (until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || date '+%H:%M'))" ;; # 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 ;; off) sched_set OVPN_SCHED 0 ;; on) sched_set OVPN_SCHED 1 ;; [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" 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 ;; status) if [ -f "$OFF_FLAG" ]; then echo "off (manual)" elif [ -f "$UNTIL_FLAG" ] && [ "$(date +%s)" -lt "$(cat "$UNTIL_FLAG" 2>/dev/null || echo 0)" ]; then echo "on by timer until $(date -d "@$(cat "$UNTIL_FLAG")" '+%H:%M' 2>/dev/null || echo '?'), $(alive && echo 'tunnel up' || echo 'tunnel down')" elif ! want_up; then echo "off by schedule ($OVPN_SCHED_START-$OVPN_SCHED_END MSK)" elif alive; then echo "on, tunnel is up" else echo "on, tunnel is down (cron brings it up within a minute)" fi ;; # 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