#!/usr/bin/env bash # ╔══════════════════════════════════════════════════════════════════╗ # ║ Gateway — Interactive Installer ║ # ║ Programmable Network Gateway for Raspberry Pi / VPS / Linux ║ # ╚══════════════════════════════════════════════════════════════════╝ # # Usage: # Interactive: sudo ./install-gateway.sh # Quick: sudo ./install-gateway.sh --profile vps --binary /path/to/gatewayd # Pipe: curl -sSL http://host/scripts/install-gateway.sh | sudo bash -s -- --profile vps # # Profiles: # rpi — Full install for Raspberry Pi (WiFi AP, SD hardening, Ollama optional) # vps — Minimal VPS node (no WiFi, no SD hardening, no Ollama) # node — Bare node for federation (gatewayd only, minimal deps) # full — Everything (all features, all optional packages) # custom — Interactive selection of each component # # Supports: Debian 12+, Ubuntu 22.04+, arm64 and amd64 set -euo pipefail # ── Colors and helpers ── RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m' log() { echo -e "${GREEN}[+]${NC} $*"; } warn() { echo -e "${YELLOW}[!]${NC} $*"; } err() { echo -e "${RED}[✗]${NC} $*"; exit 1; } info() { echo -e "${CYAN}[i]${NC} $*"; } ask() { echo -en "${BOLD}$1${NC} "; } # ── Detect architecture ── ARCH=$(dpkg --print-architecture 2>/dev/null || uname -m) case "$ARCH" in amd64|x86_64) ARCH=amd64 ;; arm64|aarch64) ARCH=arm64 ;; armhf|armv7l) ARCH=armhf ;; *) err "Unsupported architecture: $ARCH" ;; esac # ── Detect if RPi ── IS_RPI=false if [ -f /proc/device-tree/model ] && grep -qi "raspberry" /proc/device-tree/model 2>/dev/null; then IS_RPI=true fi # ── Root check ── [ "$(id -u)" -eq 0 ] || err "This script must be run as root (use sudo)" # ── Parse CLI args ── PROFILE="" BINARY_PATH="" GATEWAY_VERSION="latest" API_PORT="8080" NON_INTERACTIVE=false INSTALL_GO=false INSTALL_WIFI=false INSTALL_BLUETOOTH=false INSTALL_MESH=false INSTALL_REDSOCKS=false INSTALL_GITEA=false INSTALL_OLLAMA=false SD_HARDENING=false INSTALL_BUILD_DEPS=false REFRESH=false # access, server management and updates (plan section 11): a flag or the # GATEWAY_* variable install.sh passes through sudo AUTH="${GATEWAY_AUTH:-on}" ADMIN_PASSWORD_FILE="${GATEWAY_ADMIN_PASSWORD_FILE:-}" ADMIN_MODE="" SERVER_MGMT="${GATEWAY_SERVER_MGMT:-}" UPDATE_POLICY="${GATEWAY_UPDATE_POLICY:-notify}" UPDATE_WINDOW="${GATEWAY_UPDATE_WINDOW:-}" HEADSCALE="${GATEWAY_HEADSCALE:-}" RELAY_MODE="${GATEWAY_RELAY_MODE:-none}" TLS_SANS="${GATEWAY_TLS_SANS:-}" # answers given by a flag or a variable are not asked again AUTH_GIVEN="${GATEWAY_AUTH:+1}" UPDATE_GIVEN="${GATEWAY_UPDATE_POLICY:+1}" RELAY_GIVEN="${GATEWAY_RELAY_MODE:+1}" INSTALL_SUMMARY=/var/lib/gateway/install-summary.txt while [[ $# -gt 0 ]]; do case "$1" in --profile) PROFILE="$2"; shift 2 ;; --auth) AUTH="$2"; AUTH_GIVEN=1; shift 2 ;; --admin-password-file) ADMIN_PASSWORD_FILE="$2"; shift 2 ;; --server-mgmt) SERVER_MGMT="$2"; shift 2 ;; --update-policy) UPDATE_POLICY="$2"; UPDATE_GIVEN=1; shift 2 ;; --update-window) UPDATE_WINDOW="$2"; shift 2 ;; --headscale) HEADSCALE="$2"; shift 2 ;; --relay-mode) RELAY_MODE="$2"; RELAY_GIVEN=1; shift 2 ;; --tls-sans) TLS_SANS="$2"; shift 2 ;; --binary) BINARY_PATH="$2"; shift 2 ;; --version) GATEWAY_VERSION="$2"; shift 2 ;; --port) API_PORT="$2"; shift 2 ;; --non-interactive) NON_INTERACTIVE=true; shift ;; --refresh) REFRESH=true; shift ;; --with-go) INSTALL_GO=true; shift ;; --with-wifi) INSTALL_WIFI=true; shift ;; --with-bluetooth) INSTALL_BLUETOOTH=true; shift ;; --with-mesh) INSTALL_MESH=true; shift ;; --with-gitea) INSTALL_GITEA=true; shift ;; --with-ollama) INSTALL_OLLAMA=true; shift ;; --with-all) INSTALL_GO=true; INSTALL_WIFI=true; INSTALL_BLUETOOTH=true; INSTALL_MESH=true; INSTALL_REDSOCKS=true; INSTALL_GITEA=true; INSTALL_OLLAMA=true; shift ;; -h|--help) echo "Usage: sudo $0 [options]" echo "" echo "Options:" echo " --profile Install profile: rpi, vps, node, full, custom" echo " --binary Use pre-built binary instead of building from source" echo " --port API listen port (default: 8080)" echo " --non-interactive Skip all prompts (use with --profile)" echo " --auth on|off Sign-in required (default on; GATEWAY_AUTH)" echo " --admin-password-file The admin's password, read from a file (GATEWAY_ADMIN_PASSWORD_FILE);" echo " without it: generated on a node with a public address or with server" echo " management, else set in the Web UI with the one-time setup token" echo " --server-mgmt on|off Manage servers from this gateway: creates its SSH key (GATEWAY_SERVER_MGMT;" echo " asked when interactive, off when not)" echo " --update-policy notify|manual|auto Updates of gatewayd (default notify; GATEWAY_UPDATE_POLICY)" echo " --update-window HH:MM The maintenance window auto installs in (GATEWAY_UPDATE_WINDOW)" echo " --headscale on|off Run the mesh's control plane on this node (default off; GATEWAY_HEADSCALE;" echo " on installs the mesh packages)" echo " --relay-mode none|tls|public The control plane's relays (default none; GATEWAY_RELAY_MODE):" echo " none = direct connections only, tls = this node's relay on 443 (needs a" echo " public address), public = Tailscale's relays" echo " --tls-sans More addresses and names for the server certificate, comma-separated" echo " (GATEWAY_TLS_SANS); the node's public IPv4 is in it anyway" echo " --refresh Rewrite the gatewayd unit and its helper scripts only (no apt, no config)" echo " --with-go Install Go compiler" echo " --with-wifi Install WiFi AP packages (hostapd, dnsmasq)" echo " --with-bluetooth Install Bluetooth packages (bluez, dnsmasq for NAP)" echo " --with-mesh Install Tailscale + Headscale" echo " --with-gitea Install Gitea git server" echo " --with-ollama Install Ollama AI runtime" echo " --with-all Install all optional components" echo "" echo "Profiles:" echo " rpi Full RPi install (WiFi, Bluetooth, mesh, SD hardening, redsocks)" echo " vps Minimal VPS (firewall, mesh, no WiFi, no SD hardening)" echo " node Bare federation node (gatewayd only)" echo " full Everything (all features + optional packages)" echo " custom Interactive component selection" exit 0 ;; *) warn "Unknown option: $1"; shift ;; esac done [ -n "$PROFILE" ] || PROFILE="${GATEWAY_PROFILE:-}" # ── Apply profile defaults ── apply_profile() { case "$1" in rpi) INSTALL_WIFI=true; INSTALL_BLUETOOTH=true; INSTALL_MESH=true; INSTALL_REDSOCKS=true SD_HARDENING=true; INSTALL_BUILD_DEPS=true ;; vps) INSTALL_MESH=true; INSTALL_REDSOCKS=true INSTALL_BUILD_DEPS=true ;; node) # Bare minimum — just gatewayd ;; full) INSTALL_GO=true; INSTALL_WIFI=true; INSTALL_BLUETOOTH=true; INSTALL_MESH=true INSTALL_REDSOCKS=true; INSTALL_GITEA=true; INSTALL_OLLAMA=true SD_HARDENING=$IS_RPI; INSTALL_BUILD_DEPS=true ;; esac } # ── Interactive menu ── show_banner() { echo "" echo -e "${CYAN}╔══════════════════════════════════════════════════╗${NC}" echo -e "${CYAN}║${NC} ${BOLD}Gateway Installer${NC} ${CYAN}║${NC}" echo -e "${CYAN}║${NC} Programmable Network Gateway ${CYAN}║${NC}" echo -e "${CYAN}║${NC} $(uname -s) ${ARCH} $([ "$IS_RPI" = true ] && echo "(Raspberry Pi)" || echo "") ${CYAN}║${NC}" echo -e "${CYAN}╚══════════════════════════════════════════════════╝${NC}" echo "" } yesno() { local prompt="$1" default="${2:-y}" if $NON_INTERACTIVE; then [ "$default" = "y" ] && return 0 || return 1 fi local yn if [ "$default" = "y" ]; then ask "$prompt [Y/n]: "; read -r yn [ -z "$yn" ] || [[ "$yn" =~ ^[Yy] ]] else ask "$prompt [y/N]: "; read -r yn [[ "$yn" =~ ^[Yy] ]] fi } choose_profile() { if $NON_INTERACTIVE && [ -n "$PROFILE" ]; then apply_profile "$PROFILE" return fi echo "Select installation profile:" echo "" if $IS_RPI; then echo -e " ${BOLD}1)${NC} RPi Gateway — WiFi AP, mesh, firewall, SD hardening ${GREEN}(recommended)${NC}" else echo -e " ${BOLD}1)${NC} RPi Gateway — WiFi AP, mesh, firewall, SD hardening" fi if ! $IS_RPI; then echo -e " ${BOLD}2)${NC} VPS Node — Firewall, mesh, minimal footprint ${GREEN}(recommended)${NC}" else echo -e " ${BOLD}2)${NC} VPS Node — Firewall, mesh, minimal footprint" fi echo -e " ${BOLD}3)${NC} Bare Node — Just gatewayd, nothing else" echo -e " ${BOLD}4)${NC} Full Install — Everything including Gitea + Ollama" echo -e " ${BOLD}5)${NC} Custom — Choose each component" echo "" ask "Choice [1-5]: "; read -r choice case "$choice" in 1) PROFILE=rpi; apply_profile rpi ;; 2) PROFILE=vps; apply_profile vps ;; 3) PROFILE=node; apply_profile node ;; 4) PROFILE=full; apply_profile full ;; 5) PROFILE=custom; custom_selection ;; *) PROFILE=vps; apply_profile vps; warn "Invalid choice, using VPS profile" ;; esac } custom_selection() { echo "" info "Select components to install:" echo "" yesno " WiFi AP (hostapd, dnsmasq, wpa_supplicant)?" "$([ "$IS_RPI" = true ] && echo y || echo n)" && INSTALL_WIFI=true yesno " Bluetooth (bluez; PAN/NAP tethering, scanning)?" "$([ "$IS_RPI" = true ] && echo y || echo n)" && INSTALL_BLUETOOTH=true yesno " Mesh networking (Tailscale + Headscale)?" "y" && INSTALL_MESH=true yesno " Transparent proxy (redsocks)?" "y" && INSTALL_REDSOCKS=true yesno " Go compiler (for building from source)?" "n" && INSTALL_GO=true yesno " Gitea git server?" "n" && INSTALL_GITEA=true yesno " Ollama AI runtime?" "$([ "$ARCH" != "armhf" ] && echo n || echo n)" && INSTALL_OLLAMA=true if $IS_RPI; then yesno " SD card hardening (volatile journald, swap off)?" "y" && SD_HARDENING=true fi } choose_binary() { if [ -n "$BINARY_PATH" ]; then return fi echo "" echo "How to install gatewayd binary?" echo "" echo -e " ${BOLD}1)${NC} Use pre-built binary (provide path or URL)" echo -e " ${BOLD}2)${NC} Build from source (requires Go — will install if needed)" echo -e " ${BOLD}3)${NC} Skip (binary already installed or will install later)" echo "" if $NON_INTERACTIVE; then choice=3 else ask "Choice [1-3]: "; read -r choice fi case "$choice" in 1) ask "Path or URL to gatewayd binary: "; read -r BINARY_PATH ;; 2) INSTALL_GO=true INSTALL_BUILD_DEPS=true ;; 3) if command -v gatewayd &>/dev/null; then info "Using existing: $(gatewayd -version 2>/dev/null || echo 'gatewayd found')" else warn "gatewayd not found — install it manually later" fi ;; esac } # ── Access, server management, updates (plan section 11) ── # public_ipv4: the first address of this host that is neither private nor # CGNAT, "" when it has none (behind NAT) — and success either way: under # pipefail grep's "nothing" ended a `(public_ipv4; tls_sans)` list early public_ipv4() { ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep -vE '^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.|100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.|169\.254\.)' | head -n 1 || true } has_public_ipv4() { [ -n "$(public_ipv4)" ]; } # tls_sans: the addresses and names asked for the server certificate, one # per line (commas or spaces between them) tls_sans() { tr ', ' '\n\n' <<<"$TLS_SANS" | sed '/^$/d'; } # tls_san_kind : IP or DNS — how the certificate's subjectAltName # carries it; nothing, and failure, for anything else tls_san_kind() { local o if [[ "$1" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then # openssl refuses an octet over 255 halfway through the install for o in ${1//./ }; do [ "$((10#$o))" -le 255 ] || return 1; done echo IP elif [[ "$1" =~ ^[0-9A-Fa-f:]{2,39}$ && "$1" == *:*:* && "$1" != *:::* ]] && [ "$(grep -o '::' <<<"$1" | wc -l)" -le 1 ]; then echo IP elif [[ "$1" =~ ^(\*\.)?[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$ ]]; then echo DNS else return 1 fi } choose_access() { if ! $NON_INTERACTIVE; then echo "" echo -e "${BOLD}Access, servers and updates${NC}" if [ -z "$SERVER_MGMT" ]; then yesno "Manage servers (relays, bridges, Splitting) from this gateway? It creates the gateway's SSH key" "y" && SERVER_MGMT=on || SERVER_MGMT=off fi if [ "$SERVER_MGMT" = on ]; then [ "$AUTH" = on ] || info "Server management needs sign-in: authentication stays on" AUTH=on elif [ -z "$AUTH_GIVEN" ]; then yesno "Require sign-in to the Web UI and the API?" "y" && AUTH=on || AUTH=off fi if [ "$AUTH" = on ] && [ -z "$ADMIN_PASSWORD_FILE" ]; then local def=3 { has_public_ipv4 || [ "$SERVER_MGMT" = on ]; } && def=1 echo "" echo "The admin's password:" echo -e " ${BOLD}1)${NC} Generate one now (shown once, at the end)" echo -e " ${BOLD}2)${NC} Enter one now" [ "$SERVER_MGMT" = on ] || echo -e " ${BOLD}3)${NC} Set it in the Web UI with a one-time setup token (printed at the end)" ask "Choice [$def]: "; read -r choice case "${choice:-$def}" in 1) ADMIN_MODE=generate ;; 2) ADMIN_MODE=enter ;; 3) [ "$SERVER_MGMT" = on ] && ADMIN_MODE=generate || ADMIN_MODE=web ;; *) ADMIN_MODE=generate; warn "Invalid choice: the password is generated" ;; esac fi if [ -z "$HEADSCALE" ] && $INSTALL_MESH; then echo "" yesno "Run the mesh's control plane (headscale) on this node? Most nodes join another node's" "n" && HEADSCALE=on || HEADSCALE=off fi if [ "$HEADSCALE" = on ] && [ -z "$RELAY_GIVEN" ]; then echo "" echo "Relays, for devices that cannot reach each other directly:" echo -e " ${BOLD}1)${NC} None — direct connections only ${GREEN}(default)${NC}" echo -e " ${BOLD}2)${NC} This gateway's relay over TLS on 443 (needs a public address)" echo -e " ${BOLD}3)${NC} Tailscale's public relays" ask "Choice [1]: "; read -r choice case "${choice:-1}" in 2) RELAY_MODE=tls ;; 3) RELAY_MODE=public ;; *) RELAY_MODE=none ;; esac fi if [ -z "$UPDATE_GIVEN" ]; then echo "" echo "Updates of gatewayd:" echo -e " ${BOLD}1)${NC} Notify — say when a release is out, install by hand ${GREEN}(default)${NC}" echo -e " ${BOLD}2)${NC} Manual — check only when asked" echo -e " ${BOLD}3)${NC} Auto — install signed releases in a maintenance window" ask "Choice [1]: "; read -r choice case "${choice:-1}" in 2) UPDATE_POLICY=manual ;; 3) UPDATE_POLICY=auto [ -n "$UPDATE_WINDOW" ] || { ask "Maintenance window start (HH:MM, local time) [03:00]: "; read -r UPDATE_WINDOW; UPDATE_WINDOW="${UPDATE_WINDOW:-03:00}"; } ;; *) UPDATE_POLICY=notify ;; esac fi fi [ -n "$SERVER_MGMT" ] || SERVER_MGMT=off [ -n "$HEADSCALE" ] || HEADSCALE=off case "$HEADSCALE" in on|off) ;; *) err "--headscale: on or off, not '$HEADSCALE'" ;; esac case "$RELAY_MODE" in none|tls|public) ;; *) err "--relay-mode: none, tls or public, not '$RELAY_MODE'" ;; esac [ "$RELAY_MODE" != none ] && [ "$HEADSCALE" = off ] && err "the relay mode is the control plane's: add --headscale on" if [ "$RELAY_MODE" = tls ] && ! has_public_ipv4; then err "this node's relay over TLS needs a public address on the node: choose it on the Mesh page once the address and port 443 reach this node" fi [ "$HEADSCALE" = on ] && INSTALL_MESH=true if [ "$AUTH" = on ] && [ -z "$ADMIN_MODE" ]; then if [ -n "$ADMIN_PASSWORD_FILE" ]; then ADMIN_MODE="file" elif has_public_ipv4 || [ "$SERVER_MGMT" = on ]; then ADMIN_MODE=generate else ADMIN_MODE=web fi fi case "$AUTH" in on|off) ;; *) err "--auth: on or off, not '$AUTH'" ;; esac case "$SERVER_MGMT" in on|off) ;; *) err "--server-mgmt: on or off, not '$SERVER_MGMT'" ;; esac case "$UPDATE_POLICY" in notify|manual|auto) ;; *) err "--update-policy: notify, manual or auto, not '$UPDATE_POLICY'" ;; esac [ "$SERVER_MGMT" = on ] && [ "$AUTH" = off ] && err "server management needs sign-in: drop --auth off (the gateway's key reaches every server)" if [ "$UPDATE_POLICY" = auto ] && ! [[ "$UPDATE_WINDOW" =~ ^([01][0-9]|2[0-3]):[0-5][0-9]$ ]]; then err "auto updates install in a maintenance window: give --update-window HH:MM" fi local san while IFS= read -r san; do tls_san_kind "$san" >/dev/null || err "--tls-sans: '$san' is neither an IP address nor a DNS name" done < <(tls_sans) if [ "$ADMIN_MODE" = file ]; then [ -r "$ADMIN_PASSWORD_FILE" ] || err "the admin password file $ADMIN_PASSWORD_FILE cannot be read" [ "$(head -n 1 "$ADMIN_PASSWORD_FILE" | tr -d '\r\n' | wc -c)" -ge 8 ] || err "the admin password in $ADMIN_PASSWORD_FILE has fewer than 8 characters" fi log "Access: sign-in $AUTH$([ "$AUTH" = on ] && echo ", admin password: $ADMIN_MODE"), server management $SERVER_MGMT, updates $UPDATE_POLICY, control plane $HEADSCALE$([ "$HEADSCALE" = on ] && echo " (relays: $RELAY_MODE)")" } # admin_password_into writes the admin's password into file (0600): the # file's first line, a generated one, or one typed twice. admin_password_into() { local out="$1" a b case "$ADMIN_MODE" in file) head -n 1 "$ADMIN_PASSWORD_FILE" | tr -d '\r\n' > "$out" ;; generate) openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 20 > "$out" ;; enter) while :; do # IFS= keeps the spaces at either end: the password is what was typed ask "Admin password (8 characters or more; 12+ advised): "; IFS= read -rs a; echo ask "Again: "; IFS= read -rs b; echo if [ "$a" != "$b" ]; then warn "They differ: once more"; continue; fi if [ "${#a}" -lt 8 ]; then warn "Fewer than 8 characters: once more"; continue; fi printf '%s' "$a" > "$out" break done ;; esac } # create_admin makes the admin account before the first start, so no first # visitor can claim the node (setup is closed once an admin exists); an # admin there already (a re-run) is kept. create_admin() { case "$ADMIN_MODE" in generate|enter|file|web) ;; *) return 0 ;; esac if ! command -v gatewayd >/dev/null 2>&1; then [ "$ADMIN_MODE" = web ] && return 0 warn "No gatewayd binary yet: create the admin later (sudo gatewayd user add --username admin --role admin)" ADMIN_MODE=later; return 0 fi # an admin there already (a re-run) is kept, whatever was asked; setup-token # reads the accounts without touching the database, gatewayd running or not # (exit 0: a token, or nothing when an admin exists; else it failed) local tok rc=0 tok=$(timeout 15 gatewayd setup-token --config /var/lib/gateway/config.yaml 2>/dev/null) || rc=$? if [ "$rc" != 0 ]; then warn "Whether an admin exists could not be read (gatewayd setup-token exit $rc): none is made — create it later: sudo gatewayd user add --username admin --role admin" ADMIN_MODE=later; return 0 fi if [ -z "$tok" ]; then info "An admin exists already: kept" ADMIN_MODE=existing; return 0 fi [ "$ADMIN_MODE" = web ] && return 0 if systemctl is-active --quiet gatewayd 2>/dev/null; then warn "gatewayd is running: the installer does not write accounts under it — stop it, then: sudo gatewayd user add --username admin --role admin" ADMIN_MODE=running; return 0 fi admin_password_into "$ADMIN_PW_TMP" if timeout 60 gatewayd user add --config /var/lib/gateway/config.yaml --username admin --role admin < "$ADMIN_PW_TMP" >/dev/null; then ADMIN_CREATED=1 log "Admin account 'admin' created: the Web UI opens with a sign-in, no first-visitor setup" else err "the admin account could not be created (gatewayd user add)" fi } # api_call METHOD PATH [JSON-FILE]: the local API over its own CA, with the # admin's token from a header file (nothing secret in argv) api_call() { local args=(-sS --max-time 30 --cacert /etc/gateway/tls/ca.crt -X "$1" -H "Content-Type: application/json") [ -s "$API_HDR" ] && args+=(-H "@$API_HDR") [ -n "${3:-}" ] && args+=(--data-binary "@$3") curl "${args[@]}" "https://127.0.0.1:${API_PORT}/api/v1$2" } # configure_after_start sets what the API decides — server management, the # control plane and its relays, the update policy — signed in as the admin # (with sign-in off, without a token), and reads the update policy back for # the summary (a development build keeps updates manual by default) configure_after_start() { local signed=false case "$ADMIN_MODE" in generate|enter|file) signed=true ;; esac if [ "$AUTH" = on ] && ! $signed; then if [ "$SERVER_MGMT" = on ] || [ "$UPDATE_POLICY" != notify ] || [ "$HEADSCALE" = on ]; then warn "Server management, the control plane and the update policy are set in the Web UI once you sign in (the installer did not set the admin's password)" fi return 0 fi local code for _ in $(seq 1 60); do code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 --cacert /etc/gateway/tls/ca.crt "https://127.0.0.1:${API_PORT}/api/v1/status" || true) case "$code" in 200|401|403) break ;; esac sleep 2 done # the login body holds the password: the exit trap removes the file even # when the install stops here local body="$API_BODY" out if $signed; then python3 -c 'import json,sys; print(json.dumps({"username": "admin", "password": open(sys.argv[1]).read()}))' "$ADMIN_PW_TMP" > "$body" local token token=$(api_call POST /auth/login "$body" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("token", ""))' 2>/dev/null || true) : > "$body" if [ -z "$token" ]; then warn "The installer could not sign in to the API: set server management, the control plane and the update policy in the Web UI" return 0 fi printf 'Authorization: Bearer %s\n' "$token" > "$API_HDR" fi if [ "$HEADSCALE" = on ]; then echo '{"action": "start"}' > "$body" out=$(api_call POST /mesh/headscale/control "$body" || true) if [ -z "$out" ] || [[ "$out" == *'"error"'* ]]; then warn "headscale was not started (${out:-no answer}): Mesh in the Web UI" HEADSCALE="on (not started: Mesh in the Web UI)" else log "headscale runs on this node" if [ "$RELAY_MODE" != none ]; then if [ "$RELAY_MODE" = tls ]; then printf '{"mode": "tls", "tls_host": "%s"}\n' "$(public_ipv4)" > "$body" else printf '{"mode": "%s"}\n' "$RELAY_MODE" > "$body" fi out=$(api_call PUT /mesh/relays "$body" || true) if [[ "$out" == *"\"mode\":\"$RELAY_MODE\""* ]]; then log "Relays: $RELAY_MODE" else warn "The relays stay none: Mesh → Relays in the Web UI (${out:-no answer})" RELAY_MODE="none (the installer's $RELAY_MODE was refused)" fi fi fi fi if ! $signed; then [ "$UPDATE_POLICY" = notify ] || warn "The update policy is set with sign-in on: System → Updates" return 0 fi if [ "$SERVER_MGMT" = on ]; then echo '{"enabled": true}' > "$body" out=$(api_call PUT /servers/settings "$body" || true) if [[ "$out" == *'"enabled":true'* ]]; then SERVER_KEY=$(api_call GET /servers/key | python3 -c 'import json,sys; k=json.load(sys.stdin); print(k.get("public_key", "").strip(), "(" + k.get("fingerprint", "") + ")")' 2>/dev/null || true) log "Server management on: the gateway's SSH key is made" else warn "Server management was not turned on: Servers in the Web UI" fi fi if [ "$UPDATE_POLICY" != notify ]; then if [ "$UPDATE_POLICY" = auto ]; then printf '{"policy": "auto", "window_start": "%s", "window_minutes": 120}\n' "$UPDATE_WINDOW" > "$body" else printf '{"policy": "%s"}\n' "$UPDATE_POLICY" > "$body" fi out=$(api_call PUT /system/update/policy "$body" || true) if [[ "$out" == *"\"policy\":\"$UPDATE_POLICY\""* ]]; then log "Updates: $UPDATE_POLICY" else warn "$UPDATE_POLICY updates were refused: System → Updates in the Web UI" fi fi # no answer leaves read at the end of its input: under set -e that ended # the install before its summary local actual="" dev="" read -r actual dev < <(api_call GET /system/update | python3 -c 'import json,sys; u=json.load(sys.stdin); print(u.get("policy", ""), (u.get("node") or {}).get("dev", False))' 2>/dev/null || true) || true if [ -n "${actual:-}" ] && [ "$actual" != "$UPDATE_POLICY" ]; then local why="" [ "$actual" = manual ] && [ "${dev:-}" = True ] && why=": a development build updates by hand" UPDATE_POLICY="$actual (asked for $UPDATE_POLICY$why)" UPDATE_WINDOW="" fi : > "$API_HDR" } # install_summary: what the operator must keep — shown and confirmed when # interactive, else a 0600 file the Web UI reminds them to delete install_summary() { local ip pw ca ip=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'src \K\S+' || hostname -I | awk '{print $1}') ca=$(openssl x509 -in /etc/gateway/tls/ca.crt -noout -fingerprint -sha256 2>/dev/null | cut -d= -f2) case "$ADMIN_MODE" in generate) pw=$(cat "$ADMIN_PW_TMP") ;; enter) pw="(the one you entered)" ;; file) pw="(from $ADMIN_PASSWORD_FILE)" ;; existing) pw="(unchanged: the admin existed before)" ;; running) pw="(not set: gatewayd was running — stop it, then: sudo gatewayd user add --username admin --role admin)" ;; later) pw="(none yet: sudo gatewayd user add --username admin --role admin)" ;; web) pw="(set it in the Web UI with the one-time setup token: sudo gatewayd setup-token)" ;; *) pw="(sign-in is off)" ;; esac # plain variables: an apostrophe inside ${VAR:+…} in a $(heredoc) is a # "bad substitution" for bash local mgmt="$SERVER_MGMT" upd="$UPDATE_POLICY" cp text [ -n "$SERVER_KEY" ] && mgmt="$SERVER_MGMT — the gateway's SSH key: $SERVER_KEY" [ -n "$UPDATE_WINDOW" ] && upd="$UPDATE_POLICY (window $UPDATE_WINDOW)" if [ "${HEADSCALE%% *}" = on ]; then cp="headscale on this node${HEADSCALE#on}, relays: $RELAY_MODE" if ! has_public_ipv4; then cp="$cp Port forwarding: the node has no public address: forward TCP 8085 (the control plane) to it on the router STUN: answered here only for the LAN: once a server with the DERP role is in Servers, choose it in Mesh → Relays" fi else cp="not on this node (it joins another node's)" fi text="Gateway install summary — $(hostname) — $(date -u +%Y-%m-%dT%H:%MZ) Web UI: https://${ip}:${API_PORT}/ Sign-in: ${AUTH} Admin user: admin Admin password: ${pw} CA fingerprint: ${ca:-none} (/etc/gateway/tls/ca.crt: import it so the browser trusts the Web UI) Server management: ${mgmt} Control plane: ${cp} Updates: ${upd}" echo "" if $NON_INTERACTIVE; then # a re-run that kept the admin keeps the first install's summary: it # may hold the only copy of a generated password if [ "$ADMIN_MODE" = existing ] && [ -s "$INSTALL_SUMMARY" ]; then log "Install summary of the first install kept: $INSTALL_SUMMARY (0600) — store it somewhere safe, then delete it: sudo rm $INSTALL_SUMMARY" return fi ( umask 077; printf '%s\n' "$text" > "$INSTALL_SUMMARY" ) log "Install summary: $INSTALL_SUMMARY (0600) — store it somewhere safe, then delete it: sudo rm $INSTALL_SUMMARY" return fi echo -e "${BOLD}${text}${NC}" echo "" [ "$ADMIN_MODE" = generate ] && warn "The admin password is shown only here." local ans while :; do ask "Store this now. Type SAVED to go on: "; read -r ans [ "$ans" = SAVED ] && break done } # ── Installation functions ── # apt_install_any ... — install the first package name this distro knows. # For tools whose package was renamed between releases (dhcpcd: dhcpcd-base on # Debian 12+/13, dhcpcd5 on Ubuntu 22.04; vcgencmd: raspi-utils on Raspberry Pi # OS trixie, libraspberrypi-bin before). Never fails the install. apt_install_any() { local p for p in "$@"; do if apt-cache show "$p" >/dev/null 2>&1; then # "|| warn": under set -e/pipefail a failing install (dpkg lock, # unmet dependencies) used to abort the whole installer. apt-get install -y -qq "$p" 2>&1 | tail -1 || warn "apt-get install $p failed — the feature that needs it stays off" return 0 fi done warn "none of [$*] is available from apt — the feature that needs it stays off" return 0 } # Every external program gatewayd executes at runtime, grouped by what needs # it (inventory of exec.Command call sites, 2026-10-07). Optional features are # installed by their own step below; everything here is needed by a plain node. install_base_packages() { log "Installing base packages..." apt-get update -qq apt-get install -y -qq \ nftables iptables iproute2 conntrack \ wireguard-tools openvpn \ curl wget jq ca-certificates openssl openssh-client \ sqlite3 \ tcpdump ethtool \ cryptsetup \ procps iputils-ping kmod dbus \ python3 python3-yaml 2>&1 | tail -1 # ip/tc (iproute2), nft, iptables, conntrack, wg — routing, firewall, tunnels # openvpn — OpenVPN tunnels (the daemon starts each instance itself) # openssl — setup_tls below; ca-certificates for https fetches # openssh-client (scp) — backups to a remote target # tcpdump — Diagnostics → Capture and the live Map # ethtool — r8152 USB-Ethernet offload fix on the WAN # cryptsetup — Settings → Encrypted Storage # procps/iputils-ping/kmod/dbus — pgrep/pkill/sysctl, health probes, module checks, BT D-Bus # python3 + python3-yaml — scripts/verify-node.sh and the ui-truth harness # DHCP client for WAN uplinks / Interfaces → DHCP Client (renamed across releases) apt_install_any dhcpcd-base dhcpcd5 dhcpcd # The distro enables a no-op openvpn.service; gatewayd runs its own instances. systemctl disable --now openvpn 2>/dev/null || true # vcgencmd for the CPU temperature / throttling readout on a Raspberry Pi if $IS_RPI && ! command -v vcgencmd &>/dev/null; then apt_install_any raspi-utils libraspberrypi-bin fi # Not installed on purpose: network-manager (optional — used only when it # already manages an interface; installing it would take interfaces over), # amneziawg (not in the distro repos; obfuscated WG is used only when the # module and `awg` are present). # Disable systemd-resolved if present (conflicts with gateway DNS) if systemctl is-active systemd-resolved &>/dev/null; then info "Disabling systemd-resolved (gateway handles DNS)..." systemctl disable --now systemd-resolved 2>/dev/null || true rm -f /etc/resolv.conf echo "nameserver 1.1.1.1" > /etc/resolv.conf fi } install_wifi_packages() { log "Installing WiFi AP packages..." apt-get install -y -qq \ hostapd dnsmasq wpasupplicant iw wireless-tools rfkill 2>&1 | tail -1 # Prevent hostapd and dnsmasq from auto-starting (gateway manages them) systemctl disable hostapd 2>/dev/null || true systemctl disable dnsmasq 2>/dev/null || true systemctl stop hostapd 2>/dev/null || true systemctl stop dnsmasq 2>/dev/null || true } install_bluetooth_packages() { log "Installing Bluetooth packages (PAN/NAP, scanning)..." # bluetoothctl / btmgmt / hciconfig come with bluez; dnsmasq serves DHCP on the NAP bridge apt-get install -y -qq bluez dnsmasq 2>&1 | tail -1 systemctl disable dnsmasq 2>/dev/null || true systemctl stop dnsmasq 2>/dev/null || true systemctl enable --now bluetooth 2>/dev/null || true } install_redsocks() { log "Installing redsocks (transparent proxy)..." apt-get install -y -qq redsocks 2>&1 | tail -1 systemctl disable redsocks 2>/dev/null || true systemctl stop redsocks 2>/dev/null || true } install_go() { GO_VERSION="1.24.2" if command -v go &>/dev/null && go version | grep -q "$GO_VERSION"; then info "Go $GO_VERSION already installed" return fi log "Installing Go $GO_VERSION..." wget -q "https://go.dev/dl/go${GO_VERSION}.linux-${ARCH}.tar.gz" -O /tmp/go.tar.gz rm -rf /usr/local/go tar -C /usr/local -xzf /tmp/go.tar.gz rm /tmp/go.tar.gz export PATH=$PATH:/usr/local/go/bin echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh log "Go $(go version | grep -oP 'go[\d.]+')" } # sha256_is FILE SUM: the file's sha256 is SUM, and SUM is not empty sha256_is() { [ -n "$2" ] && [ "$(sha256sum "$1" | cut -c1-64)" = "$2" ]; } # headscale_sha256 ARCH: the sum of headscale's .deb, from its release's # checksums.txt (checked against the download, 2026-10-21) headscale_sha256() { case "$1" in amd64) echo 3a610d3941de367a57b63b277054e02dee90084d3a6f6112a57709ec5cdd7b75 ;; arm64) echo d6f8e6562fa0efeba7c21df34148a7e7968cbcee0c3a3b247ef345db5a6e7b68 ;; armv7) echo 249cd0c2c0ae3e69e72782198b14eb1152819c2795ca4724ff83f0f2f9bffb88 ;; esac } install_mesh() { # a re-run over a node whose control plane gateway configured before # (its marker in the config) leaves headscale as it found it: stopping it # below left it down, and with the admin kept nothing signs in to start it local hs_was_active=false hs_was_enabled=false if grep -q '# gateway-managed v1' /etc/headscale/config.yaml 2>/dev/null; then systemctl is-active --quiet headscale 2>/dev/null && hs_was_active=true systemctl is-enabled --quiet headscale 2>/dev/null && hs_was_enabled=true fi # Headscale binary HEADSCALE_VERSION="0.23.0" if ! command -v headscale &>/dev/null; then log "Installing Headscale $HEADSCALE_VERSION..." local deb_arch=$ARCH [ "$deb_arch" = "armhf" ] && deb_arch="armv7" wget -q "https://github.com/juanfont/headscale/releases/download/v${HEADSCALE_VERSION}/headscale_${HEADSCALE_VERSION}_linux_${deb_arch}.deb" -O /tmp/headscale.deb # by its pinned sum (plan 7.5): another file is refused before dpkg if ! sha256_is /tmp/headscale.deb "$(headscale_sha256 "$deb_arch")"; then rm -f /tmp/headscale.deb err "headscale ${HEADSCALE_VERSION} (${deb_arch}): the download's sha256 is not the pinned one — refusing" fi dpkg -i /tmp/headscale.deb 2>/dev/null || apt-get install -f -y -qq rm -f /tmp/headscale.deb else info "Headscale already installed" fi # Headscale config. Two non-default choices baked in: # # 1. No relay, by design (the operator's choice, 2026-10-19; the # server-management plan 10.1-10.2): direct connections only. # headscale refuses an empty map, so derp-norelay.yaml holds one # region, 998 "No relay (by design)", whose only node is a # STUN-only stub on the detected primary IP; clients name it when # they warn that no relay answers. The Mesh page switches to this # node's relay over TLS, Tailscale's public relays or an external # one; every map is re-read every 10 minutes without a restart. # # 2. magic_dns=false — gatewayd's own DNS plane is the source of # truth for mesh DNS so it can apply per-policy DNAT, query # logs, and telemetry blocking. Letting magic_dns push its own # resolver onto every peer fights that path. # # /etc/headscale/config.yaml is the persistent canonical file; # mesh_dns.go (gatewayd-side) reads `base_domain` from it on every # sync, and updateHeadscaleBaseDomain rewrites the line in place # so operator-added DERP / OIDC / ACL sections survive UI edits. # # We use a marker comment ("# gateway-managed v1") to distinguish # our config from the headscale .deb's default — the package # writes its own /etc/headscale/config.yaml that listens on # 0.0.0.0:8080 and steals the port gatewayd wants. On a fresh # install we always rewrite; on a re-run we only skip if the # marker is present (operator-edited configs survive). if [ ! -f /etc/headscale/config.yaml ] || ! grep -q '# gateway-managed v1' /etc/headscale/config.yaml; then if [ -f /etc/headscale/config.yaml ]; then log "Replacing headscale config (deb-default detected — no relay by design)..." cp /etc/headscale/config.yaml /etc/headscale/config.yaml.bak.$(date -u +%Y%m%dT%H%M%SZ) else log "Writing headscale config (no relay by design, no MagicDNS)..." fi mkdir -p /etc/headscale /var/lib/headscale # Detect the box's primary outbound IP so server_url points at an # address other peers can actually reach. Hardcoded 127.0.0.1 is # the headscale-default but it propagates into the DERPMap as the # local-DERP node's HostName (via automatically_add_embedded_derp_region) — # every peer then tries to relay through its OWN 127.0.0.1:8085, # finds nothing, and falls off the tailnet. Lost an hour to that # one. Falls back to 127.0.0.1 only when we genuinely can't detect # (no default route, unusual netstack). gw_local_ip=$(ip route get 1.1.1.1 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="src") print $(i+1)}' | head -1) if [ -z "$gw_local_ip" ]; then gw_local_ip="127.0.0.1" warn "Couldn't auto-detect primary IP; headscale server_url is left as 127.0.0.1. Set server_url in /etc/headscale/config.yaml before peers join." fi cat > /etc/headscale/config.yaml < /etc/headscale/derp-norelay.yaml </dev/null || true systemctl stop headscale 2>/dev/null || true # Seed the operator-supplied namespace (defaults to "gateway") so # the very first preauthkey-create call from the UI doesn't fail # with the gRPC-internal "user not found". We have to briefly start # headscale to issue the user-create CLI, then stop it again — the # alternative (seeding on first Start from the UI) means the very # first Generate click after Start still races, which is worse UX # than a 4-second blip at install time. local hs_ns="${GATEWAY_HEADSCALE_NAMESPACE:-gateway}" if command -v headscale &>/dev/null; then systemctl start headscale 2>/dev/null || true sleep 3 if systemctl is-active headscale &>/dev/null; then headscale user create "$hs_ns" 2>/dev/null || true systemctl stop headscale 2>/dev/null || true fi fi $hs_was_enabled && { systemctl enable headscale >/dev/null 2>&1 || true; } if $hs_was_active; then systemctl start headscale 2>/dev/null || true log "headscale runs again, as before this install" fi # Tailscale (mesh client) if ! command -v tailscale &>/dev/null; then install_tailscale else info "Tailscale already installed" fi } # install_tailscale: from Tailscale's apt repository, its signing key pinned # by fingerprint (plan 7.5) — not `curl https://tailscale.com/install.sh | sh` TAILSCALE_KEY_FPR=2596A99EAAB33821893C0A79458CA832957F5868 install_tailscale() { log "Installing Tailscale from its apt repository (signing key pinned)..." local dist code dist=$(. /etc/os-release && echo "${ID:-}") code=$(. /etc/os-release && echo "${VERSION_CODENAME:-}") case "$dist" in debian|ubuntu|raspbian) ;; *) err "tailscale: Tailscale's repository has Debian, Ubuntu and Raspberry Pi OS, not '$dist'" ;; esac [ -n "$code" ] || err "tailscale: the release codename is not in /etc/os-release" command -v gpg >/dev/null 2>&1 || apt-get install -y -qq gpg >/dev/null local key=/usr/share/keyrings/tailscale-archive-keyring.gpg tmp fpr keys tmp=$(mktemp) curl -fsSL "https://pkgs.tailscale.com/stable/${dist}/${code}.noarmor.gpg" -o "$tmp" || { rm -f "$tmp"; err "tailscale: its signing key could not be fetched"; } # the whole file becomes apt's keyring for the repository: one key, the # pinned one — a second key after it would be trusted too keys=$(gpg --show-keys --with-colons "$tmp" 2>/dev/null | grep -c '^pub:' || true) fpr=$(gpg --show-keys --with-colons "$tmp" 2>/dev/null | awk -F: '/^fpr/ {print $10; exit}') if [ "$keys" != 1 ] || [ "$fpr" != "$TAILSCALE_KEY_FPR" ]; then rm -f "$tmp" err "tailscale: the repository's key file holds ${keys:-0} key(s), the first '${fpr:-unreadable}', not the pinned $TAILSCALE_KEY_FPR alone — refusing" fi install -m 0644 "$tmp" "$key" rm -f "$tmp" echo "deb [signed-by=$key] https://pkgs.tailscale.com/stable/${dist} ${code} main" > /etc/apt/sources.list.d/tailscale.list apt-get update -qq apt-get install -y -qq tailscale >/dev/null log "Tailscale $(tailscale version 2>/dev/null | head -1)" } install_gitea() { GITEA_VERSION="1.23.8" if command -v gitea &>/dev/null; then info "Gitea already installed" return fi log "Installing Gitea $GITEA_VERSION..." wget -q "https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-linux-${ARCH}" -O /usr/local/bin/gitea chmod +x /usr/local/bin/gitea useradd -r -s /bin/bash -d /srv/data/gitea git 2>/dev/null || true mkdir -p /srv/data/gitea/{custom,data,log} chown -R git:git /srv/data/gitea } install_ollama() { if command -v ollama &>/dev/null; then info "Ollama already installed" return fi log "Installing Ollama..." curl -fsSL https://ollama.ai/install.sh | sh } setup_directories() { log "Creating directory structure..." # 0750 root-only (GR-371 #407): kv_settings inside gateway.db holds the # JWT secret, managed API keys, node_api_key and the Telegram token. At # the default 0755 any local unprivileged user could read the DB and # forge admin sessions — the same reason config.yaml is forced to 0600. # "backup" (singular) is what backup_scheduler.go writes; the old # "backups" directory was never used by anything. mkdir -p /var/lib/gateway/{ovpn,secrets,backup} mkdir -p /tmp/gateway/ovpn/certs mkdir -p /etc/gateway/tls/issued chmod 0750 /var/lib/gateway /var/lib/gateway/secrets 2>/dev/null || true chmod 0750 /etc/gateway /etc/gateway/tls 2>/dev/null || true # Match deployments/systemd/gatewayd.conf so a tmpfiles run keeps it. cat > /etc/tmpfiles.d/gatewayd.conf << 'TMPEOF' # /etc/tmpfiles.d/gatewayd.conf — installed by install-gateway.sh d /var/lib/gateway 0750 root root - TMPEOF # Existing DBs from earlier installs are world-readable; fix in place. chmod 0600 /var/lib/gateway/gateway.db /var/lib/gateway/gateway.db-wal /var/lib/gateway/gateway.db-shm 2>/dev/null || true chmod 700 /var/lib/gateway/secrets } # Internal CA + server cert for gatewayd HTTPS. ECDSA P-256, not # Ed25519: Windows schannel (default curl / .NET TLS) failed handshake # on Ed25519 with SEC_E_INVALID_TOKEN, so the CA needs to be P-256 for # universal cross-platform support. CA validity: 10 years. Server # cert: 825 days (max accepted by current macOS/iOS without a profile). # # tls_extra_names: the [alt_names] lines for the node's public IPv4 and the # addresses asked for (--tls-sans) — a peer or a browser reaching the node # by one of them checks that the certificate names it tls_extra_names() { local san kind n_ip=2 n_dns=3 seen=" 127.0.0.1 100.64.0.1 gateway.mesh *.gateway.mesh localhost " while IFS= read -r san; do [ -n "$san" ] || continue [[ "$seen" == *" $san "* ]] && continue seen+="$san " kind=$(tls_san_kind "$san") || continue if [ "$kind" = IP ]; then n_ip=$((n_ip + 1)); echo "IP.$n_ip = $san" else n_dns=$((n_dns + 1)); echo "DNS.$n_dns = $san" fi done < <(public_ipv4; tls_sans) } # tls_names_missing: a certificate left in place keeps its names — say which # of the asked-for ones it lacks tls_names_missing() { local names san names=$(openssl x509 -in /etc/gateway/tls/server.crt -noout -ext subjectAltName 2>/dev/null | tail -n +2 | tr ',' '\n' | sed -e 's/^ *//' -e 's/^IP Address://' -e 's/^DNS://') while IFS= read -r san; do [ -n "$san" ] || continue grep -qxF "$san" <<<"$names" || warn "the server certificate does not name $san: reissue it in the Web UI (PKI → Server certificate) to add it" done < <(public_ipv4; tls_sans) } # Idempotent: if /etc/gateway/tls/ca.crt already exists we DO NOT # regenerate it — rotating the CA invalidates every client device's # trust install, so it has to be an explicit operator action. setup_tls() { if [ -f /etc/gateway/tls/ca.crt ] && [ -f /etc/gateway/tls/server.crt ]; then info "TLS certs already present — leaving in place" tls_names_missing return fi log "Generating internal CA + server cert (ECDSA P-256)..." local d=/etc/gateway/tls mkdir -p "$d" cd "$d" # CA: 10-year self-signed root. openssl ecparam -name prime256v1 -genkey -noout -out ca.key openssl req -x509 -new -key ca.key -days 3650 -sha256 \ -subj "/CN=gateway-internal-CA/O=gateway.mesh" \ -out ca.crt # Server key + CSR. openssl ecparam -name prime256v1 -genkey -noout -out server.key cat > server.cnf <<'CNF' [ req ] distinguished_name = req_distinguished_name req_extensions = v3_req prompt = no [ req_distinguished_name ] CN = gateway.mesh O = gateway.mesh [ v3_req ] keyUsage = digitalSignature, keyEncipherment extendedKeyUsage = serverAuth, clientAuth subjectAltName = @alt_names [ alt_names ] DNS.1 = gateway.mesh DNS.2 = *.gateway.mesh DNS.3 = localhost IP.1 = 127.0.0.1 IP.2 = 100.64.0.1 CNF tls_extra_names >> server.cnf openssl req -new -key server.key -out server.csr -config server.cnf # Sign with CA — 825 days, copy SAN through. openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \ -days 825 -sha256 \ -extfile server.cnf -extensions v3_req \ -out server.crt chmod 600 ca.key server.key chmod 644 ca.crt server.crt info "CA fingerprint:" openssl x509 -in ca.crt -noout -fingerprint -sha256 | sed 's/^/ /' cd - >/dev/null } # The DERP relay's certificate, for a node whose DERP mode is its own relay # over TLS on 443 (set on the Mesh page; a fresh install has no relay): a # leaf from the internal CA, whose key is at hand here. Issued once; the # Mesh page reissues it (a new address, expiry). setup_derp_tls() { local map=/etc/headscale/derp-tls.yaml d=/etc/gateway/tls/issued/derp-relay host san [ -f "$map" ] || return 0 grep -q "$map" /etc/headscale/config.yaml 2>/dev/null || return 0 host=$(awk '$1 == "hostname:" {print $2; exit}' "$map") [ -n "$host" ] || return 0 # this node's tailscaled checks the relay against the system roots too if command -v update-ca-certificates >/dev/null 2>&1 && [ -f /etc/gateway/tls/ca.crt ]; then install -m 0644 /etc/gateway/tls/ca.crt /usr/local/share/ca-certificates/gateway-internal-ca.crt update-ca-certificates >/dev/null 2>&1 || warn "update-ca-certificates failed: this node's tailscaled will not trust its own relay" fi # a certificate already there is kept while it chains to this CA and # names the relay's address if [ -f "$d/cert.pem" ] && openssl verify -CAfile /etc/gateway/tls/ca.crt "$d/cert.pem" >/dev/null 2>&1 \ && openssl x509 -in "$d/cert.pem" -noout -checkhost "$host" -checkip "$host" 2>/dev/null | grep -q 'does match'; then return 0 fi if [ ! -f /etc/gateway/tls/ca.key ]; then warn "No CA key at /etc/gateway/tls/ca.key (in the encrypted storage?): issue the DERP relay's certificate from the Mesh page" return 0 fi case "$host" in *:*) san="IP:$host" ;; *[!0-9.]*) san="DNS:$host" ;; *) san="IP:$host" ;; esac log "Issuing the DERP relay certificate for $host (internal CA)..." mkdir -p "$d" ( umask 077; openssl ecparam -name prime256v1 -genkey -noout -out "$d/key.pem" ) openssl req -new -key "$d/key.pem" -subj "/CN=$host/O=gateway.mesh" -out "$d/req.csr" printf 'keyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=%s\n' "$san" > "$d/ext.cnf" openssl x509 -req -in "$d/req.csr" -CA /etc/gateway/tls/ca.crt -CAkey /etc/gateway/tls/ca.key -CAcreateserial \ -days 825 -sha256 -extfile "$d/ext.cnf" -out "$d/cert.pem" rm -f "$d/req.csr" "$d/ext.cnf" cat "$d/cert.pem" /etc/gateway/tls/ca.crt > "$d/bundle.pem" chmod 644 "$d/cert.pem" "$d/bundle.pem" } setup_sd_hardening() { log "Configuring SD card hardening..." # Volatile journald mkdir -p /etc/systemd/journald.conf.d/ cat > /etc/systemd/journald.conf.d/volatile.conf << 'EOF' [Journal] Storage=volatile RuntimeMaxUse=16M RuntimeMaxFileSize=4M EOF systemctl restart systemd-journald 2>/dev/null || true # Disable swap swapoff -a 2>/dev/null || true systemctl disable dphys-swapfile 2>/dev/null || true # Low swappiness echo 'vm.swappiness=1' > /etc/sysctl.d/99-gateway.conf sysctl -p /etc/sysctl.d/99-gateway.conf 2>/dev/null || true # Redirect login accounting to /dev/null ln -sf /dev/null /var/log/wtmp 2>/dev/null || true ln -sf /dev/null /var/log/btmp 2>/dev/null || true ln -sf /dev/null /var/log/lastlog 2>/dev/null || true # Disable cloud-init if present if command -v cloud-init &>/dev/null; then touch /etc/cloud/cloud-init.disabled systemctl disable cloud-init cloud-init-local cloud-config cloud-final 2>/dev/null || true fi } install_binary() { # written beside and renamed over: a gatewayd that runs (a re-run of the # installer) keeps its file — cp onto it failed with "Text file busy" local new=/usr/local/bin/gatewayd.new if [ -n "$BINARY_PATH" ]; then if [[ "$BINARY_PATH" == http* ]]; then log "Downloading gatewayd binary..." wget -q "$BINARY_PATH" -O "$new" else log "Installing gatewayd from $BINARY_PATH..." cp "$BINARY_PATH" "$new" fi chmod 0755 "$new" mv -f "$new" /usr/local/bin/gatewayd systemctl is-active --quiet gatewayd 2>/dev/null && info "gatewayd runs the binary it started with until it restarts (sudo systemctl restart gatewayd)" elif $INSTALL_GO && $INSTALL_BUILD_DEPS; then if [ -d "./cmd/gatewayd" ]; then log "Building gatewayd from source..." export PATH=$PATH:/usr/local/go/bin # in an && list a failed build did not stop the install (set -e) go build -ldflags "-X main.version=$GATEWAY_VERSION" -o "$new" ./cmd/gatewayd/ || err "gatewayd did not build from source" mv -f "$new" /usr/local/bin/gatewayd else warn "Source not found — skipping build (provide --binary or run from repo root)" fi fi if command -v gatewayd &>/dev/null; then log "gatewayd installed: $(gatewayd -version 2>/dev/null || echo 'ok')" fi } setup_systemd() { log "Installing systemd services..." # Byte-identical to deployments/systemd/gatewayd.service (GR-379 #416): # the two copies used to disagree — the installer's lacked Type=notify + # WatchdogSec (so a hung daemon on an installer node was never restarted) # and the repo's lacked StartLimit*/OnFailure/bootcheck. Quoted heredoc: # nothing here is interpolated. cat > /etc/systemd/system/gatewayd.service << 'SVCEOF' [Unit] Description=Gateway Daemon - Programmable Network Gateway After=network-online.target Wants=network-online.target # Emergency post-mortem snapshot on uncontrolled crash. systemd fires # OnFailure when the unit enters the failed state (SIGKILL / OOM / # repeated Restart=always blow-ups); the oneshot snapshots the live DB + # WAL sidecars and config.yaml to a timestamped subdir for forensics. # W3-E storage topology: the live DB is /var/lib/gateway/gateway.db. # OnFailure=, StartLimitIntervalSec= and StartLimitBurst= are [Unit] # directives — in [Service] systemd silently ignores OnFailure and only # accepts the StartLimit pair for backwards compatibility. OnFailure=gatewayd-emergency-backup.service gatewayd-recover.service # GR-080 #109: with bare Restart=always the unit NEVER enters failed state, # so OnFailure= (emergency backup) could never fire. The start limit makes # systemd give up after 5 crashes in 5 minutes -> unit fails -> OnFailure runs. # # Giving up is the point, but giving up FOREVER is not: the kill-switch # forward chain stays installed and dropping, so every client behind this # gateway loses its route out until somebody intervenes. (The node itself # stays reachable — that chain hooks forward, not input.) # gatewayd-recover.service arms one delayed retry so a transient cause heals # without a human. StartLimitIntervalSec=300 StartLimitBurst=5 [Service] Type=notify # WatchdogSec bumped from 30s to 180s. Under real load (12+ policies × several # tunnels × per-domain DNS resolution × redsocks lifecycle + nft/ip rule/route # execs), applyAllRoutingPolicies legitimately takes 60-120s on Pi-class # hardware. Even though the watchdog goroutine is independent of the apply # work, any single stall that exceeds WatchdogSec triggers SIGKILL — and a # SIGKILL while SQLite is mid-write corrupts its B-tree / UNIQUE index, # which is exactly the "Rowid out of order" / duplicate-rowid DB corruption # we keep seeing. Correlation confirmed: every recurring corruption matched # a restart event near an apply cycle. 180s gives enough headroom that # legitimate work never trips it; a truly hung daemon still dies, just slower. WatchdogSec=180 # READY=1 is sent only after tunnel bring-up, mesh start and the first # enforce pass (daemon.go), all of which are synchronous. On a cold boot # with the WAN or DNS still down, WireGuard endpoint resolution alone can # burn tens of seconds per tunnel, and systemd's default 90s start timeout # then SIGKILLs the daemon mid-init — the exact SQLite-corruption trigger # WatchdogSec above is written to avoid. 300s covers the worst observed # cold start with room to spare; a daemon that truly hangs in init still # gets killed (GR-384 #421). TimeoutStartSec=300 # TimeoutStopSec explicit so systemd waits for FinalBackup()'s VACUUM + WAL # checkpoint to complete before SIGKILL'ing. Default 90s was close to the # VACUUM timing on a busy DB, making mid-shutdown SIGKILLs plausible. TimeoutStopSec=120 # Files the daemon creates (gateway.db, backups, ovpn sidecars) hold every # secret the node has: kv_settings carries the JWT secret, managed API keys # and the node bearer. 0077 keeps them root-only even where a code path # forgets an explicit mode (GR-371 #407). UMask=0077 ExecStartPre=/usr/local/bin/gateway-pre-start.sh ExecStartPre=/usr/local/bin/killswitch-prestart.sh ExecStart=/usr/local/bin/gatewayd -config /tmp/gateway/config.yaml # Post-start healthcheck: confirm the daemon stays up and answers HTTPS # for 25 seconds before declaring the service healthy. Catches the # "binary starts, runs init, panics 5s in" regression class that a plain # `systemctl is-active` rollback check cannot detect (systemd then loops # Restart=always indefinitely and the operator's WebUI never comes back). # Leading '-': a node that predates scripts/gateway-bootcheck.sh (or any # install path that skipped it) must still start. Without it a missing # file is 203/EXEC and the unit never comes up. ExecStartPost=-/usr/local/bin/gateway-bootcheck.sh # Copy runtime OVPN sidecars + config back to persistent storage on stop # (GR-023). Without this ExecStopPost, configs/creds uploaded through the UI # live only in the tmpfs runtime dir and are lost on the next reboot — the # ExecStartPre restore has no matching save. ExecStopPost=/bin/bash -c "mkdir -p /var/lib/gateway/ovpn; cp /tmp/gateway/config.yaml /var/lib/gateway/config.yaml 2>/dev/null; cp /tmp/gateway/ovpn/*.ovpn /var/lib/gateway/ovpn/ 2>/dev/null; cp /tmp/gateway/ovpn/*.auth /var/lib/gateway/ovpn/ 2>/dev/null; cp /tmp/gateway/ovpn/*.bind /var/lib/gateway/ovpn/ 2>/dev/null; cp /tmp/gateway/ovpn/*.defgw /var/lib/gateway/ovpn/ 2>/dev/null; cp /tmp/gateway/ovpn/*.autoconnect /var/lib/gateway/ovpn/ 2>/dev/null; cp /tmp/gateway/ovpn/*.devname /var/lib/gateway/ovpn/ 2>/dev/null; true" Restart=always RestartSec=5 # Resource limits LimitNOFILE=65536 LimitNPROC=512 # No core dumps: gatewayd holds the JWT secret, admin password hash, bridge PSKs # and config bearer secrets in memory — a crash core file would write them to # the SD card in cleartext (GR-025). LimitCORE=0 # Logging StandardOutput=journal StandardError=journal SyslogIdentifier=gatewayd [Install] WantedBy=multi-user.target SVCEOF # Emergency post-mortem backup unit. Triggered ONLY by gatewayd's # OnFailure= above; never enabled directly. Best-effort: any cp # failure goes to journal but the unit still completes so a # subsequent Restart=always can fire without being blocked by a # failed dependency. cat > /etc/systemd/system/gatewayd-emergency-backup.service << 'EMGEOF' [Unit] Description=Gateway emergency post-mortem backup DefaultDependencies=no Conflicts=shutdown.target Before=shutdown.target [Service] Type=oneshot ExecStart=/usr/local/bin/gatewayd-emergency-backup.sh TimeoutStartSec=20 StandardOutput=journal StandardError=journal SyslogIdentifier=gatewayd-emergency-backup EMGEOF # Delayed recovery after the start limit. gatewayd.service names # this in OnFailure= alongside the post-mortem snapshot: without it # five crashes in five minutes leave the daemon down for good, with # the kill-switch forward chain still dropping every client's # traffic until somebody logs in. cat > /etc/systemd/system/gatewayd-recover.service << 'RECEOF' [Unit] Description=Gateway daemon delayed recovery after the start limit DefaultDependencies=no Conflicts=shutdown.target Before=shutdown.target [Service] Type=oneshot # gatewayd.service pairs Restart=always with StartLimitBurst=5 in 300s so the # unit can actually reach the failed state and fire OnFailure (GR-080). # The cost of that is a gateway which, after five crashes, stays down until a # human intervenes — with the kill-switch forward chain still installed and # dropping, so every client behind it loses its route out. SSH to the node # itself keeps working (the chain hooks forward, not input), but nothing # brings the daemon back on its own. # # So: arm one delayed attempt. reset-failed clears the rate-limit counter and # start tries again ten minutes later. A transient cause — WAN down at boot, # a disk that had not settled, a peer that was unreachable — heals by itself; # a permanent one retries five times per ten minutes, which is slow enough to # be harmless and still fires the post-mortem snapshot each round. ExecStart=/usr/bin/systemd-run --on-active=10min --unit=gatewayd-recover-attempt \ --description="Delayed gatewayd restart after the start limit" \ /bin/sh -c "systemctl reset-failed gatewayd.service; systemctl start gatewayd.service" TimeoutStartSec=20 StandardOutput=journal StandardError=journal SyslogIdentifier=gatewayd-recover RECEOF cat > /usr/local/bin/gatewayd-emergency-backup.sh << 'EMGSHEOF' #!/bin/bash # gatewayd-emergency-backup.sh — capture the live DB + WAL + config # into /emergency-/ when gatewayd.service # crashes uncontrolledly. W3-E storage topology: the live DB is # /var/lib/gateway/gateway.db (tmpfs-DB design abandoned) — before this # fix the loop only listed /tmp/gateway/gateway.db*, which doesn't # exist on current installs, so emergency snapshots silently missed # the database entirely. /tmp paths stay in the loop for any legacy # install still running a tmpfs db_path. # # Canonical copy. scripts/install-gateway.sh embeds this file verbatim and # scripts/deploy-pi.sh uploads it; they must not drift (GR-378). set -u ts=$(date -u +%Y%m%d-%H%M%S) # With the encrypted storage set up (Settings -> Encrypted Storage) the # snapshots go into the vault while it is unlocked and are skipped while it # is locked: written beside it they would put the database back on the card # in plaintext. root=/var/lib/gateway/backup if [ -e /opt/gateway/vault.img ] || [ -d /var/lib/gateway/vault ]; then if mountpoint -q /var/lib/gateway/vault; then root=/var/lib/gateway/vault/backup else logger -t gatewayd-emergency-backup "encrypted storage closed or missing - no snapshot" exit 0 fi fi dest="${root}/emergency-${ts}" mkdir -p "${dest}" || { logger -t gatewayd-emergency-backup "mkdir ${dest} failed"; exit 0; } chmod 0700 "${dest}" 2>/dev/null || true copied=0 for f in /var/lib/gateway/gateway.db /var/lib/gateway/gateway.db-wal /var/lib/gateway/gateway.db-shm /tmp/gateway/gateway.db /tmp/gateway/gateway.db-wal /tmp/gateway/gateway.db-shm /tmp/gateway/config.yaml; do if [ -f "${f}" ]; then if cp -a "${f}" "${dest}/" 2>/dev/null; then copied=$((copied + 1)) else logger -t gatewayd-emergency-backup "cp ${f} failed" fi fi done # config.yaml holds bearer secrets — tighten to root-only at rest even # if cp -a inherited a looser source mode. [ -f "${dest}/config.yaml" ] && chmod 0600 "${dest}/config.yaml" 2>/dev/null # Keep the last 10 and no more. Nothing ever pruned these, and a node in a # genuine crash loop writes one snapshot per failure — on a 16 GB SD card # behind a daemon that cannot start, unbounded post-mortems fill the disk # and turn a recoverable fault into an unrecoverable one. The newest # snapshots are the ones that explain the crash; the tenth-oldest does not. ls -1dt "${root}"/emergency-* 2>/dev/null | tail -n +11 | while IFS= read -r old; do rm -rf -- "${old}" 2>/dev/null && logger -t gatewayd-emergency-backup "pruned ${old}" done logger -t gatewayd-emergency-backup "snapshot ${dest} files=${copied}" exit 0 EMGSHEOF chmod +x /usr/local/bin/gatewayd-emergency-backup.sh # Install boot-stability healthcheck script. Probes HTTPS for 25s # post-start; if the daemon either dies or stops answering /api/v1/ # auth/status, surface a journald error so the operator (or an # external monitor) sees the failed boot. Exit non-zero so systemd # marks the boot as failed and Restart=always picks up the loop — # this surfaces in `systemctl status` instead of the silent restart # spiral the pre-fix install left behind. # Same content as scripts/gateway-bootcheck.sh in the repo (GR-379 #416). cat > /usr/local/bin/gateway-bootcheck.sh << 'BCKEOF' #!/bin/bash # gateway-bootcheck.sh — verify gatewayd stays up + reachable for 25s. deadline=$(($(date +%s) + 25)) while [ "$(date +%s)" -lt "$deadline" ]; do # ExecStartPost runs while the unit is still "activating" (systemd marks # it active only after every ExecStartPost returns), so `is-active` was # false on the very first iteration and this script exited 1 immediately # — it has never actually probed anything. Fail only on the states that # really mean the daemon is gone (GR-379 #416). BC_STATE=$(systemctl show gatewayd -p ActiveState --value 2>/dev/null) case "$BC_STATE" in failed|inactive|deactivating) logger -t gateway-bootcheck "gatewayd is $BC_STATE during the 25s post-start window" exit 1 ;; esac # GR-079 #108: derive the port from the live config and try BOTH schemes # — a non-default --port or TLS-disabled install made the hardcoded # https://:8080 probe fail forever, flapping the unit via ExecStartPost. # Tolerate quoting: `api_addr: "0.0.0.0:8080"` and `api_addr: :8080` # both have to yield 8080. Anchoring on a trailing digit missed every # quoted value, which is how config.yaml is usually written. BC_PORT=$(grep -E "^[[:space:]]*api_addr:" /tmp/gateway/config.yaml 2>/dev/null | head -n1 | tr -d "\"'[:space:]" | sed -nE 's/.*:([0-9]+)$/\1/p') case "$BC_PORT" in ''|*[!0-9]*) BC_PORT=8080 ;; esac for BC_SCHEME in https http; do if curl -sk -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 3 \ "$BC_SCHEME://127.0.0.1:$BC_PORT/api/v1/auth/status" 2>/dev/null | grep -q '^200$'; then logger -t gateway-bootcheck "gatewayd healthy ($BC_SCHEME:$BC_PORT) at $(date -Is)" exit 0 fi done sleep 2 done logger -t gateway-bootcheck "gatewayd did not answer HTTPS within 25s post-start" exit 1 BCKEOF chmod +x /usr/local/bin/gateway-bootcheck.sh # Pre-start script, verbatim from scripts/gateway-pre-start.sh # (GR-378 #415). The old inline twin copied the live DB into tmpfs # on every boot (GR-269 reversed), skipped the integrity_check → # REINDEX → .recover ladder, never purged stale prio-100 rules and # missed the ovpn certs/ subdirectory. cat > /usr/local/bin/gateway-pre-start.sh << 'PREEOF' #!/bin/bash # update guard (docs/plans/server-management.md 7.6): while an update of # gatewayd is open, its guard runs first; it never fails the start if [ -s /var/lib/gateway/update/active ]; then gid=$(head -c 64 /var/lib/gateway/update/active | tr -cd '0-9a-f-') [ -n "$gid" ] && [ -f "/var/lib/gateway/update/$gid/guard.sh" ] && /bin/sh "/var/lib/gateway/update/$gid/guard.sh" || true fi # gateway-pre-start.sh — restore daemon state from persistent SD storage # to volatile tmpfs working directory before the daemon starts. # # IMPORTANT: This script must NOT use `set -e` because we want partial # restores to succeed even if some files are missing (first boot, etc.). # Critical errors are logged to stderr (captured by systemd journal). mkdir -p /tmp/gateway /tmp/gateway/ovpn # --- DB restore with integrity check and non-destructive auto-repair --- # The previous behavior was "integrity_check != ok" → move aside → # daemon starts fresh. That cost the operator their policies/tunnels/ # proxies/bridges on every index-level corruption, which is the most # common failure mode (SD cards with timing glitches under load). # # Recovery ladder: # 1. integrity_check passes → copy as-is. # 2. integrity_check fails but errors are "wrong # of entries in # index" / "row ... missing from index" → REINDEX then re-check. # 3. Still corrupt → fall back to `.recover` into a new DB, which # salvages every readable row even from deeply corrupt pages. # 4. All the above failed → move aside with a loud log (unchanged). db_status() { sqlite3 "$1" 'PRAGMA integrity_check;' 2>/dev/null | head -1 } # keep_newest_copies : the newest 3 recovery copies of one kind # stay. Each recovery event added a full DB copy and nothing removed any, # which fills /var exactly while the storage is failing. keep_newest_copies() { ls -1t "$1"* 2>/dev/null | tail -n +4 | while IFS= read -r f; do rm -f -- "$f"; done } db_is_index_only() { # Returns 0 if every line of integrity_check output looks like an # index-only error (safe to REINDEX). local out out=$(sqlite3 "$1" 'PRAGMA integrity_check;' 2>/dev/null) || return 1 echo "$out" | grep -qE '^(ok|row [0-9]+ missing from index|wrong # of entries in index)' || return 1 ! echo "$out" | grep -qvE '^(ok|row [0-9]+ missing from index|wrong # of entries in index)' } restore_db() { local src=$1 # The live DB is cfg.Store.DBPath under /var/lib/gateway (W3-E); nothing # is copied to tmpfs any more (GR-269) — only the integrity ladder runs # here, in place. if ! command -v sqlite3 >/dev/null 2>&1; then return 0 fi if [ "$(db_status "$src")" = "ok" ]; then return 0 fi if db_is_index_only "$src"; then echo "PRE-START INFO: DB has index-level corruption, running REINDEX..." >&2 cp "$src" "/var/lib/gateway/gateway.db.prerepair.$(date +%s)" 2>/dev/null keep_newest_copies /var/lib/gateway/gateway.db.prerepair. if sqlite3 "$src" 'REINDEX;' 2>/dev/null && [ "$(db_status "$src")" = "ok" ]; then echo "PRE-START INFO: REINDEX repaired the DB, data preserved." >&2 return 0 fi fi # Last resort: .recover produces a fresh DB from every readable row. echo "PRE-START INFO: integrity_check failed past REINDEX, trying .recover ..." >&2 local tmp=/tmp/gateway/gateway.db.recovering mkdir -p /tmp/gateway rm -f "$tmp" if sqlite3 "$src" '.recover' 2>/dev/null | sqlite3 "$tmp" 2>/dev/null \ && [ "$(db_status "$tmp")" = "ok" ]; then mv "$src" "/var/lib/gateway/gateway.db.corrupt.$(date +%s)" 2>/dev/null keep_newest_copies /var/lib/gateway/gateway.db.corrupt. mv "$tmp" "$src" 2>/dev/null echo "PRE-START INFO: .recover rebuilt the DB from salvageable rows." >&2 return 0 fi rm -f "$tmp" # Before accepting a fresh start, try to salvage the admin credentials # and JWT secret. .recover drops some keys when the auto-index is # non-unique (duplicate INSERT OR IGNORE in its output), so we do direct # key-scoped SELECTs — those can succeed even when index-wide scans fail. # Without this, every DB-corruption recovery logged the operator out of # their own gateway and forced the "create admin" onboarding form, which # is the symptom users kept hitting after SD timing events. local salvage=/tmp/gateway/gateway.db.salvage-creds rm -f "$salvage" local admin_user admin_hash jwt admin_user=$(sqlite3 "$src" "SELECT value FROM kv_settings WHERE key='admin_username'" 2>/dev/null) admin_hash=$(sqlite3 "$src" "SELECT value FROM kv_settings WHERE key='admin_password_hash'" 2>/dev/null) jwt=$(sqlite3 "$src" "SELECT value FROM kv_settings WHERE key='jwt_secret'" 2>/dev/null) # SQL-escape single quotes before interpolating into the INSERT literals # below (GR-026). A value containing a quote would otherwise produce # malformed SQL, the INSERT would fail under `2>/dev/null`, credentials # would silently NOT be salvaged, and the operator would land on the # onboarding form — the exact outcome this block exists to prevent. admin_user=${admin_user//\'/\'\'} admin_hash=${admin_hash//\'/\'\'} jwt=${jwt//\'/\'\'} mv "$src" "/var/lib/gateway/gateway.db.corrupt.$(date +%s)" 2>/dev/null || true keep_newest_copies /var/lib/gateway/gateway.db.corrupt. if [ -n "$admin_user" ] && [ -n "$admin_hash" ]; then # Bootstrap a fresh DB with just the critical credentials so the # operator can log in after the crash recovery. kv_settings is the # only table we touch; schema-creating tables are the daemon's job # on first connection. sqlite3 "$src" </dev/null CREATE TABLE IF NOT EXISTS kv_settings (key TEXT PRIMARY KEY, value TEXT); INSERT OR REPLACE INTO kv_settings(key,value) VALUES ('admin_username', '$admin_user'); INSERT OR REPLACE INTO kv_settings(key,value) VALUES ('admin_password_hash', '$admin_hash'); $( [ -n "$jwt" ] && echo "INSERT OR REPLACE INTO kv_settings(key,value) VALUES ('jwt_secret', '$jwt');" ) EOF echo "PRE-START WARN: DB unrecoverable but admin credentials salvaged — daemon will start with only auth data, all policies/tunnels/bridges lost." >&2 else echo "PRE-START ERROR: DB corruption unrecoverable and admin credentials unreadable; daemon will start with empty DB (onboarding form will appear)." >&2 fi } if [ -f /var/lib/gateway/gateway.db ]; then restore_db /var/lib/gateway/gateway.db fi # --- Config restore --- if [ -f /var/lib/gateway/config.yaml ]; then cp /var/lib/gateway/config.yaml /tmp/gateway/ \ || echo "PRE-START WARN: config.yaml copy failed" >&2 fi # --- OVPN sidecar files: copy directory contents safely (no glob-expansion footguns) --- if [ -d /var/lib/gateway/ovpn ]; then # Use find instead of glob to handle empty directories cleanly find /var/lib/gateway/ovpn -maxdepth 1 -type f \ \( -name '*.ovpn' -o -name '*.auth' -o -name '*.bind' \ -o -name '*.defgw' -o -name '*.autoconnect' -o -name '*.devname' \) \ -exec cp {} /tmp/gateway/ovpn/ \; 2>/dev/null if [ -d /var/lib/gateway/ovpn/certs ]; then cp -r /var/lib/gateway/ovpn/certs /tmp/gateway/ovpn/ 2>/dev/null \ || echo "PRE-START WARN: ovpn certs copy failed" >&2 fi fi # --- Auto-detect the WAN iface from the default route --- # Hardcoding eth1 broke whenever eth1 was unplugged or the user ran # wlan0-as-client / other-iface setups, and the eth1 fallback only ever # matched the reference Pi (GR-385 #422). Missing uplink is fine — the daemon # tolerates a no-WAN state; these rules are best-effort. WAN_IFACE=$(ip -4 route show default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1); exit}}') if [[ -z "$WAN_IFACE" ]]; then # No default route yet. Fall back to the first non-loopback interface # that has an address — the old `eth1` literal only ever matched the # reference Pi (GR-385 #422). WAN_IFACE=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $2}' | grep -v '^lo$' | head -1) fi # Purge our previous priority-100/101 `lookup main` entries first: every # restart used to append another copy, and a WAN change left the old WAN # IP's rule behind (GR-180). Only the `lookup main` entries at these # priorities are ours — the per-tunnel `from lookup ` rules # share priority 100 and must survive. for _ in 1 2 3 4 5 6 7 8; do stale=$(ip rule show 2>/dev/null | awk -F':[[:space:]]+' '($1==100 || $1==101) && /lookup main/ {print $1"|"$2; exit}') [[ -z "$stale" ]] && break pr=${stale%%|*}; sel=${stale#*|}; sel=${sel% lookup main} # shellcheck disable=SC2086 ip rule del $sel lookup main priority "$pr" 2>/dev/null || break done if [[ -n "$WAN_IFACE" ]]; then WAN_SUBNET=$(ip -4 route show dev "$WAN_IFACE" 2>/dev/null | grep -m1 -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+') if [[ "$WAN_SUBNET" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$ ]]; then ip rule add to "$WAN_SUBNET" lookup main priority 100 2>/dev/null fi # No `from … priority 101` rule here any more (GR-306): the # daemon owns the from-rules — applyAllRoutingPolicies installs # `from lookup main priority 51` and deletes exactly this # host rule on its first pass, so it was dead within seconds of boot. fi # --- Pi-only tuning (GR-385 #422) --- # The noatime remount exists to spare an SD card, and rp_filter=0 exists for # AP/VPN forwarding on the reference Pi. On the embedded VPS both were wrong: # the root filesystem got remounted on every start, and reverse-path # filtering was disabled on a PUBLIC interface. Gate them on actually being # a Raspberry Pi. is_raspberry_pi() { grep -qi "raspberry pi" /proc/device-tree/model 2>/dev/null && return 0 grep -qi "raspberry pi" /sys/firmware/devicetree/base/model 2>/dev/null && return 0 grep -qi "^Model.*Raspberry Pi" /proc/cpuinfo 2>/dev/null && return 0 return 1 } if is_raspberry_pi; then # --- Remount root with noatime to reduce SD writes --- mount -o remount,noatime / 2>/dev/null # --- Disable rp_filter for AP/VPN forwarding --- sysctl -w net.ipv4.conf.all.rp_filter=0 > /dev/null 2>&1 sysctl -w net.ipv4.conf.default.rp_filter=0 > /dev/null 2>&1 fi # Always exit success — partial state is acceptable; daemon handles missing data exit 0 PREEOF chmod +x /usr/local/bin/gateway-pre-start.sh # Kill-switch pre-start, verbatim from scripts/killswitch-prestart.sh # (GR-378 #415). The previous fallback stub returned early whenever # /var/lib/gateway/killswitch.state existed, so the forwarding lines # the installer appended AFTER it never ran on any boot but the # first — and the stub itself lacked the ks-ipv6-*/ks-tailscale # rules. Nothing is appended to the script any more: it enables # forwarding itself, after the drop table exists. cat > /usr/local/bin/killswitch-prestart.sh << 'KSEOF' #!/bin/bash # killswitch-prestart.sh — Restore kill switch nftables rules before daemon starts. # Called by systemd ExecStartPre to ensure traffic is blocked even if the daemon # takes time to start or crashes during startup. # # The kill switch table uses priority -1 (before the main gateway table) and # defaults to dropping all forwarded non-LAN traffic. Only explicitly allowed # tunnel interfaces can pass traffic. # # IMPORTANT: NOT using `set -e` because we want best-effort rule installation # and don't want a single failure to abort the whole pre-start (which would # then keep the daemon from starting at all). Critical failures are logged # to stderr where systemd-journal will capture them. STATE_FILE="/var/lib/gateway/killswitch.state" # Sanity check: nft must be available, otherwise this script is meaningless. if ! command -v nft >/dev/null 2>&1; then echo "killswitch-prestart: ERROR nft binary not found, kill switch DISABLED" >&2 exit 0 # exit 0 to not block daemon startup fi # Always create the base kill switch table with drop-all policy. # This ensures protection even if no state file exists (first boot). # `2>/dev/null || true` because table/chain may already exist from a prior run. nft add table inet killswitch 2>/dev/null || true nft 'add chain inet killswitch forward { type filter hook forward priority -1 ; policy drop ; }' 2>/dev/null || true nft flush chain inet killswitch forward 2>/dev/null || true # Verify the chain was actually created — if not, the rules below will all fail. if ! nft list chain inet killswitch forward >/dev/null 2>&1; then echo "killswitch-prestart: ERROR failed to create killswitch chain, traffic UNBLOCKED" >&2 exit 0 fi # Base rules: allow established, LAN, and mesh traffic. # These are appended in order; failures here would mean kernel/nft is broken. add_rule() { nft add rule inet killswitch forward "$@" 2>/dev/null \ || echo "killswitch-prestart: WARN failed to add rule: $*" >&2 } add_rule ct state established,related accept comment ks-established add_rule ip saddr 192.168.0.0/16 ip daddr 192.168.0.0/16 accept comment ks-lan-192 add_rule ip saddr 10.0.0.0/8 ip daddr 10.0.0.0/8 accept comment ks-lan-10 add_rule ip saddr 172.16.0.0/12 ip daddr 172.16.0.0/12 accept comment ks-lan-172 add_rule ip saddr 100.64.0.0/10 ip daddr 100.64.0.0/10 accept comment ks-mesh # Same base rules as setupKillSwitchTable in the daemon (GR-181): the mesh # interface carries exit-node and cross-subnet traffic that the ks-mesh # peer-to-peer rule does not cover, and non-link-local IPv6 is REJECTED so # clients fall back to IPv4 at once instead of waiting out a silent drop. add_rule iifname tailscale0 accept comment ks-tailscale add_rule oifname tailscale0 accept comment ks-tailscale add_rule ip6 saddr fe80::/10 ip6 daddr fe80::/10 accept comment ks-ipv6-linklocal add_rule meta nfproto ipv6 ip6 saddr != fe80::/10 reject with icmpv6 type no-route comment ks-ipv6-reject # Restore tunnel allow rules from saved state file. # Only restore rules for interfaces that currently exist on the system. restored=0 if [ -f "$STATE_FILE" ]; then while IFS= read -r line; do # Look for tunnel allow rules: iifname "tun0" accept comment "ks-tun-tun0" if ! echo "$line" | grep -q 'ks-tun-'; then continue fi # Extract interface name from the comment iface=$(echo "$line" | grep -oP 'ks-tun-\K[^"[:space:]]+' | head -1) if [ -z "$iface" ]; then continue fi # Validate interface name: must be alphanumeric, dot, dash, or underscore if ! [[ "$iface" =~ ^[a-zA-Z0-9._-]+$ ]]; then echo "killswitch-prestart: WARN ignoring invalid iface name from state: $iface" >&2 continue fi # Only restore if the interface exists if [ ! -d "/sys/class/net/$iface" ]; then continue fi if echo "$line" | grep -q 'iifname'; then nft add rule inet killswitch forward iifname "$iface" accept comment "ks-tun-$iface" 2>/dev/null && restored=$((restored+1)) elif echo "$line" | grep -q 'oifname'; then nft add rule inet killswitch forward oifname "$iface" accept comment "ks-tun-$iface" 2>/dev/null && restored=$((restored+1)) fi done < "$STATE_FILE" echo "killswitch-prestart: restored $restored tunnel rules from state file" else echo "killswitch-prestart: no state file, starting with drop-all (no tunnels allowed)" fi echo "killswitch-prestart: table active, policy=drop" # GR-163 #184: forwarding is enabled HERE, after the drop table exists — # not in gateway-pre-start / sysctl.d, which ran before any rules were up. # (These lines sat after `exit 0` and never ran — GR-209.) sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null 2>&1 || true exit 0 KSEOF chmod +x /usr/local/bin/killswitch-prestart.sh systemctl daemon-reload } setup_config() { if [ -f /var/lib/gateway/config.yaml ]; then info "Config already exists at /var/lib/gateway/config.yaml" return fi log "Creating default config..." local listen_addr="0.0.0.0:${API_PORT}" local wan_iface lan_iface # `dev` is not always field 5 (metric/proto ordering varies) and the old # `|| echo eth0` only fired when awk itself failed, so the default was # unreachable (GR-251). Read the token after "dev", then default. wan_iface=$(ip -o route show default 2>/dev/null | awk '{for(i=1;i/dev/null); do case "$cand" in eth*|en*) if [ "$cand" != "$wan_iface" ]; then lan_iface="$cand"; break; fi ;; esac done cat > /var/lib/gateway/config.yaml << CFGEOF version: "1" listen: api_addr: "${listen_addr}" store: db_path: "/var/lib/gateway/gateway.db" log: level: "info" format: "json" network: mode: "$([ "$IS_RPI" = true ] && echo "primary" || echo "embedded")" wan_iface: "${wan_iface}" $([ "$IS_RPI" = true ] && [ -n "$lan_iface" ] && echo " lan_iface: \"${lan_iface}\"") dns: listen_addr: "0.0.0.0:53" upstream_servers: - "1.1.1.1" - "8.8.8.8" filtering_enabled: true tls: enabled: true cert_file: /etc/gateway/tls/server.crt key_file: /etc/gateway/tls/server.key auth: enabled: $([ "$AUTH" = on ] && echo true || echo false) CFGEOF # Copy to tmpfs cp /var/lib/gateway/config.yaml /tmp/gateway/config.yaml 2>/dev/null || true } setup_firewall() { # GR-373 #409: forwarding must NOT come up at sysctl-boot time. A # persistent /etc/sysctl.d entry forwards LAN traffic un-NATed and # unfiltered from network-online until gatewayd's ExecStartPre builds # the kill-switch drop table — and forever if the daemon is disabled or # its unit is broken. killswitch-prestart.sh enables forwarding right # after the drop table exists; netplane.Start re-asserts it at runtime. # This also removes the file earlier installer runs left behind. log "Removing boot-time IP-forwarding overrides (forwarding is enabled after the kill-switch table)..." rm -f /etc/sysctl.d/99-gateway-forward.conf local stale stale=$(grep -rls '^[[:space:]]*net\.ipv4\.ip_forward[[:space:]]*=[[:space:]]*1' /etc/sysctl.d/ 2>/dev/null || true) if [ -n "$stale" ]; then warn "ip_forward is still set at boot by: $stale" warn "Remove those lines — they re-open the pre-kill-switch forwarding window (GR-163/GR-373)." fi } # ── Summary ── show_summary() { echo "" echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}" echo -e "${GREEN}║ Installation Complete! ║${NC}" echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}" echo "" echo " Profile: ${PROFILE:-custom}" echo " Arch: ${ARCH}" echo "" echo " Installed:" echo " ✓ nftables, iptables, iproute2, conntrack, wireguard-tools, openvpn, dhcpcd" echo " ✓ tcpdump, ethtool, cryptsetup, openssl, openssh-client, sqlite3, python3" command -v gatewayd &>/dev/null && echo " ✓ gatewayd $(gatewayd -version 2>&1 | head -1)" $INSTALL_WIFI && echo " ✓ hostapd, dnsmasq, wpa_supplicant" $INSTALL_BLUETOOTH && echo " ✓ bluez (Bluetooth PAN/NAP)" $INSTALL_MESH && echo " ✓ Tailscale, Headscale" $INSTALL_REDSOCKS && echo " ✓ redsocks" $INSTALL_GO && echo " ✓ Go $(go version 2>/dev/null | grep -oP 'go[\d.]+' || echo '?')" $INSTALL_GITEA && echo " ✓ Gitea" $INSTALL_OLLAMA && echo " ✓ Ollama" $SD_HARDENING && echo " ✓ SD card hardening" echo "" echo " Config: /var/lib/gateway/config.yaml" echo " Data: /var/lib/gateway/" echo " Secrets: /var/lib/gateway/secrets/" echo "" if command -v gatewayd &>/dev/null; then echo " Start gateway:" echo " sudo systemctl start gatewayd" echo "" local ip ip=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'src \K\S+' || hostname -I | awk '{print $1}') echo " Web UI: http://${ip}:${API_PORT}" # The first admin is created in the web UI only with this one-time # token (empty once an admin exists). timeout: a binary older than the # command would otherwise try to start a second daemon. local token token=$(timeout 15 gatewayd setup-token --config /var/lib/gateway/config.yaml 2>/dev/null || true) if [ -n "$token" ]; then echo "" echo " First sign-in: open the Web UI and create the admin account" echo " with this one-time setup token (show it again: sudo gatewayd setup-token):" echo -e " ${GREEN}${token}${NC}" fi else echo " Next: install gatewayd binary, then:" echo " sudo systemctl start gatewayd" fi echo "" } # ══════════════════════════════════════════════════ # Main # ══════════════════════════════════════════════════ # --refresh (install.sh GATEWAY_REFRESH=1, plan 7.5): the unit and the helper # scripts as this release has them — no apt, no config.yaml, no restart; # they take effect at gatewayd's next start if $REFRESH; then setup_systemd log "gatewayd unit and helper scripts refreshed; gatewayd keeps running and starts with them next time" exit 0 fi show_banner # Profile selection if [ -n "$PROFILE" ]; then apply_profile "$PROFILE" log "Using profile: $PROFILE" else choose_profile fi # Binary selection (if not provided via CLI) choose_binary # the admin's password, the API token and the login body live in 0600 files # only, gone at exit; an install that stops after making the admin with a # generated password keeps that password in the summary file — it was the # only copy, and the admin account stays ADMIN_PW_TMP=$(mktemp); API_HDR=$(mktemp); API_BODY=$(mktemp); SERVER_KEY=""; ADMIN_CREATED="" chmod 600 "$ADMIN_PW_TMP" "$API_HDR" "$API_BODY" on_exit() { local rc=$? if [ "$rc" != 0 ] && [ "$ADMIN_CREATED" = 1 ] && [ "$ADMIN_MODE" = generate ] && [ -s "$ADMIN_PW_TMP" ]; then ( umask 077; printf 'Gateway install summary — %s — the install stopped early (exit %s)\nAdmin user: admin\nAdmin password: %s\n' \ "$(hostname)" "$rc" "$(cat "$ADMIN_PW_TMP")" > "$INSTALL_SUMMARY" ) && echo "The install stopped: the admin's generated password is kept in $INSTALL_SUMMARY (0600)" >&2 fi rm -f "$ADMIN_PW_TMP" "$API_HDR" "$API_BODY" } trap on_exit EXIT choose_access echo "" log "Starting installation (profile: ${PROFILE:-custom}, arch: ${ARCH})..." echo "" # ── Execute installation steps ── install_base_packages setup_directories setup_firewall $INSTALL_WIFI && install_wifi_packages $INSTALL_BLUETOOTH && install_bluetooth_packages $INSTALL_REDSOCKS && install_redsocks $INSTALL_GO && install_go $INSTALL_MESH && install_mesh $INSTALL_GITEA && install_gitea $INSTALL_OLLAMA && install_ollama $SD_HARDENING && setup_sd_hardening install_binary setup_tls $INSTALL_MESH && setup_derp_tls setup_systemd setup_config [ "$AUTH" = on ] && create_admin # ── Enable and optionally start ── systemctl enable gatewayd 2>/dev/null || true if command -v gatewayd &>/dev/null; then if $NON_INTERACTIVE || yesno "Start gateway now?" "y"; then log "Starting gatewayd..." # a unit that does not come up is told below: under set -e its exit # code ended the install before the summary systemctl start gatewayd || true sleep 3 if systemctl is-active gatewayd &>/dev/null; then log "Gateway is running!" else warn "Gateway failed to start — check: journalctl -u gatewayd -n 20" fi fi fi if systemctl is-active --quiet gatewayd 2>/dev/null; then configure_after_start elif [ "$SERVER_MGMT" = on ] || [ "$UPDATE_POLICY" != notify ]; then warn "gatewayd is not running: turn server management on and set the update policy in the Web UI once it is" fi show_summary install_summary