interplane.Get Omega
Read in your language

readings-window

aien-dev/readings-window

Brought by drakestapleton

branch main Branches Tags History

readings-window / scripts / exposure-watch.sh

115 lines · 6993 bytes Raw Blame History
1#!/bin/bash
2# exposure-watch: what the house shows on its public IP, scanned from INSIDE the LAN (router hairpin view). Scans ONLY our own public IP.
3# Inside view != internet view: the router answers its own 53/80 and reflects LAN-only forwards (e.g. 9443). Baseline holds the accepted inside view; Ports in optional_tcp may come and go without alarming (the router's own 53/80 flicker in the hairpin view).
4# the real outside view is a separate, occasional check (check-host.net or similar). A change here means "something on the router or LAN moved", not proof of exposure.
5export PATH=/usr/sbin:/usr/bin:/sbin:/bin
6OUT=/var/lib/readings-window/exposure.json
7STATE=/var/lib/exposure-watch
8BASE=/etc/exposure-watch/baseline.json
9# base_list KEY: the port numbers in the baseline's "KEY":[...] list, space-separated with a trailing space.
10# Whitespace anywhere in the file is ignored (a hand-written or pretty-printed baseline must parse the same).
11# Returns 1 when the key is absent, so an unreadable baseline alarms instead of reading as "nothing expected".
12base_list() {
13 [ -r "$BASE" ] || return 1
14 local flat; flat=$(tr -d ' \t\r\n' < "$BASE")
15 case "$flat" in *"\"$1\":["*) ;; *) return 1 ;; esac
16 printf '%s' "$flat" | grep -o "\"$1\":\[[^]]*\]" | grep -o '[0-9]\+' | sort -n | tr '\n' ' '
17}
18if [ "${1-}" = --parse-baseline ]; then # test hook: print the parsed lists of FILE, no scan, no writes
19 BASE=$2; rc=0
20 for k in expected_tcp optional_tcp expected_udp; do v=$(base_list "$k") || { v=MISSING; rc=1; }; echo "$k=$v"; done
21 exit $rc
22fi
23mkdir -p "$STATE" /etc/exposure-watch
24RUNLOG=$STATE/last-run.txt
25log() { echo "$*" >> "$RUNLOG.new"; }
26: > "$RUNLOG.new"
27ts=$(date +%s)
28log "start $(date -u +%FT%TZ)"
29
30# a. public IP
31ip=$(curl -s -m 10 https://api.ipify.org)
32if ! [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
33 ip=""
34 command -v dig >/dev/null && ip=$(dig +short +time=5 +tries=1 myip.opendns.com @resolver1.opendns.com | head -1)
35 [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || ip=""
36fi
37if [ -z "$ip" ]; then
38 log "FAIL could not learn public IP; no result written"
39 mv "$RUNLOG.new" "$RUNLOG"; exit 1
40fi
41
42# baseline (first run creates it from the expected lists)
43if [ ! -s "$BASE" ]; then
44 echo '{"vantage":"lan-hairpin","expected_tcp":[443],"optional_tcp":[53,80],"expected_udp":[],"note":"inside view; readings 9443 is tailnet-only and the control server runs no STUN, so only 443/tcp is expected"}' > "$BASE"
45 log "baseline created"
46fi
47base_bad=""
48exp_tcp=$(base_list expected_tcp) || base_bad="$base_bad expected_tcp"
49exp_udp=$(base_list expected_udp) || base_bad="$base_bad expected_udp"
50opt_tcp=$(base_list optional_tcp) || base_bad="$base_bad optional_tcp"
51[ -n "$base_bad" ] && log "FAIL baseline $BASE has no list for:$base_bad"
52base_note=$(grep -o '"note"[[:space:]]*:[[:space:]]*"[^"]*"' "$BASE" | sed 's/^"note"[^"]*"//; s/"$//')
53
54# b. scans
55PORTS="1-1024,1194,1723,2222,3000,3010,3389,4433,5000,5900,8000,8080,8443,9443,10443,18443,41641,50443"
56open_tcp=""; open_udp=""; udp_note=""; scan_ok=1
57if command -v nmap >/dev/null; then
58 res=$(nmap -Pn -n -sT --open -T4 --max-retries 1 --host-timeout 300s -p "$PORTS" -oG - "$ip" 2>/dev/null)
59 echo "$res" | grep -q '^Host:' || echo "$res" | grep -q 'Status: Up\|Ports:' || scan_ok=0
60 open_tcp=$(echo "$res" | grep -o '[0-9]\+/open/tcp' | cut -d/ -f1 | sort -n | tr '\n' ' ')
61 ures=$(nmap -Pn -n -sU --open -p 3478,41641 --max-retries 2 -oG - "$ip" 2>/dev/null)
62 open_udp=$(echo "$ures" | grep -o '[0-9]\+/open/udp' | cut -d/ -f1 | sort -n | tr '\n' ' ')
63 udp_note="UDP open/filtered is not distinguishable; only 'open' counted."
64else
65 udp_note="UNVERIFIED: nmap missing, UDP not checked."
66 conn() { timeout 2 bash -c "exec 3<>/dev/tcp/$ip/$1" 2>/dev/null && echo "$1"; }
67 list=$(seq 1 1024; for p in 1194 1723 2222 3000 3010 3389 4433 5000 5900 8000 8080 8443 9443 10443 18443 41641 50443; do echo $p; done)
68 open_tcp=$(echo "$list" | xargs -P 64 -I{} bash -c "timeout 2 bash -c 'exec 3<>/dev/tcp/$ip/{}' 2>/dev/null && echo {}" | sort -n | tr '\n' ' ')
69fi
70log "scan_ok=$scan_ok tcp=[$open_tcp] udp=[$open_udp] $udp_note"
71
72# c. UPnP
73upnp=off; mappings=""
74up=$(timeout 30 upnpc -l 2>&1)
75if command -v upnpc >/dev/null; then
76 if echo "$up" | grep -qi 'No IGD UPnP Device found\|No valid UPNP Internet Gateway\|upnpDiscover() error'; then upnp=off
77 elif echo "$up" | grep -qi 'Found valid IGD\|Found a valid IGD\|List of UPNP port mappings'; then upnp=on
78 fi
79 mappings=$(echo "$up" | grep -E '^ *[0-9]+ +(TCP|UDP) ' | sed 's/^ *//; s/"/\\"/g')
80else
81 log "UNVERIFIED: upnpc missing"
82fi
83log "upnp=$upnp"
84
85# d. DNS
86dns_ok=true; dns_detail=""
87# Public DNS names that must resolve to this public IP (override with EXPOSURE_DNS_HOSTS).
88for h in ${EXPOSURE_DNS_HOSTS:-hs.aienos.com}; do
89 a=$(dig +short +time=5 +tries=1 A "$h" 2>/dev/null | grep -E '^[0-9.]+$' | sort | tr '\n' ' ')
90 if [ "$a" != "$ip " ]; then dns_ok=false; dns_detail="$dns_detail $h=${a:-none}"; fi
91done
92
93# e. compare
94changes=()
95[ -n "$base_bad" ] && changes+=("The baseline file $BASE could not be read for:$base_bad. Nothing is being compared for those lists.")
96fmt() { echo "$*" | xargs; }
97for p in $open_tcp; do [[ " $exp_tcp" == *" $p "* || " $opt_tcp" == *" $p "* ]] || changes+=("TCP port $p is open in the inside view and is not in the baseline."); done
98for p in $exp_tcp; do [[ " $open_tcp" == *" $p "* ]] || changes+=("Baseline TCP port $p is not reachable in the inside view."); done
99for p in $open_udp; do [[ " $exp_udp" == *" $p "* ]] || changes+=("UDP port $p is open in the inside view and is not in the baseline."); done
100[ "$upnp" = on ] && changes+=("The router answers UPnP, so devices could open ports by themselves.")
101[ -n "$mappings" ] && changes+=("The router lists UPnP port mappings.")
102[ "$dns_ok" = false ] && changes+=("DNS does not match the public IP $ip:$dns_detail.")
103[ "$scan_ok" = 0 ] && changes+=("The port scan did not complete; result UNVERIFIED.")
104status=ok; [ ${#changes[@]} -gt 0 ] && status=changed
105
106jarr() { local o="" x; for x in "$@"; do o="$o${o:+,}$x"; done; echo "[$o]"; }
107sarr() { local o="" x; for x in "$@"; do o="$o${o:+,}\"$x\""; done; echo "[$o]"; }
108mapjson=$(printf '%s\n' "$mappings" | sed '/^$/d' | sed 's/^/"/; s/$/"/' | paste -sd, -)
109chjson=""; for c in "${changes[@]}"; do chjson="$chjson${chjson:+,}\"${c//\"/\\\"}\""; done
110json=$(printf '{"ts":%s,"vantage":"lan-hairpin","baseline_note":"%s","public_ip":"%s","open_tcp":%s,"open_udp":%s,"upnp":"%s","upnp_mappings":[%s],"dns_ok":%s,"expected_tcp":%s,"optional_tcp":%s,"expected_udp":%s,"status":"%s","changes":[%s]}' \
111 "$ts" "${base_note//\"/}" "$ip" "$(jarr $open_tcp)" "$(jarr $open_udp)" "$upnp" "$mapjson" "$dns_ok" "$(jarr $exp_tcp)" "$(jarr $opt_tcp)" "$(jarr $exp_udp)" "$status" "$chjson")
112echo "$json" > "$OUT.tmp" && chmod 644 "$OUT.tmp" && mv "$OUT.tmp" "$OUT"
113[ "$status" = changed ] && echo "$json" >> "$STATE/alerts.log"
114log "status=$status end $(date -u +%FT%TZ)"
115mv "$RUNLOG.new" "$RUNLOG"