#!/bin/sh
# icewatch-update — fetch IceWatch's definitions (malware fingerprints and
# rules, botnet networks, country data) on a machine that is NOT managed by a
# FreezeOS fleet. Run daily by icewatch-update.timer.
#
# It only downloads. `icewatch defs-apply` then decides: nothing is installed
# unless the list is signed with the IceWatch definitions key, every file
# matches it, and it is not older than what is installed.
#
# Nothing about this machine is sent: these are plain file downloads.
# Prints nothing when all is well; "no network right now" is not an error.
#   icewatch-update -v     say what was done
set -u
URL="https://os.freeze2k.net/api/fleet/icewatch/intel"
[ -r /etc/freezeos/icewatch/update.conf ] && . /etc/freezeos/icewatch/update.conf
STATE=/var/lib/icewatch
INC="$STATE/incoming"
VERBOSE=0; [ "${1:-}" = "-v" ] && VERBOSE=1
say() { [ "$VERBOSE" = 1 ] && echo "$*"; return 0; }

[ "$(id -u)" = 0 ] || { echo "icewatch-update: must be run as root" >&2; exit 1; }
# A fleet-managed machine gets its definitions through the fleet report.
if [ -s /boot/freezeos/node.json ] || grep -qs '^FLEET_SERVER_ID=..' /etc/freezeos/fleet.env; then
    say "this machine is managed by a fleet; its report tool fetches the definitions"
    exit 0
fi
command -v curl >/dev/null 2>&1 || { echo "icewatch-update: curl is not installed" >&2; exit 1; }
command -v icewatch >/dev/null 2>&1 || { echo "icewatch-update: the icewatch command is not installed" >&2; exit 1; }

mkdir -p "$INC" && chmod 700 "$INC" || exit 1
# One at a time: two runs would delete each other's downloads.
exec 9>"$STATE/.update.lock"
flock -n 9 || { say "an update is already running"; exit 0; }
get() { curl -sS --fail --location --max-time 900 -A "icewatch-update" -o "$INC/$1" "$URL/$1" 2>/dev/null; }
if ! get manifest.json || ! get manifest.sig; then
    rm -f "$INC"/*
    say "the definitions server could not be reached; will try again later"
    exit 0
fi
# Fetch only the files whose checksum differs from what is installed.
for f in geo.bin bad-nets.txt bad-hashes.bin bad-hashes.names bad-hashes-daily.bin bad-hashes-daily.names yara-rules.txt; do
    want=$(tr -d '\n ' < "$INC/manifest.json" | sed -n "s/.*\"$f\":{\"sha256\":\"\([0-9a-f]*\)\".*/\1/p")
    [ -n "$want" ] || continue
    have=""
    [ -r "$STATE/defs.json" ] && have=$(tr -d '\n ' < "$STATE/defs.json" | sed -n "s/.*\"$f\":\"\([0-9a-f]*\)\".*/\1/p")
    if [ "$want" != "$have" ] || [ ! -s "$STATE/$f" ]; then
        if ! get "$f"; then
            rm -f "$INC"/*
            say "$f could not be fetched; keeping the definitions as they are"
            exit 0
        fi
    fi
done
out=$(icewatch defs-apply 2>&1); rc=$?
rm -f "$INC"/*
if [ $rc -ne 0 ]; then
    # A refused download is worth one line: it means the server sent something wrong.
    echo "icewatch-update: $out" >&2
    exit 1
fi
say "${out:-definitions are up to date}"
exit 0
