Compare commits

..
2 Commits
+26 -3
View File
@@ -42,8 +42,17 @@ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export LC_ALL=C
umask 077 # state files hold key fingerprints and source IPs
TELEGRAM_BOT="8602530664:AAFE7tsRY79zhhEjU7sRR7MrS8p3FB0jvXg"
TELEGRAM_CHAT_ID="108712105"
# Telegram credentials live outside the script (it's in a public repo): a root-only env file
# with TELEGRAM_BOT=... and TELEGRAM_CHAT_ID=... lines. Fail loudly if it's missing rather than
# running a monitor that silently can't alert.
TELEGRAM_ENV="${TELEGRAM_ENV:-/root/.security-monitor/telegram.env}"
if [ ! -r "$TELEGRAM_ENV" ]; then
echo "ERROR: $TELEGRAM_ENV missing or unreadable — no way to send alerts" >&2
exit 1
fi
# shellcheck source=/dev/null
. "$TELEGRAM_ENV"
: "${TELEGRAM_BOT:?not set in $TELEGRAM_ENV}" "${TELEGRAM_CHAT_ID:?not set in $TELEGRAM_ENV}"
DISK_ALERT_PCT="${DISK_ALERT_PCT:-90}" # alert once usage reaches this
DISK_RECOVER_PCT="${DISK_RECOVER_PCT:-85}" # ...and don't re-arm until it drops back below this (hysteresis)
@@ -85,9 +94,17 @@ hash_files() {
# Listening sockets, normalised: pid/fd stripped (they change on every restart) and duplicate
# process entries collapsed (nginx reports one entry per worker, so a worker-count change from
# a routine reload would otherwise look like a socket change).
# UDP sockets of IGNORE_UDP_PROCS are dropped: helvetiscan (a known, trusted scanner) opens and
# closes dozens of random-port UDP sockets per second, so every tick alerted on lines like
# "UNCONN *:13786 helvetiscan". Its TCP listeners are still tracked. Ownerless UDP sockets on a
# port >= 1024 are dropped too: they're the same scanner's sockets caught mid-teardown, already
# detached from the process (sequential inodes, a new port every second). Ownerless sockets on
# privileged ports (e.g. the DHCP client on :68) stay in the snapshot.
IGNORE_UDP_PROCS="${IGNORE_UDP_PROCS:-helvetiscan}"
listening_sockets() {
local flag="$1"
ss -"$flag"lnp 2>/dev/null | tail -n +2 | awk '
ss -"$flag"lnp 2>/dev/null | tail -n +2 | awk -v flag="$flag" -v ignprocs="$IGNORE_UDP_PROCS" '
BEGIN { n = split(ignprocs, ip, /[ ,]+/); for (i = 1; i <= n; i++) if (ip[i] != "") ign[ip[i]] = 1 }
{
proc = $6
gsub(/,?(pid|fd)=[0-9]+/, "", proc)
@@ -102,6 +119,12 @@ listening_sockets() {
out = (out == "" ? parts[i] : out "," parts[i])
}
}
if (flag == "u") {
port = $4; sub(/.*:/, "", port)
if (out == "" && port + 0 >= 1024) next
n = split(out, names, ",")
for (i = 1; i <= n; i++) if (names[i] in ign) next
}
print $1, $4, out
}' | sort -u
}