mihomo-kit/router/bmstu-otp.sh
2026-10-09 17:13:30 +03:00

286 lines
10 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, and the tunnel is started lazily on first use. 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 immediately warms the tunnel up
# (delay test) while the code is still valid. After that the server's
# auth-token (if pushed) keeps rekeys alive without an OTP.
#
# 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 check warm-up test; refresh only if the tunnel is dead (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 server drops the old session after its ping-restart, up to ~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}"
# otp-last - <password><otp> (what the BMSTU server accepts)
# otp-first - <otp><password>
# scrv1 - what openvpn sends for "static-challenge ... 1": SCRV1:b64(pass):b64(otp)
: "${PASS_FORMAT:=otp-last}"
: "${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"; }
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"
echo " ping: 10"
echo " ping-restart: 60"
[ "$HANDSHAKE_TIMEOUT" -gt 0 ] && echo " handshake-timeout: $HANDSHAKE_TIMEOUT"
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"
}
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 ;;
check)
[ -f "$OFF_FLAG" ] && exit 0
alive || { log "tunnel is down, 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)"
log "OpenVPN off: tunnel closed, the server frees the session within its ping-restart (~5 min)"
;;
on)
rm -f "$OFF_FLAG"
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