#!/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 warm-up test; refresh only if two probes fail (cron) # bmstu-otp.sh off close the tunnel and keep it closed (BMSTU traffic goes without it); # frees the single server session for another client (the kit core # sends EXIT; other cores leave it until the server's ping-restart, ~5 min) # bmstu-otp.sh on allow the tunnel again and bring it up # bmstu-otp.sh status on/off and whether the tunnel answers # bmstu-otp.sh debug show the real handshake error in the nikki log 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) : "${OFF_FLAG:=/etc/nikki/bmstu.off}" : "${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 } 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; } refresh ;; write) # only where OpenVPN is set up and on [ -f "$OFF_FLAG" ] || [ ! -f "$PROVIDER_FILE" ] && exit 0 write_provider ;; check) [ -f "$OFF_FLAG" ] && exit 0 # one run at a time: two slow probes can outlast the cron minute 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 alive && exit 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 alive && exit 0 log "tunnel is down (2 failed probes), refreshing" refresh ;; off) touch "$OFF_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" wait_api routes_set on refresh ;; status) if [ -f "$OFF_FLAG" ]; then echo "off" 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