SPB Git

Repository Public

tunnelctl 7.4 KB 126 lines

1#!/usr/bin/env bash2# tunnelctl — MacLustr Tunnel : gestion des pairs WireGuard et des routes Caddy sur la passerelle publique (R9128).3# Usage :4#   tunnelctl peer add <alias> <pubkey>        ajoute/remplace un Mac (IP fixe tirée de /etc/maclustr-tunnel/ipmap)5#   tunnelctl peer rm <alias>6#   tunnelctl peer ls                          pairs + dernier handshake7#   tunnelctl add <domaine> <alias|ip>:<port> [<alias|ip>:<port>…] [--no-tls] [--websocket]8#                                              route publique https://<domaine> → upstream(s) via WireGuard (LB + health si plusieurs)9#   tunnelctl redirect <domaine> <cible>       redirection 308 (ex. apex → www)10#   tunnelctl rm <domaine>11#   tunnelctl ls                               routes publiques12#   tunnelctl status                           wg + caddy + routes13#   tunnelctl json                             même chose en JSON (pour maclustr-agentd)14set -euo pipefail15ETC=/etc/maclustr-tunnel16IPMAP=$ETC/ipmap17PEERS=/etc/wireguard/peers.d18SITES=/etc/caddy/sites19EXTRAS=/etc/caddy/site-extras   # <domaine>.caddy : directives ajoutées dans le bloc du site par `add` (2026-11-19)20WG_IF=wg021PUBLIC_IP=${PUBLIC_IP:-$(cat /etc/maclustr-tunnel/public_ip 2>/dev/null || echo 51.255.75.61)}22[ "$(id -u)" = 0 ] || exec sudo -E "$0" "$@"23mkdir -p "$ETC" "$PEERS" "$SITES"2425die(){ echo "tunnelctl: $*" >&2; exit 1; }26ip_of(){ awk -v a="$1" '$1==a{print $2}' "$IPMAP"; }27alias_of(){ awk -v ip="$1" '$2==ip{print $1}' "$IPMAP"; }28resolve_upstream(){ # alias:port | ip:port  -> ip:port29  local hp=$1 h=${1%%:*} p=${1##*:}30  [ "$h" != "$p" ] || die "upstream « $hp » : format <alias|ip>:<port>"31  if [[ "$h" =~ ^[0-9.]+$ ]]; then echo "$h:$p"; else local ip; ip=$(ip_of "$h"); [ -n "$ip" ] || die "alias inconnu « $h » (voir $IPMAP)"; echo "$ip:$p"; fi32}33wg_sync(){ # reconstruit wg0.conf = [Interface] + peers.d/*.conf puis applique sans couper les tunnels34  local conf=/etc/wireguard/$WG_IF.conf tmp; tmp=$(mktemp)35  awk '/^\[Peer\]/{exit} {print}' "$conf" > "$tmp"36  for f in "$PEERS"/*.conf; do [ -f "$f" ] && { echo; cat "$f"; } >> "$tmp"; done37  install -m 600 "$tmp" "$conf"; rm -f "$tmp"38  wg syncconf "$WG_IF" <(wg-quick strip "$WG_IF")39}40caddy_reload(){ caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null && systemctl reload caddy; }4142cmd=${1:-status}; shift || true43case "$cmd" in44  peer)45    sub=${1:-ls}; shift || true46    case "$sub" in47      add)48        a=${1:?alias}; pk=${2:?pubkey}; ip=$(ip_of "$a"); [ -n "$ip" ] || die "alias « $a » absent de $IPMAP"49        printf "[Peer]\n# %s\nPublicKey = %s\nAllowedIPs = %s/32\n" "$a" "$pk" "$ip" > "$PEERS/$a.conf"50        wg_sync; echo "pair $a → $ip ajouté" ;;51      rm) a=${1:?alias}; rm -f "$PEERS/$a.conf"; wg_sync; echo "pair $a retiré" ;;52      ls)53        wg show "$WG_IF" dump | tail -n +2 | while IFS=$'\t' read -r pk psk ep allowed hs rx tx ka; do54          ip=${allowed%/32}; a=$(alias_of "$ip"); age="jamais"; [ "$hs" != 0 ] && age="$(( $(date +%s) - hs )) s"55          printf "%-8s %-12s %-22s handshake %-10s rx %6.1f Mo tx %6.1f Mo\n" "${a:-?}" "$ip" "${ep:-—}" "$age" "$(echo "$rx/1048576" | bc -l)" "$(echo "$tx/1048576" | bc -l)"56        done ;;57      *) die "peer add|rm|ls" ;;58    esac ;;59  add)60    d=${1:?domaine}; shift; ups=(); tls=1; ws=061    for x in "$@"; do case "$x" in --no-tls) tls=0;; --websocket) ws=1;; *) ups+=("$(resolve_upstream "$x")");; esac; done62    [ ${#ups[@]} -gt 0 ] || die "au moins un upstream"63    {64      [ $tls = 1 ] && echo "$d {" || echo "http://$d {"65      echo "	import maclustr_errors"   # page MacLustr « service indisponible » (502/503/504) avec contact@spboucher.ai66      echo "	encode zstd gzip"67      echo "	log"   # journal d accès → journald (journalctl -u caddy), filtrable par request.host68      if [ -f "$EXTRAS/$d.caddy" ]; then echo "	import $EXTRAS/$d.caddy"; fi   # directives propres au site (optionnel, ex. log_skip)69      echo "	reverse_proxy ${ups[*]} {"70      if [ ${#ups[@]} -gt 1 ]; then71        echo "		lb_policy first"; echo "		lb_try_duration 5s"72        echo "		health_uri /"; echo "		health_interval 10s"; echo "		health_timeout 4s"; echo "		health_status 2xx 3xx 4xx"73      fi74      echo "		header_up X-Forwarded-Proto {scheme}"; echo "		header_up X-Real-IP {remote_host}"75      echo "		transport http {"; echo "			dial_timeout 5s"; echo "			response_header_timeout 300s"; echo "		}"76      echo "	}"77      echo "}"78    } > "$SITES/$d.caddy"79    if caddy_reload; then echo "route https://$d → ${ups[*]} active (TLS Let's Encrypt automatique si le DNS de $d pointe vers $PUBLIC_IP)"; else rm -f "$SITES/$d.caddy"; caddy_reload || true; die "Caddyfile invalide, route annulée"; fi ;;80  redirect) # tunnelctl redirect <domaine-source> <domaine-cible>  (ex. apex → www), 308 permanent, TLS auto81    s=${1:?source}; t=${2:?cible}82    printf "%s {\n\tredir https://%s{uri} permanent\n}\n" "$s" "$t" > "$SITES/$s.caddy"83    if caddy_reload; then echo "redirection https://$s → https://$t active"; else rm -f "$SITES/$s.caddy"; caddy_reload || true; die "Caddyfile invalide, redirection annulée"; fi ;;84  rm) d=${1:?domaine}; rm -f "$SITES/$d.caddy"; caddy_reload; echo "route $d retirée" ;;85  ls)86    for f in "$SITES"/*.caddy; do [ -f "$f" ] || continue; d=$(basename "$f" .caddy); up=$(awk '/reverse_proxy/{ $1=""; sub(/ *\{ *$/,""); print }' "$f" | sed 's/^ *//'); printf "%-36s → %s\n" "$d" "$up"; done ;;87  json) # état machine-lisible (consommé par maclustr-agentd → apps MacLustr)88    GW_NAME=${GW_NAME:-$(hostname -s | tr a-z A-Z)}89    wg show "$WG_IF" dump 2>/dev/null | tail -n +2 > /tmp/.wgdump.$$ || true90    python3 - "$GW_NAME" "$PUBLIC_IP" "$IPMAP" "$SITES" "/tmp/.wgdump.$$" "$(wg show $WG_IF listen-port 2>/dev/null)" "$(systemctl is-active caddy 2>/dev/null)" <<'PY'91import sys, json, glob, os, re, time92name, pub_ip, ipmap, sites, dump, port, caddy = sys.argv[1:8]93alias_of = {}94for line in open(ipmap):95    p = line.split()96    if len(p) >= 2 and not line.startswith('#'): alias_of[p[1]] = p[0]97peers = []98now = int(time.time())99for line in open(dump):100    f = line.rstrip('\n').split('\t')101    if len(f) < 8: continue102    ip = f[3].replace('/32', '')103    hs = int(f[4] or 0)104    peers.append({"alias": alias_of.get(ip, "?"), "ip": ip, "endpoint": f[2] if f[2] != '(none)' else None,105                  "handshakeS": (now - hs) if hs else None, "rxBytes": int(f[5] or 0), "txBytes": int(f[6] or 0)})106routes = []107for fn in sorted(glob.glob(os.path.join(sites, '*.caddy'))):108    dom = os.path.basename(fn)[:-6]; txt = open(fn).read()109    m = re.search(r'redir\s+(\S+)', txt)110    if m:111        routes.append({"domain": dom, "kind": "redirect", "target": m.group(1).replace('{uri}', ''), "upstreams": []})112        continue113    m = re.search(r'reverse_proxy\s+([^{\n]+)', txt)114    ups = m.group(1).split() if m else []115    routes.append({"domain": dom, "kind": "proxy", "upstreams": [{"addr": u, "alias": alias_of.get(u.split(':')[0], None)} for u in ups]})116print(json.dumps({"gateway": name, "ip": pub_ip, "ts": now,117                  "wg": {"listenPort": int(port or 0), "peers": peers},118                  "caddy": {"active": caddy == "active", "routes": routes}}, ensure_ascii=False))119PY120    rm -f /tmp/.wgdump.$$ ;;121  status)122    echo "== WireGuard $WG_IF ($(wg show $WG_IF listen-port 2>/dev/null) udp) — $(ls "$PEERS"/*.conf 2>/dev/null | wc -l) pairs"; "$0" peer ls123    echo; echo "== Caddy : $(systemctl is-active caddy) — $(ls "$SITES"/*.caddy 2>/dev/null | wc -l) routes"; "$0" ls ;;124  *) sed -n '2,12p' "$0"; exit 1 ;;125esac126
Files main
Menu

Theme