#!/usr/bin/env bash # Cloudverg agent. Joins this machine to a VergMesh network and keeps it in step with the console. # # What it does, and nothing else: # - makes a WireGuard key pair on this machine. The private key never leaves it. # - asks the console every 30 seconds which peers, routes and firewall rules this node should have. # - applies them to one interface (verg0), one nftables table (inet verg), and routes in its own routing table # (7710) with two routing rules, so nothing in the machine's main routing table changes. # - reports tunnel health: handshake times, byte counts and ping times to the other nodes. # - runs measurements the console asks for from a fixed list: ping, mtu, trace and iperf3. # The console cannot send any other command to this machine. # If the console cannot be reached, the tunnels that are up stay up. # # Usage: verg-agent enroll --token TOKEN [--name NAME] | run | sync | status | reset | uninstall | version set -euo pipefail umask 077 VERSION="1.0.0" API="${VERG_API:-https://api.cloudverg.com}" DIR="${VERG_DIR:-/etc/verg}" RUN="${VERG_RUN:-/run/verg}" IFACE="${VERG_IFACE:-verg0}" RT_PROTO=186 # Mesh routes live in their own table. WireGuard marks its own packets, and marked packets skip that table, so the # tunnel's encrypted traffic always leaves by the normal routes, even when a mesh route covers a peer's address. # Routes the machine already has (its own LANs, its cloud network) always win over mesh routes. RT_TABLE="${VERG_TABLE:-7710}" FWMARK="${VERG_FWMARK:-0x7710}" RULE_MAIN=5110 RULE_MESH=5120 UNIT=/etc/systemd/system/verg-agent.service BIN=/usr/local/sbin/verg-agent say() { printf 'verg: %s\n' "$*" >&2; } die() { say "$*"; exit 1; } has() { command -v "$1" >/dev/null 2>&1; } need_root() { [ "$(id -u)" = 0 ] || die "run this as root (use sudo)"; } is_ip() { [[ "${1:-}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; } is_cidr() { [[ "${1:-}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$ ]]; } is_int() { [[ "${1:-}" =~ ^[0-9]{1,6}$ ]]; } # The value of key=value in the head of a message (before the first #section). head_val() { awk -v k="$1" '/^#[a-z]+$/{exit} index($0, k "=") == 1 {print substr($0, length(k) + 2); exit}' "$2"; } # The lines of one #section. A marker is "#name" alone on a line; "# text" inside a section is an ordinary line. section() { awk -v s="#$1" '$0 == s {on = 1; next} /^#[a-z]+$/ {on = 0} on' "$2"; } os_name() { ( . /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-Linux}" ) || printf 'Linux'; } load_conf() { [ -f "$DIR/agent.conf" ] || die "this machine has not joined a network yet. Run: verg-agent enroll --token TOKEN" NODE_ID="$(head_val node_id "$DIR/agent.conf")" SECRET="$(head_val secret "$DIR/agent.conf")" local api; api="$(head_val api "$DIR/agent.conf")" [ -n "$api" ] && [ -z "${VERG_API:-}" ] && API="$api" [[ "$SECRET" =~ ^vgn_[A-Za-z0-9_-]{20,60}$ ]] || die "the file $DIR/agent.conf is damaged. Run: verg-agent reset, then enroll again" } # True when another firewall on this machine would drop what this node forwards (ufw and Docker both do). forward_dropped() { has iptables || return 1 [ "$(iptables -S FORWARD 2>/dev/null | head -n1)" = "-P FORWARD DROP" ] || return 1 iptables -S FORWARD 2>/dev/null | grep -q -- "$IFACE" && return 1 return 0 } collect() { local applied="" [ -f "$RUN/applied" ] && applied="$(cat "$RUN/applied")" printf 'applied=%s\nagent=%s\nhostname=%s\nkernel=%s\nos=%s\n' "$applied" "$VERSION" "$(hostname 2>/dev/null || echo unknown)" "$(uname -r)" "$(os_name)" printf 'load=%s\n' "$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)" printf 'nft=%s\n' "$(has nft && echo 1 || echo 0)" printf 'iperf=%s\n' "$(has iperf3 && echo 1 || echo 0)" printf 'fwd=%s\n' "$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo 0)" printf 'fwdrop=%s\n' "$(forward_dropped && echo 1 || echo 0)" echo '#peers' # The first line of the dump holds this machine's private key, so it is cut off here and never sent. wg show "$IFACE" dump 2>/dev/null | tail -n +2 | awk -F'\t' 'NF >= 8 {print $1 "\t" $3 "\t" $5 "\t" $6 "\t" $7}' || true echo '#pings' [ -f "$RUN/pings" ] && cat "$RUN/pings" echo '#lans' ip -4 route show table main scope link 2>/dev/null | awk -v me="$IFACE" '$1 ~ /\// && $0 !~ ("dev " me "( |$)") && $0 !~ /dev (docker|br-|veth|virbr|cni|flannel|cali|tailscale|wg|lo|zt|tun|tap)/ {print $1}' | sort -u | head -n 16 || true echo '#counters' if has nft; then nft list table inet verg 2>/dev/null | sed -n 's/.*counter packets \([0-9]*\) bytes \([0-9]*\).*comment "r:\([A-Za-z0-9_-]*\)".*/\3 \1 \2/p' || true; fi echo '#results' [ -f "$RUN/results" ] && cat "$RUN/results" echo '#end' } rules_on() { ip -4 rule show priority "$RULE_MAIN" 2>/dev/null | grep -q . || ip -4 rule add priority "$RULE_MAIN" lookup main suppress_prefixlength 0 ip -4 rule show priority "$RULE_MESH" 2>/dev/null | grep -q . || ip -4 rule add priority "$RULE_MESH" not fwmark "$FWMARK" lookup "$RT_TABLE" } rules_off() { while ip -4 rule del priority "$RULE_MESH" 2>/dev/null; do :; done while ip -4 rule del priority "$RULE_MAIN" 2>/dev/null; do :; done } teardown() { ip link del "$IFACE" 2>/dev/null || true ip -4 route flush table "$RT_TABLE" proto "$RT_PROTO" 2>/dev/null || true rules_off if has nft; then nft delete table inet verg 2>/dev/null || true; fi rm -f "$RUN/applied" "$RUN/pings" } apply() { local f="$1" version address mtu forward version="$(head_val version "$f")"; address="$(head_val address "$f")"; mtu="$(head_val mtu "$f")"; forward="$(head_val forward "$f")" is_cidr "$address" || { say "the console sent an address this agent does not understand; nothing changed"; return 1; } is_int "$mtu" && [ "$mtu" -ge 1280 ] && [ "$mtu" -le 9000 ] || { say "the console sent an MTU this agent does not understand; nothing changed"; return 1; } if [ -n "$version" ] && [ "$version" = "$(cat "$RUN/applied" 2>/dev/null || true)" ] && ip link show "$IFACE" >/dev/null 2>&1; then return 0; fi if ! ip link show "$IFACE" >/dev/null 2>&1; then ip link add "$IFACE" type wireguard || { say "this kernel has no WireGuard support (needs Linux 5.6 or the wireguard module)"; return 1; } fi # The console sends peers and the port. The private key is added here, from this machine's own file. section wg "$f" > "$RUN/wg.peers" { echo '[Interface]'; printf 'PrivateKey = '; cat "$DIR/private.key"; printf 'FwMark = %s\n' "$FWMARK"; tail -n +2 "$RUN/wg.peers"; } > "$RUN/wg.full" wg syncconf "$IFACE" "$RUN/wg.full" || { rm -f "$RUN/wg.full"; say "WireGuard refused the configuration; the previous one stays"; return 1; } rm -f "$RUN/wg.full" ip -4 addr replace "$address" dev "$IFACE" local a for a in $(ip -4 -o addr show dev "$IFACE" | awk '{print $4}'); do [ "$a" = "$address" ] || ip -4 addr del "$a" dev "$IFACE" 2>/dev/null || true; done ip link set dev "$IFACE" mtu "$mtu" up local want have r want="$(section routes "$f" | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$' | sort -u || true)" # "ip route" prints a single address without its /32, so add it back before comparing with what the console sent. have="$(ip -4 route show table "$RT_TABLE" proto "$RT_PROTO" 2>/dev/null | awk '{print ($1 ~ /\//) ? $1 : $1 "/32"}' | sort -u || true)" for r in $want; do ip -4 route replace "$r" dev "$IFACE" table "$RT_TABLE" proto "$RT_PROTO" || say "could not add the route $r"; done for r in $have; do printf '%s\n' "$want" | grep -qxF "$r" || ip -4 route del "$r" table "$RT_TABLE" proto "$RT_PROTO" 2>/dev/null || true; done rules_on if [ "$forward" = 1 ]; then sysctl -qw net.ipv4.ip_forward=1 2>/dev/null || echo 1 > /proc/sys/net/ipv4/ip_forward || true; fi if has nft; then section nft "$f" > "$RUN/nft" if [ -s "$RUN/nft" ]; then # Only the table this agent owns may be named, and nothing may be included or flushed. if grep -Eq '^[[:space:]]*(include|flush)[[:space:]]' "$RUN/nft" || grep -E '^[[:space:]]*(delete[[:space:]]+)?table[[:space:]]' "$RUN/nft" | grep -Evq '^[[:space:]]*(delete[[:space:]]+)?table inet verg([[:space:]]*\{)?[[:space:]]*$'; then say "the console sent firewall rules outside the verg table; they were not applied" elif nft -c -f "$RUN/nft" 2>"$RUN/nft.err"; then nft -f "$RUN/nft" else say "nftables refused the rules: $(head -n1 "$RUN/nft.err")"; fi else nft delete table inet verg 2>/dev/null || true; fi fi printf '%s' "$version" > "$RUN/applied" say "applied configuration $version ($(printf '%s\n' "$want" | grep -c . || true) routes)" } ping_line() { local out loss avg out="$(ping -n -q -c 3 -i 0.3 -W 1 "$1" 2>/dev/null || true)" loss="$(printf '%s\n' "$out" | sed -n 's/.* \([0-9.]*\)% packet loss.*/\1/p' | head -n1)" avg="$(printf '%s\n' "$out" | sed -n 's#.*= [0-9.]*/\([0-9.]*\)/.*#\1#p' | head -n1)" printf '%s %s %s\n' "$1" "${avg:--}" "${loss:-100}" } measure() { local ip pids=() : > "$RUN/pings.new" while read -r ip; do is_ip "$ip" || continue ( ping_line "$ip" >> "$RUN/pings.new" ) & pids+=("$!") done < <(section pingto "$1") [ "${#pids[@]}" -gt 0 ] && wait "${pids[@]}" 2>/dev/null || true mv "$RUN/pings.new" "$RUN/pings" } result() { printf '%s\n' "$*" >> "$RUN/results"; } task_ping() { local out loss stats out="$(ping -n -q -c "$3" -i 0.2 -W 2 "$2" 2>/dev/null || true)" loss="$(printf '%s\n' "$out" | sed -n 's/.* \([0-9.]*\)% packet loss.*/\1/p' | head -n1)" stats="$(printf '%s\n' "$out" | sed -n 's#.*= \([0-9.]*\)/\([0-9.]*\)/\([0-9.]*\)/\{0,1\}\([0-9.]*\).*#min=\1;avg=\2;max=\3;jitter=\4#p' | head -n1)" if [ -n "$stats" ]; then result "$1 ok loss=${loss:-0};$stats"; else result "$1 fail loss=${loss:-100};error=no reply"; fi } task_mtu() { local lo=1200 hi=1472 mid ping -n -q -c 1 -W 2 -M do -s "$lo" "$2" >/dev/null 2>&1 || { result "$1 fail error=no reply to a 1228 byte packet"; return 0; } if ping -n -q -c 1 -W 2 -M do -s "$hi" "$2" >/dev/null 2>&1; then result "$1 ok path_mtu=$((hi + 28))"; return 0; fi while [ $((hi - lo)) -gt 1 ]; do mid=$(((lo + hi) / 2)) if ping -n -q -c 1 -W 1 -M do -s "$mid" "$2" >/dev/null 2>&1; then lo=$mid; else hi=$mid; fi done result "$1 ok path_mtu=$((lo + 28))" } task_trace() { local hops if has tracepath; then hops="$(tracepath -n -m 16 "$2" 2>/dev/null | awk '$1 ~ /^[0-9]+[:?]$/ && $2 ~ /^[0-9.]+$/ {printf "%s%s", (n++ ? "," : ""), $2}' || true)" elif has traceroute; then hops="$(traceroute -n -m 16 -w 1 -q 1 "$2" 2>/dev/null | awk 'NR > 1 && $2 ~ /^[0-9.]+$/ {printf "%s%s", (n++ ? "," : ""), $2}' || true)" else result "$1 fail error=tracepath is not installed"; return 0; fi if [ -n "$hops" ]; then result "$1 ok hops=$hops"; else result "$1 fail error=no hops answered"; fi } task_iperf_server() { has iperf3 || { result "$1 fail error=iperf3 is not installed"; return 0; } ( timeout "$4" iperf3 -s -1 -B "$2" -p "$3" >/dev/null 2>&1 || true ) & result "$1 ok listening=1" } task_iperf_client() { has iperf3 || { result "$1 fail error=iperf3 is not installed"; return 0; } local out mbps retr out="$(timeout $(($4 + 20)) iperf3 -c "$2" -p "$3" -t "$4" -P "$5" -f m 2>&1 || true)" mbps="$(printf '%s\n' "$out" | awk '/receiver/ {for (i = 1; i <= NF; i++) if ($i == "Mbits/sec") v = $(i - 1); if ($1 == "[SUM]") {s = v}} END {if (s != "") print s; else if (v != "") print v}')" retr="$(printf '%s\n' "$out" | awk '/sender/ {for (i = 1; i <= NF; i++) if ($i == "Mbits/sec") v = $(i + 1); if ($1 == "[SUM]") {s = v}} END {if (s != "") print s; else if (v != "") print v}')" if [ -n "$mbps" ]; then result "$1 ok mbps=$mbps;retr=${retr:-0};streams=$5;secs=$4" else result "$1 fail error=$(printf '%s\n' "$out" | tail -n1 | tr -cd 'A-Za-z0-9 .,:/-' | cut -c1-120)"; fi } run_tasks() { local id verb a b c d while read -r id verb a b c d; do [[ "$id" =~ ^tsk_[a-f0-9]{6,40}$ ]] || continue case "$verb" in ping) if is_ip "$a" && is_int "$b"; then ( task_ping "$id" "$a" "$b" ) & fi ;; mtu) if is_ip "$a"; then ( task_mtu "$id" "$a" ) & fi ;; trace) if is_ip "$a"; then ( task_trace "$id" "$a" ) & fi ;; iperf_server) if is_ip "$a" && is_int "$b" && is_int "$c"; then task_iperf_server "$id" "$a" "$b" "$c"; fi ;; iperf_client) if is_ip "$a" && is_int "$b" && is_int "$c" && is_int "$d"; then ( task_iperf_client "$id" "$a" "$b" "$c" "$d" ) & fi ;; *) result "$id fail error=this agent does not know that measurement" ;; esac done < <(section tasks "$1") } sync_once() { load_conf mkdir -p "$RUN" exec 9>"$RUN/lock" flock -n 9 || { say "another sync is already running"; return 0; } collect > "$RUN/report" local code sent sent="$(wc -l < "$RUN/results" 2>/dev/null || echo 0)" code="$(curl -sS --max-time 25 -o "$RUN/reply" -w '%{http_code}' -X POST -H "Authorization: Bearer $SECRET" -H 'Content-Type: text/plain' --data-binary @"$RUN/report" "$API/agent/v1/sync" 2>"$RUN/curl.err")" || code=000 case "$code" in 200) # Drop only the results that were in the report; a measurement that finished meanwhile goes next time. if [ -f "$RUN/results" ]; then tail -n +"$((sent + 1))" "$RUN/results" > "$RUN/results.new" || true; mv "$RUN/results.new" "$RUN/results"; fi apply "$RUN/reply" || true run_tasks "$RUN/reply" || true measure "$RUN/reply" || true INTERVAL="$(head_val interval "$RUN/reply")"; is_int "${INTERVAL:-}" || INTERVAL=30 return 0 ;; 401|403) say "the console no longer accepts this node's credential (HTTP $code)"; return 3 ;; 410) say "this node was removed or switched off in the console; taking the tunnel down"; teardown; return 4 ;; *) say "the console could not be reached (HTTP $code); the current tunnels stay as they are"; return 1 ;; esac } cmd_run() { need_root INTERVAL=30 local rc while true; do rc=0; sync_once || rc=$? exec 9>&- 2>/dev/null || true case "$rc" in 3|4) sleep 300 ;; *) sleep "$((INTERVAL + RANDOM % 5))" ;; esac done } install_service() { has systemctl && [ -d /run/systemd/system ] || { say "systemd was not found. Start the agent yourself at boot: $BIN run"; return 0; } cat > "$UNIT" </dev/null 2>&1 || say "could not start the service; run: systemctl status verg-agent" systemctl restart verg-agent.service >/dev/null 2>&1 || true } cmd_enroll() { need_root local token="" name="" service=1 while [ $# -gt 0 ]; do case "$1" in --token) token="${2:-}"; shift 2 ;; --name) name="${2:-}"; shift 2 ;; --api) API="${2:-}"; shift 2 ;; --no-service) service=0; shift ;; *) die "unknown option: $1" ;; esac done [[ "$token" =~ ^vgm_[A-Za-z0-9_-]{20,60}$ ]] || die "pass the token from the console: verg-agent enroll --token vgm_..." local t for t in wg ip curl flock; do has "$t" || die "$t is not installed. Install wireguard-tools, iproute2, curl and util-linux, then run this again."; done mkdir -p "$DIR" "$RUN"; chmod 700 "$DIR" [ -s "$DIR/private.key" ] || wg genkey > "$DIR/private.key" chmod 600 "$DIR/private.key" local pub code pub="$(wg pubkey < "$DIR/private.key")" say "keys made on this machine; joining through $API" code="$(curl -sS --max-time 30 -o "$RUN/enroll" -w '%{http_code}' -X POST "$API/agent/v1/enroll" \ --data-urlencode "token=$token" --data-urlencode "public_key=$pub" --data-urlencode "name=$name" \ --data-urlencode "hostname=$(hostname 2>/dev/null || echo unknown)" --data-urlencode "os=$(os_name)" \ --data-urlencode "kernel=$(uname -r)" --data-urlencode "version=$VERSION" 2>"$RUN/curl.err")" || code=000 if [ "$code" != 200 ]; then local msg; msg="$(head_val error "$RUN/enroll" 2>/dev/null || true)" die "could not join (HTTP $code): ${msg:-$(head -n1 "$RUN/curl.err" 2>/dev/null || echo 'no answer from the console')}" fi local node secret nname address network node="$(head_val node_id "$RUN/enroll")"; secret="$(head_val secret "$RUN/enroll")"; nname="$(head_val node_name "$RUN/enroll")" address="$(head_val address "$RUN/enroll")"; network="$(head_val network "$RUN/enroll")" rm -f "$RUN/enroll" [[ "$secret" =~ ^vgn_[A-Za-z0-9_-]{20,60}$ ]] || die "the console's answer was not understood" printf 'node_id=%s\nsecret=%s\napi=%s\n' "$node" "$secret" "$API" > "$DIR/agent.conf" chmod 600 "$DIR/agent.conf" rm -f "$RUN/applied" say "joined network $network as $nname ($address)" if [ "$service" = 1 ]; then install_service; else say "no service installed; run: verg-agent run"; fi sync_once || true say "done. See this node in the console, or run: verg-agent status" } cmd_status() { need_root load_conf printf 'node: %s\nconsole: %s\nagent: %s\ninterface: %s\n' "$NODE_ID" "$API" "$VERSION" "$IFACE" if ip link show "$IFACE" >/dev/null 2>&1; then printf 'address: %s\napplied: %s\n' "$(ip -4 -o addr show dev "$IFACE" | awk '{print $4}' | head -n1)" "$(cat "$RUN/applied" 2>/dev/null || echo none)" wg show "$IFACE" dump | tail -n +2 | awk -F'\t' -v now="$(date +%s)" '{hs = ($5 > 0) ? (now - $5) " s ago" : "never"; printf "peer %s... endpoint %s handshake %s rx %s tx %s\n", substr($1, 1, 10), $3, hs, $6, $7}' else echo "tunnel: down"; fi } cmd_reset() { need_root if has systemctl; then systemctl disable --now verg-agent.service >/dev/null 2>&1 || true; fi mkdir -p "$RUN" teardown rm -f "$DIR/agent.conf" "$DIR/private.key" say "this machine left the network and its key was deleted. Remove the node in the console too." } case "${1:-}" in enroll) shift; cmd_enroll "$@" ;; run) cmd_run ;; sync) need_root; rc=0; sync_once || rc=$?; exit "$rc" ;; status) cmd_status ;; reset) cmd_reset ;; uninstall) cmd_reset; rm -f "$UNIT"; if has systemctl; then systemctl daemon-reload >/dev/null 2>&1 || true; fi; rm -rf "$DIR" "$RUN"; rm -f "$BIN"; say "the agent was removed" ;; version|--version|-v) echo "$VERSION" ;; *) sed -n '2,16p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;; esac