Refactor reverse tunnels installer

This commit is contained in:
Andrei Smaliak 2026-03-15 07:37:07 +04:00
parent 500ee97a91
commit c1ae9da13b
1 changed files with 160 additions and 91 deletions

239
stage_reverse_tunnels/stage_reverse_tunnels_install.sh Executable file → Normal file
View File

@ -1,11 +1,11 @@
#!/usr/bin/env bash
# =============================================================
# IOMATEX Stage4 — Reverse SSH Tunnels (production)
# IOMATEX Stage4 Reverse SSH Tunnels (production)
# - 3 independent tunnels: Cockpit / Zigbee2MQTT / WebUI
# - services ENABLED but NOT started (start after reboot)
# - services are ENABLED but NOT started
# - autossh + systemd restart for resilience
# - ServerAlive keepalive for network/IP changes
# - prints one-line VPS command (user + key + fail2ban allow)
# - prints one-line VPS bootstrap command
# =============================================================
set -euo pipefail
@ -13,18 +13,6 @@ export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export DEBIAN_FRONTEND=noninteractive
LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log"
mkdir -p /var/log >/dev/null 2>&1 || true
touch "$LOG" >/dev/null 2>&1 || true
exec > >(tee -a "$LOG") 2>&1
log(){ echo "[$(date -u +'%F %T UTC')] $*"; }
need_root(){
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
echo "Run as root: sudo bash $0"
exit 1
fi
}
EDGE_USER="${EDGE_USER:-iomatex}"
@ -38,31 +26,72 @@ WEBUI_LOCAL_PORT="${WEBUI_LOCAL_PORT:-8099}"
PORT_BASE="${PORT_BASE:-20000}"
PORT_SLOTS="${PORT_SLOTS:-4000}"
ensure_autossh(){
if ! command -v autossh >/dev/null 2>&1; then
log "Installing autossh..."
apt-get update -y
apt-get install -y autossh
WRAPPER_DIR="/usr/local/sbin"
SYSTEMD_DIR="/etc/systemd/system"
mkdir -p /var/log >/dev/null 2>&1 || true
touch "$LOG" >/dev/null 2>&1 || true
exec > >(tee -a "$LOG") 2>&1
log() {
echo "[$(date -u +'%F %T UTC')] $*"
}
die() {
log "ERROR: $*"
exit 1
}
require_root() {
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
echo "Run as root: sudo bash $0" >&2
exit 1
fi
}
require_cmd() {
local cmd="$1"
command -v "$cmd" >/dev/null 2>&1 || die "Required command not found: $cmd"
}
preflight_checks() {
require_cmd id
require_cmd cksum
require_cmd awk
require_cmd getent
require_cmd runuser
require_cmd ssh-keygen
require_cmd systemctl
}
ensure_autossh_installed() {
if command -v autossh >/dev/null 2>&1; then
return 0
fi
require_cmd apt-get
log "Installing autossh..."
apt-get update -y
apt-get install -y autossh
}
compute_ports() {
local hn="$1"
local crc slot cockpit z2m webui
crc="$(cksum <<<"$hn" | awk '{print $1}')"
local hostname_value="$1"
local crc slot cockpit_port z2m_port webui_port
crc="$(cksum <<<"$hostname_value" | awk '{print $1}')"
slot="$(( crc % PORT_SLOTS ))"
cockpit="$(( PORT_BASE + slot*3 + 0 ))"
z2m="$(( PORT_BASE + slot*3 + 1 ))"
webui="$(( PORT_BASE + slot*3 + 2 ))"
echo "$cockpit $z2m $webui"
cockpit_port="$(( PORT_BASE + slot * 3 + 0 ))"
z2m_port="$(( PORT_BASE + slot * 3 + 1 ))"
webui_port="$(( PORT_BASE + slot * 3 + 2 ))"
echo "$cockpit_port $z2m_port $webui_port"
}
ensure_key() {
# IMPORTANT:
# - stdout: ONLY "edge_home|key|keypub"
# - any info/errors: stderr
local hn="$1"
# - informational messages: stderr only
local hostname_value="$1"
local edge_home ssh_dir key keypub
if ! id -u "$EDGE_USER" >/dev/null 2>&1; then
@ -77,14 +106,14 @@ ensure_key(){
fi
ssh_dir="${edge_home}/.ssh"
key="${ssh_dir}/iomatex-${hn}"
key="${ssh_dir}/iomatex-${hostname_value}"
keypub="${key}.pub"
install -d -m 700 -o "$EDGE_USER" -g "$EDGE_USER" "$ssh_dir"
if [[ ! -f "$key" || ! -f "$keypub" ]]; then
echo "Generating SSH key for ${EDGE_USER}..." >&2
runuser -u "$EDGE_USER" -- ssh-keygen -t ed25519 -N "" -f "$key" -C "$hn" >/dev/null
runuser -u "$EDGE_USER" -- ssh-keygen -t ed25519 -N "" -f "$key" -C "$hostname_value" >/dev/null
else
echo "SSH key already exists: $key" >&2
fi
@ -92,7 +121,6 @@ ensure_key(){
chmod 600 "$key" 2>/dev/null || true
chmod 644 "$keypub" 2>/dev/null || true
chown "$EDGE_USER:$EDGE_USER" "$key" "$keypub" 2>/dev/null || true
runuser -u "$EDGE_USER" -- bash -lc "touch '$ssh_dir/known_hosts' && chmod 600 '$ssh_dir/known_hosts'" >/dev/null 2>&1 || true
echo "$edge_home|$key|$keypub"
@ -105,28 +133,30 @@ write_wrapper(){
local vps_user="$4"
local key="$5"
local edge_home="$6"
local wrapper="/usr/local/sbin/iomatex-rt-${name}.sh"
local wrapper_path="${WRAPPER_DIR}/iomatex-rt-${name}.sh"
cat > "$wrapper" <<SCRIPT
cat >"$wrapper_path" <<EOF
#!/usr/bin/env bash
exec autossh -M 0 -N \\
-o ServerAliveInterval=30 \\
-o ServerAliveCountMax=3 \\
-o ExitOnForwardFailure=yes \\
-o StrictHostKeyChecking=accept-new \\
-o UserKnownHostsFile=${edge_home}/.ssh/known_hosts \\
-i ${key} \\
-p ${VPS_PORT} \\
-o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\
-i "${key}" \\
-p "${VPS_PORT}" \\
-R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\
${vps_user}@${VPS_HOST}
SCRIPT
"${vps_user}@${VPS_HOST}"
EOF
chmod +x "$wrapper"
chmod 0755 "$wrapper_path"
}
write_unit() {
local name="$1"
cat > "/etc/systemd/system/iomatex-rt-${name}.service" <<UNIT
local unit_path="${SYSTEMD_DIR}/iomatex-rt-${name}.service"
cat >"$unit_path" <<EOF
[Unit]
Description=IOMATEX Reverse Tunnel (${name}) %H
After=network-online.target
@ -136,76 +166,63 @@ Wants=network-online.target
User=${EDGE_USER}
Environment=AUTOSSH_GATETIME=0
Environment=AUTOSSH_POLL=30
ExecStart=/usr/local/sbin/iomatex-rt-${name}.sh
ExecStart=${WRAPPER_DIR}/iomatex-rt-${name}.sh
Restart=always
RestartSec=15
StartLimitIntervalSec=0
[Install]
WantedBy=multi-user.target
UNIT
EOF
chmod 0644 "$unit_path"
}
main(){
need_root
ensure_autossh
local hn vps_user cockpit_r z2m_r webui_r
local edge_home key keypub publine
hn="$(hostname)"
vps_user="tunnel_${hn}"
read cockpit_r z2m_r webui_r <<< "$(compute_ports "$hn")"
IFS='|' read -r edge_home key keypub < <(ensure_key "$hn" | tail -n 1)
if [[ -z "${keypub:-}" || ! -f "$keypub" ]]; then
log "ERROR: keypub not found: '${keypub:-}'"
exit 1
fi
publine="$(cat "$keypub")"
write_wrapper cockpit "$COCKPIT_LOCAL_PORT" "$cockpit_r" "$vps_user" "$key" "$edge_home"
write_wrapper z2m "$Z2M_LOCAL_PORT" "$z2m_r" "$vps_user" "$key" "$edge_home"
write_wrapper webui "$WEBUI_LOCAL_PORT" "$webui_r" "$vps_user" "$key" "$edge_home"
write_unit cockpit
write_unit z2m
write_unit webui
systemctl daemon-reload
# enable but DO NOT start (start after reboot)
enable_units_only() {
systemctl enable iomatex-rt-cockpit.service
systemctl enable iomatex-rt-z2m.service
systemctl enable iomatex-rt-webui.service
}
local EDGE_IP
EDGE_IP="$(curl -s https://api.ipify.org || true)"
fetch_public_ip() {
if ! command -v curl >/dev/null 2>&1; then
echo ""
return 0
fi
curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null || true
}
print_summary() {
local hostname_value="$1"
local edge_ip="$2"
local vps_user="$3"
local cockpit_remote_port="$4"
local z2m_remote_port="$5"
local webui_remote_port="$6"
local public_key_line="$7"
local vps_bootstrap_cmd="$8"
echo
echo "============================================================"
echo "EDGE READY (TUNNELS START AFTER REBOOT)"
echo
echo "HOSTNAME: ${hn}"
echo "EDGE IP: ${EDGE_IP}"
echo "HOSTNAME: ${hostname_value}"
echo "EDGE IP: ${edge_ip}"
echo
echo "VPS HOST: ${VPS_HOST}:${VPS_PORT}"
echo "VPS USER: ${vps_user}"
echo
echo "VPS PORTS:"
echo "Cockpit=${cockpit_r}"
echo "Z2M=${z2m_r}"
echo "WebUI=${webui_r}"
echo "Cockpit=${cockpit_remote_port}"
echo "Z2M=${z2m_remote_port}"
echo "WebUI=${webui_remote_port}"
echo
echo "SSH PUBLIC KEY:"
echo "$publine"
echo "$public_key_line"
echo
echo "RUN THIS ON VPS:"
echo
echo "EDGE_HOSTNAME='${hn}'; EDGE_IP='${EDGE_IP}'; EDGE_PUBKEY_LINE='${publine}'; COCKPIT_REMOTE_PORT='${cockpit_r}'; Z2M_REMOTE_PORT='${z2m_r}'; WEBUI_REMOTE_PORT='${webui_r}'; VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
echo "$vps_bootstrap_cmd"
echo
echo "IMPORTANT:"
echo "1. Run the VPS command above"
@ -214,4 +231,56 @@ main(){
echo "============================================================"
}
main() {
local hostname_value vps_user
local cockpit_remote_port z2m_remote_port webui_remote_port
local edge_home key keypub public_key_line edge_ip
local vps_bootstrap_cmd
require_root
preflight_checks
ensure_autossh_installed
hostname_value="$(hostname)"
vps_user="tunnel_${hostname_value}"
read -r cockpit_remote_port z2m_remote_port webui_remote_port <<<"$(compute_ports "$hostname_value")"
IFS='|' read -r edge_home key keypub < <(ensure_key "$hostname_value" | tail -n 1)
[[ -n "${edge_home:-}" ]] || die "edge home is empty"
[[ -n "${key:-}" ]] || die "key path is empty"
[[ -n "${keypub:-}" ]] || die "keypub path is empty"
[[ -f "$key" ]] || die "private key not found: $key"
[[ -f "$keypub" ]] || die "keypub not found: $keypub"
public_key_line="$(<"$keypub")"
write_wrapper cockpit "$COCKPIT_LOCAL_PORT" "$cockpit_remote_port" "$vps_user" "$key" "$edge_home"
write_wrapper z2m "$Z2M_LOCAL_PORT" "$z2m_remote_port" "$vps_user" "$key" "$edge_home"
write_wrapper webui "$WEBUI_LOCAL_PORT" "$webui_remote_port" "$vps_user" "$key" "$edge_home"
write_unit cockpit
write_unit z2m
write_unit webui
systemctl daemon-reload
# Enable but DO NOT start. Services should come up after reboot.
enable_units_only
edge_ip="$(fetch_public_ip)"
vps_bootstrap_cmd="EDGE_HOSTNAME='${hostname_value}'; EDGE_IP='${edge_ip}'; EDGE_PUBKEY_LINE='${public_key_line}'; COCKPIT_REMOTE_PORT='${cockpit_remote_port}'; Z2M_REMOTE_PORT='${z2m_remote_port}'; WEBUI_REMOTE_PORT='${webui_remote_port}'; VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
print_summary \
"$hostname_value" \
"$edge_ip" \
"$vps_user" \
"$cockpit_remote_port" \
"$z2m_remote_port" \
"$webui_remote_port" \
"$public_key_line" \
"$vps_bootstrap_cmd"
}
main "$@"