#!/bin/bash
# port_watch
# Port intrusion watch for RHEL 8, 9 and 10, since the last run:
#  - port scans and probes: the packets the firewall denied, from the
#    kernel log lines firewalld writes when denied packets are logged
#    (firewall-cmd --set-log-denied=unicast, or a LOG/log rule), per
#    source address: packets, ports tried, a scan when one address
#    tried --scan (10) or more ports;
#  - listening ports: TCP and UDP sockets listening now (ss), compared
#    with a saved list, so a new listener (a backdoor, a service that
#    should not be there) shows until it is accepted.
#
# Runs on its own (CSV table to stdout or --out FILE), or hands its
# result to the DataReel Reporting Agent with --submit (drra submit
# --hook port_watch), which sends it to the dashboard. See README.md.
#
# Usage: port_watch [options]       (port_watch --help)
#
# Needs bash, gawk (awk on RHEL), ss (iproute), journalctl or
# /var/log/messages. Root, or --sudo, to read the kernel log and to see
# the programs behind the listening sockets. It changes no firewall
# setting.

PROGRAM=port_watch
VERSION=1.0
HOOK_ID=port_watch

function usage()
{
    cat <<EOF
Usage: ${PROGRAM} [options]

Denied packets (port scans) since the last run, and listening ports
compared with the accepted list.

What to read:
  --source S         auto (default), journal or messages
  --log FILE         syslog file with the kernel lines, with --source
                     messages (default /var/log/messages)
  --input FILE       parse FILE (- for stdin) as given: journalctl -k -o
                     short-iso output or a syslog file; no saved position
  --ss-input FILE    read the listening sockets from FILE (ss -H -tulnp
                     output) instead of running ss
  --since TIME       start at TIME instead of the saved position, for
                     example "24 hours ago" (journal only)
  --state FILE       saved position (default: ${DEFAULT_STATE}); the
                     accepted listening ports are in <state>.listen
  --no-save          do not save the new position
  --sudo             read the logs and run ss and drra with sudo -n
  --trusted LIST     addresses that count as trusted, not remote: IPv4
                     CIDRs or addresses, separated by spaces or commas

Checks:
  --scan N           an address that tried N or more ports in one run is
                     a scan (default 10)
  --accept-listeners save the listening ports seen now as the accepted
                     list (the first run does this too)
  --no-listeners     do not check the listening ports

Output:
  --format F         csv (default: one row per source address), lines
                     (DRSM lines: values + table) or listeners (CSV)
  --out FILE         write to FILE instead of stdout

Agent (DataReel Reporting Agent for Linux):
  --submit           send the result with drra submit (lines format)
  --now              ask the agent to send it within seconds
  --hook ID          upload hook ID (default ${HOOK_ID})
  --drra PATH        agent program (default drra in PATH or /usr/sbin/drra)
  --drra-config INI  agent settings file (drra -c INI)

  -h, --help         this help
  --version          program version
EOF
}

function die()
{
    echo "${PROGRAM}: ${*}" >&2
    exit 1
}

if [ "$(id -u)" == "0" ]; then
    DEFAULT_STATE=/var/lib/drra_utils/${PROGRAM}.state
else
    DEFAULT_STATE=${XDG_STATE_HOME:-${HOME}/.local/state}/drra_utils/${PROGRAM}.state
fi

SOURCE=auto
LOG_FILE=/var/log/messages
INPUT=""
SS_INPUT=""
SINCE=""
STATE_FILE="${DEFAULT_STATE}"
SAVE=1
SUDO=()
TRUSTED=""
SCAN=10
ACCEPT=0
LISTENERS=1
FORMAT=csv
OUT=""
SUBMIT=0
NOW=0
DRRA=""
DRRA_CONFIG=""

while [ $# -gt 0 ]; do
    case "${1}" in
	--source) SOURCE="${2}"; shift ;;
	--log) LOG_FILE="${2}"; SOURCE=messages; shift ;;
	--input) INPUT="${2}"; shift ;;
	--ss-input) SS_INPUT="${2}"; shift ;;
	--since) SINCE="${2}"; shift ;;
	--state) STATE_FILE="${2}"; shift ;;
	--no-save) SAVE=0 ;;
	--sudo) SUDO=(sudo -n) ;;
	--trusted) TRUSTED="${2}"; shift ;;
	--scan) SCAN="${2}"; shift ;;
	--accept-listeners) ACCEPT=1 ;;
	--no-listeners) LISTENERS=0 ;;
	--format) FORMAT="${2}"; shift ;;
	--out) OUT="${2}"; shift ;;
	--submit) SUBMIT=1 ;;
	--now) NOW=1 ;;
	--hook) HOOK_ID="${2}"; shift ;;
	--drra) DRRA="${2}"; shift ;;
	--drra-config) DRRA_CONFIG="${2}"; shift ;;
	-h|--help) usage; exit 0 ;;
	--version) echo "${PROGRAM} ${VERSION}"; exit 0 ;;
	*) echo "${PROGRAM}: unknown option ${1}" >&2; usage >&2; exit 2 ;;
    esac
    shift
done

case "${SOURCE}" in auto|journal|messages) ;; *) die "--source must be auto, journal or messages" ;; esac
case "${FORMAT}" in csv|lines|listeners) ;; *) die "--format must be csv, lines or listeners" ;; esac
[[ "${SCAN}" =~ ^[0-9]+$ ]] && [ "${SCAN}" -gt 0 ] || die "--scan needs a number above 0"
if [ "${SUBMIT}" == "1" ]; then
    if [ "${DRRA}" == "" ]; then
	DRRA=$(command -v drra 2> /dev/null || echo /usr/sbin/drra)
    fi
    [ -x "${DRRA}" ] || die "agent program ${DRRA} not found, install the agent or use --drra"
fi
if [ "${SOURCE}" == "auto" ]; then
    if command -v journalctl > /dev/null 2>&1; then SOURCE=journal; else SOURCE=messages; fi
fi

WORK=$(mktemp -d) || die "cannot make a temporary folder"
trap 'rm -rf "${WORK}"' EXIT
RAW="${WORK}/raw.log"
NEW_STATE="${WORK}/state"
LISTEN_FILE="${STATE_FILE%.state}.listen"

function state_value()
{
    [ -f "${STATE_FILE}" ] && sed -n "s/^${1}=//p" "${STATE_FILE}" | head -1
}

# The syslog file from the saved inode and offset (a rotated file
# <log>-YYYYMMDD is read to its end first), as auth_watch does
function read_messages()
{
    local inode offset cur_inode size f
    inode=$(state_value inode)
    offset=$(state_value offset)
    [[ "${offset}" =~ ^[0-9]+$ ]] || offset=0
    [ "$(state_value file)" == "${LOG_FILE}" ] || { inode=""; offset=0; }
    cur_inode=$("${SUDO[@]}" stat -c %i "${LOG_FILE}" 2> /dev/null) || die "cannot read ${LOG_FILE} (root or --sudo)"
    size=$("${SUDO[@]}" stat -c %s "${LOG_FILE}")
    : > "${RAW}"
    if [ "${inode}" != "" ] && [ "${inode}" != "${cur_inode}" ]; then
	for f in $("${SUDO[@]}" ls -1t "${LOG_FILE}"-* 2> /dev/null); do
	    if [ "$("${SUDO[@]}" stat -c %i "${f}" 2> /dev/null)" == "${inode}" ]; then
		"${SUDO[@]}" tail -c +$(( offset + 1 )) "${f}" >> "${RAW}" 2> /dev/null
		break
	    fi
	done
	offset=0
    elif [ "${inode}" == "" ] || [ "${offset}" -gt "${size}" ]; then
	offset=0
    fi
    "${SUDO[@]}" tail -c +$(( offset + 1 )) "${LOG_FILE}" | head -c $(( size - offset )) >> "${RAW}" \
	|| die "cannot read ${LOG_FILE}"
    printf 'source=messages\nfile=%s\ninode=%s\noffset=%s\n' "${LOG_FILE}" "${cur_inode}" "${size}" > "${NEW_STATE}"
}

# Kernel messages after the saved cursor, or since --since, or the last
# 24 hours on the first run
function read_journal()
{
    local cursor args new
    cursor=$(state_value cursor)
    args=(-q --no-pager -o short-iso --show-cursor -k)
    if [ "${SINCE}" != "" ]; then
	args+=(--since "${SINCE}")
    elif [ "${cursor}" != "" ] && [ "$(state_value source)" == "journal" ]; then
	args+=(--after-cursor "${cursor}")
    else
	args+=(--since "24 hours ago")
    fi
    "${SUDO[@]}" journalctl "${args[@]}" > "${RAW}" 2> "${WORK}/journal.err" \
	|| die "journalctl failed: $(head -1 "${WORK}/journal.err")"
    new=$(sed -n 's/^-- cursor: //p' "${RAW}" | tail -1)
    sed -i '/^-- cursor: /d' "${RAW}"
    [ "${new}" == "" ] && new="${cursor}"
    printf 'source=journal\ncursor=%s\n' "${new}" > "${NEW_STATE}"
}

if [ "${INPUT}" != "" ]; then
    SOURCE=input
    SAVE=0
    if [ "${INPUT}" == "-" ]; then cat > "${RAW}"; else cat -- "${INPUT}" > "${RAW}" || die "cannot read ${INPUT}"; fi
elif [ "${SOURCE}" == "journal" ]; then
    read_journal
else
    read_messages
fi

# Is the firewall logging denied packets? (only a hint, nothing changes)
LOG_DENIED=unknown
# firewall-cmd needs root (it can wait on polkit otherwise): root or --sudo only
if [ "${INPUT}" == "" ] && [ "${FIREWALL_CMD:-}" != "none" ] && command -v firewall-cmd > /dev/null 2>&1 \
    && { [ "$(id -u)" == "0" ] || [ ${#SUDO[@]} -gt 0 ]; }; then
    LOG_DENIED=$(timeout 15 "${SUDO[@]}" firewall-cmd --get-log-denied < /dev/null 2> /dev/null || echo unknown)
fi

# Denied packets: kernel lines with SRC= DST= PROTO= (firewalld, iptables
# LOG or nftables log). Output S rows per source, P rows per port, V values.
awk -v trusted="${TRUSTED}" -v scan="${SCAN}" '
function ip4(s,   p) {
    if (s !~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) return -1
    split(s, p, ".")
    return ((p[1] * 256 + p[2]) * 256 + p[3]) * 256 + p[4]
}
function is_trusted(ip,   i, parts, bits, a, b, div) {
    for (i = 1; i <= ntrust; i++) {
	if (trust[i] == ip) return 1
	if (split(trust[i], parts, "/") == 2 && (a = ip4(ip)) >= 0 && (b = ip4(parts[1])) >= 0) {
	    bits = parts[2] + 0
	    div = 2 ^ (32 - bits)
	    if (int(a / div) == int(b / div)) return 1
	}
    }
    return 0
}
function scope_of(ip) {
    if (ip ~ /^127\./ || ip == "::1") return "localhost"
    if (is_trusted(ip)) return "trusted"
    return "remote"
}
function field(name,   r) {
    if (match(msg, " " name "=([^ ]*)", r)) return r[1]
    return ""
}
BEGIN {
    ntrust = split(trusted, trust, /[ ,]+/)
    for (i = ntrust; i >= 1; i--) if (trust[i] == "") { delete trust[i]; ntrust-- }
}
{
    if (match($0, /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[^ ]+ [^ ]+ /)) {
	ts = substr($0, 1, index($0, " ") - 1)
    } else if (match($0, /^[A-Z][a-z][a-z] [ 0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [^ ]+ /)) {
	ts = substr($0, 1, 15)
    } else {
	next
    }
    msg = " " substr($0, RLENGTH + 1)
    if (index(msg, " SRC=") == 0 || index(msg, " PROTO=") == 0 || index(msg, " DST=") == 0) next
    if (field("OUT") != "" && field("IN") == "") next     # The host sending, not receiving
    src = field("SRC"); proto = field("PROTO"); dpt = field("DPT")
    if (src == "") next
    sc = scope_of(src)
    nlines++
    port = (dpt == "") ? tolower(proto) : tolower(proto) "/" dpt
    k = sc SUBSEP src
    if (!(k in pk)) first[k] = ts
    pk[k]++
    last[k] = ts
    if (!((k, port) in seenp)) { seenp[k, port] = 1; nports[k]++; plist[k] = plist[k] (plist[k] == "" ? "" : " ") port }
    if (!((k, proto) in seenproto)) { seenproto[k, proto] = 1; protos[k] = protos[k] (protos[k] == "" ? "" : "+") proto }
    if (sc == "remote") { portcount[port]++; remote_packets++ }
    total[sc]++
}
END {
    for (k in pk) {
	split(k, f, SUBSEP)
	kind = (nports[k] >= scan) ? "scan" : "probe"
	if (f[1] == "remote") { nsrc++; if (kind == "scan") nscan++; if (pk[k] > top_n) { top_n = pk[k]; top = f[2] } }
	pl = plist[k]
	if (length(pl) > 120) pl = substr(pl, 1, 117) "..."
	printf "S\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%s\n", f[1], f[2], pk[k], nports[k], protos[k], pl, first[k], last[k], kind
    }
    for (p in portcount) printf "P\t%s\t%d\n", p, portcount[p]
    printf "V\tdenied_packets\t%d\n", remote_packets
    printf "V\tdenied_sources\t%d\n", nsrc
    printf "V\tscan_sources\t%d\n", nscan
    printf "V\ttop_source\t%s\n", (top == "" ? "none" : top)
    printf "V\ttop_source_packets\t%d\n", top_n
    printf "V\ttrusted_denied\t%d\n", total["trusted"]
    printf "V\tlines_read\t%d\n", nlines
}' "${RAW}" > "${WORK}/parsed" || die "awk failed (gawk is needed)"

grep '^S' "${WORK}/parsed" | cut -f2- | sort -t "$(printf '\t')" -k3,3nr > "${WORK}/sources"
grep '^V' "${WORK}/parsed" | cut -f2- > "${WORK}/values"
TOP_PORTS=$(grep '^P' "${WORK}/parsed" | sort -t "$(printf '\t')" -k3,3nr | head -5 | awk -F '\t' '{ printf "%s%s:%d", (NR > 1 ? " " : ""), $2, $3 }')
printf 'top_ports\t%s\n' "${TOP_PORTS:-none}" >> "${WORK}/values"
printf 'firewall_log_denied\t%s\n' "${LOG_DENIED}" >> "${WORK}/values"
case "${LOG_DENIED}" in
    off) printf 'firewall_logging\t0\n' >> "${WORK}/values" ;;
    unknown) ;;
    *) printf 'firewall_logging\t1\n' >> "${WORK}/values" ;;
esac
: > "${WORK}/alerts"
awk -F '\t' '$1 == "remote" && $9 == "scan" { n++; if (n <= 10) printf "WARNING - port scan from %s: %d packets to %d ports (%s), %s to %s\n", $2, $3, $4, $6, $7, $8 }' \
    "${WORK}/sources" >> "${WORK}/alerts"
if [ "${LOG_DENIED}" == "off" ]; then
    echo "INFO - firewalld does not log denied packets, so port scans are not seen: firewall-cmd --set-log-denied=unicast turns it on" >> "${WORK}/alerts"
fi

# Listening sockets: proto|address:port|program
: > "${WORK}/listen_now"
NEW_LISTENERS=0
GONE_LISTENERS=0
if [ "${LISTENERS}" == "1" ]; then
    if [ "${SS_INPUT}" != "" ]; then
	cat -- "${SS_INPUT}" > "${WORK}/ss" || die "cannot read ${SS_INPUT}"
    else
	"${SUDO[@]}" ss -H -tulnp > "${WORK}/ss" 2> /dev/null || ss -H -tuln > "${WORK}/ss" 2> /dev/null \
	    || die "ss failed (iproute)"
    fi
    # ss -H -tulnp: Netid State Recv-Q Send-Q Local:Port Peer:Port [users:(("prog",pid=1,fd=3))]
    awk '{
	if ($1 != "tcp" && $1 != "udp") next
	if ($1 == "tcp" && $2 != "LISTEN") next
	if ($1 == "udp" && $2 != "UNCONN") next
	prog = "-"
	if (match($0, /users:\(\("([^"]+)"/, m)) prog = m[1]
	print $1 "|" $5 "|" prog
    }' "${WORK}/ss" | sort -u > "${WORK}/listen_now"
    if [ ! -f "${LISTEN_FILE}" ] || [ "${ACCEPT}" == "1" ]; then
	FIRST_LISTEN=1
	cp "${WORK}/listen_now" "${WORK}/listen_base"
    else
	FIRST_LISTEN=0
	sort -u "${LISTEN_FILE}" > "${WORK}/listen_base"
    fi
    # Compared by protocol and address:port; the program can change name
    cut -d '|' -f1,2 "${WORK}/listen_base" | sort -u > "${WORK}/base_keys"
    cut -d '|' -f1,2 "${WORK}/listen_now" | sort -u > "${WORK}/now_keys"
    comm -13 "${WORK}/base_keys" "${WORK}/now_keys" > "${WORK}/new_keys"
    comm -23 "${WORK}/base_keys" "${WORK}/now_keys" > "${WORK}/gone_keys"
    NEW_LISTENERS=$(wc -l < "${WORK}/new_keys")
    GONE_LISTENERS=$(wc -l < "${WORK}/gone_keys")
    while IFS='|' read -r proto addr; do
	prog=$(awk -F '|' -v p="${proto}" -v a="${addr}" '$1 == p && $2 == a { print $3; exit }' "${WORK}/listen_now")
	echo "WARNING - new listening port ${proto} ${addr} (${prog}), not in the accepted list: port_watch --accept-listeners accepts it" >> "${WORK}/alerts"
    done < "${WORK}/new_keys"
    while IFS='|' read -r proto addr; do
	echo "INFO - accepted listening port ${proto} ${addr} is closed" >> "${WORK}/alerts"
    done < "${WORK}/gone_keys"
    printf 'listeners\t%d\n' "$(wc -l < "${WORK}/listen_now")" >> "${WORK}/values"
    printf 'listeners_all_addresses\t%d\n' "$(grep -cE '\|(0\.0\.0\.0|\*|\[::\]):[0-9]+\|' "${WORK}/listen_now")" >> "${WORK}/values"
    printf 'new_listeners\t%d\n' "${NEW_LISTENERS}" >> "${WORK}/values"
    # New listeners other hosts can reach: not on a loopback address
    printf 'new_exposed_listeners\t%d\n' "$(grep -cvE '\|(127\.[0-9.]+|\[::1\]|::1):[0-9]+$' "${WORK}/new_keys")" >> "${WORK}/values"
    printf 'closed_listeners\t%d\n' "${GONE_LISTENERS}" >> "${WORK}/values"
fi
function value() { awk -F '\t' -v n="${1}" '$1 == n { print $2 }' "${WORK}/values"; }

# $1 == format, $2 == output file
function write_output()
{
    if [ "${1}" == "csv" ]; then
	echo "scope,source,packets,ports,protocols,ports_tried,first,last,kind" > "${2}"
	awk -F '\t' '{ printf "%s,%s,%s,%s,%s,%s,%s,%s,%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9 }' "${WORK}/sources" >> "${2}"
	return
    fi
    if [ "${1}" == "listeners" ]; then
	echo "protocol,address,program,state" > "${2}"
	awk -F '|' -v newf="${WORK}/new_keys" 'BEGIN { while ((getline l < newf) > 0) isnew[l] = 1 }
	    { printf "%s,%s,%s,%s\n", $1, $2, $3, (($1 "|" $2) in isnew) ? "new" : "accepted" }' "${WORK}/listen_now" >> "${2}"
	return
    fi
    {
	echo "INFO - ${PROGRAM} ${VERSION} on $(hostname -s): $(value denied_packets) denied packets from" \
	    "$(value denied_sources) addresses, $(value scan_sources) port scans; top ports $(value top_ports);" \
	    "${NEW_LISTENERS} new listening ports (${SOURCE}, firewall log-denied ${LOG_DENIED})"
	cat "${WORK}/alerts"
	while IFS=$'\t' read -r n v; do echo "DETAIL ${n}=${v}"; done < "${WORK}/values"
	echo "DETAIL source=${SOURCE}"
	echo "DETAIL collected=$(date '+%Y-%m-%dT%H:%M:%S%z')"
	echo "UPLOAD columns|Scope|Source|Packets|Ports|Protocols|Ports tried|First|Last|Kind"
	head -200 "${WORK}/sources" | awk -F '\t' '{ printf "UPLOAD row|%s|%s|%s|%s|%s|%s|%s|%s|%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9 }'
    } > "${2}"
}

write_output "${FORMAT}" "${WORK}/out"
if [ "${OUT}" != "" ]; then
    cp "${WORK}/out" "${OUT}" || die "cannot write ${OUT}"
elif [ "${SUBMIT}" == "0" ]; then
    cat "${WORK}/out"
fi

if [ "${SUBMIT}" == "1" ]; then
    PAYLOAD="${WORK}/${PROGRAM}_$(hostname -s)_$(date +%Y%m%d%H%M%S).txt"
    write_output lines "${PAYLOAD}"
    chmod 644 "${PAYLOAD}"
    chmod 755 "${WORK}"
    args=()
    [ "${DRRA_CONFIG}" != "" ] && args+=(-c "${DRRA_CONFIG}")
    args+=(submit --hook "${HOOK_ID}")
    [ "${NOW}" == "1" ] && args+=(--now)
    "${SUDO[@]}" "${DRRA}" "${args[@]}" "${PAYLOAD}" || die "drra submit failed, the position is not saved"
fi

if [ "${SAVE}" == "1" ] || [ "${ACCEPT}" == "1" ]; then
    mkdir -p "$(dirname "${STATE_FILE}")" && chmod 700 "$(dirname "${STATE_FILE}")" 2> /dev/null
fi
if [ "${SAVE}" == "1" ]; then
    cp "${NEW_STATE}" "${STATE_FILE}.tmp" && mv "${STATE_FILE}.tmp" "${STATE_FILE}" \
	|| die "cannot save the position in ${STATE_FILE}"
fi
# The accepted listening ports: written on the first run and with
# --accept-listeners, never changed otherwise
if [ "${LISTENERS}" == "1" ] && { [ "${FIRST_LISTEN}" == "1" ]; } && { [ "${SAVE}" == "1" ] || [ "${ACCEPT}" == "1" ]; }; then
    cp "${WORK}/listen_now" "${LISTEN_FILE}.tmp" && chmod 600 "${LISTEN_FILE}.tmp" && mv "${LISTEN_FILE}.tmp" "${LISTEN_FILE}" \
	|| die "cannot save the listening ports in ${LISTEN_FILE}"
fi
exit 0
