#!/bin/sh
# Linux client, with the same read-only diagnostics as the Windows client.
set -eu
origin=${1:-https://audit.mb-cloud.ru}
sample=${2:-}
case "$origin" in https://*) ;; *) echo 'Expected HTTPS origin' >&2; exit 2;; esac
authority=${origin#https://}
case "$authority" in ''|*[!A-Za-z0-9.:-]*) echo 'Invalid origin' >&2; exit 2;; esac
printf 'One-time invitation: ' >&2
if [ -t 0 ]; then
    terminal_state=$(stty -g)
    trap 'stty "$terminal_state"' EXIT
    trap 'exit 1' HUP INT TERM
    stty -echo
    IFS= read -r invite
    stty "$terminal_state"
    trap - EXIT HUP INT TERM
    printf '\n' >&2
else
    IFS= read -r invite
fi
valid_token() {
    [ "${#1}" = 43 ] || return 1
    case "$1" in *[!A-Za-z0-9_-]*) return 1;; esac
}
valid_token "$invite" || exit 2

post() {
    # Put the bearer on stdin, outside the curl command line.
    response=$(printf 'header = "Authorization: Bearer %s"\n' "$2" |
        curl -q --config - --silent --show-error --proto '=https' \
        --max-time 5 --max-filesize 256 --write-out ' %{http_code}' \
        --data-binary "${3:-}" "$origin/$1") || return 1
    case "${response##* }" in
        200) printf '%s' "${response% *}" ;;
        403) if [ "$1" = poll ]; then printf 'closed'; else return 1; fi ;;
        *) printf 'Audit relay returned HTTP %s\n' "${response##* }" >&2; return 1 ;;
    esac
}
uptime_seconds() {
    read -r uptime rest < /proc/uptime
    printf '%s' "${uptime%%.*}"
}
host_health() {
    memory=$(awk '/^MemTotal:/ { total=$2 } /^MemAvailable:/ { available=$2 }
        END { if (!total || available == "") exit 1
              printf "mem_total_kib=%s mem_available_kib=%s", total, available }' /proc/meminfo) || return 1
    disk=$(LC_ALL=C df -Pk /) || return 1
    disk=$(printf '%s\n' "$disk" | awk 'NR==2 && $2 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ {
        printf "disk_total_kib=%s disk_available_kib=%s", $2, $4; seen=1 } END { if (!seen) exit 1 }') || return 1
    printf 'uptime_s=%s %s %s' "$(uptime_seconds)" "$memory" "$disk"
}
login_failures() {
    [ -r /var/log/btmp ] || return 1
    # lastb reads the active btmp file; identifiers never leave this function.
    entries=$(LC_ALL=C timeout 4 lastb -f /var/log/btmp -s '-1hour' -n 101 2>/dev/null) || return 1
    printf '%s\n' "$entries" | awk 'NF && !($1=="btmp" && $2=="begins") { n++ }
        END { printf "source=btmp interval_s=3600 failures=%d capped=%d", (n>100 ? 100 : n), (n>100) }'
}
peer_check() {
    printf '%s\n' "$1" | awk -F. 'NF!=4 {exit 1} {for(i=1;i<=4;i++) if ($i !~ /^[0-9]+$/ || length($i)>3 || $i+0>255 || (length($i)>1 && substr($i,1,1)=="0")) exit 1}' || return 1
    sockets=$(LC_ALL=C timeout 4 ss -Hnt state all dst "$1" 2>/dev/null) || return 1
    printf '%s\n' "$sockets" | awk 'NF && $1!="LISTEN" {n++; if ($1=="ESTAB") e++}
        END {printf "matching_tcp=%d established=%d", n, e}'
}
# Run the two potentially slow operations as direct children. A Linux parent-death
# signal also stops the downloader or scanner if the session process is killed.
run_scan_child() {
    setpriv --pdeathsig KILL -- "$@" &
    worker=$!
    while kill -0 "$worker" 2>/dev/null; do
        sleep 1
        [ "$(uptime_seconds)" -lt "$deadline" ] && [ "$(post poll "$token")" = "$job" ] || exit 0
    done
    child_status=0
    wait "$worker" || child_status=$?
    worker=''
    return "$child_status"
}
scan_sample() {
    [ -n "$sample" ] || { printf sample_not_selected; return; }
    [ -f "$sample" ] && [ -r "$sample" ] || { printf sample_unavailable; return; }
    [ "$(uname -m)" = x86_64 ] || { printf scanner_unavailable; return; }
    [ "$(stat -Lc %s -- "$sample")" -le 16777216 ] || { printf sample_too_large; return; }
    # Snapshot before hashing so the returned hash identifies exactly the scanned bytes.
    head -c 16777217 -- "$sample" > "$scratch/subject" || return 1
    [ "$(wc -c < "$scratch/subject")" -le 16777216 ] || { printf sample_too_large; return; }
    if [ ! -x "$scratch/yr" ]; then
        run_scan_child curl -q --fail --silent --show-error --proto '=https' --max-time 90 --max-filesize 12000000 \
            -o "$scratch/package" "$origin/tools/yara-1.25.0-linux-x64.tar.gz" || return 1
        sum=$(sha256sum "$scratch/package") || return 1
        [ "${sum%% *}" = 5c4a1541dadc7d95eb8e56a2d972f5d3751e04e44db147a6f0b0fd5c398473a6 ] || return 1
        tar -xzf "$scratch/package" -C "$scratch" yr triage.yar || return 1
    fi
    sum=$(sha256sum "$scratch/subject") || return 1
    before_scan=$PWD
    cd "$scratch" || return 1
    scan_status=0
    run_scan_child ./yr scan --threads 1 --timeout 5 --disable-warnings triage.yar subject > matches || scan_status=$?
    cd "$before_scan" || return 1
    [ "$scan_status" -eq 0 ] || return 1
    matches=$(cat "$scratch/matches") || return 1
    rules=$(printf '%s\n' "$matches" | awk 'NF { if (NF!=2 || $2!="subject" || $1 !~ /^(redline_payload|MALW_emotet|MALW_fritzfrog|malw_eicar|AuditBridge_Test_Marker)$/) exit 1
        names=names sep $1; sep="," } END {printf "%s",names ? names : "none"}') || return 1
    printf 'sha256=%s rules=%s' "${sum%% *}" "$rules"
}
protection_events() {
    # journalctl may silently return an incomplete system journal for an unprivileged user.
    if [ "$(id -u)" != 0 ]; then
        case " $(id -Gn) " in *" systemd-journal "*|*" adm "*) ;; *) return 1;; esac
    fi
    available=$(LC_ALL=C timeout 3 journalctl -k -n 1 -q --no-pager -o json 2>/dev/null) || return 1
    [ -n "$available" ] || return 1
    if [ "${1:-}" = timeline ]; then
        recent=$(LC_ALL=C timeout 5 journalctl -k -p 0..3 --since '24 hours ago' -n 5 -rq --no-pager -o short-unix 2>/dev/null) || return 1
        printf '%s\n' "$recent" | awk '/^[0-9]+[.][0-9]+ / {
            text=tolower($0); label="other"
            if(text ~ /out of memory|oom.kill|killed process/) label="oom"
            else if(text ~ /i\/o error|blk_update_request/) label="io"
            else if(text ~ /segfault/) label="segfault"
            else if(text ~ /ext4-fs|xfs|btrfs/) label="filesystem"
            else if(text ~ /blocked for more than/) label="blocked"
            split($1,t,"[.]"); events=events sep t[1] ":" label; sep=","
        } END {printf "source=kernel recent=%s", events ? events : "none"}'
        return
    fi
    recent=$(LC_ALL=C timeout 5 journalctl -k -p 0..3 --since '24 hours ago' -n 101 -q --no-pager -o json 2>/dev/null) || return 1
    printf '%s\n' "$recent" | awk 'NF {n++} END {printf "source=kernel-journal interval_s=86400 events=%d capped=%d", (n>100 ? 100 : n), (n>100)}'
}
start=$(uptime_seconds)
joined=$(post join "$invite" audit/2)
unset invite
token=${joined% *}
ttl=${joined##* }
valid_token "$token" || exit 1
case "$ttl" in ''|0*|*[!0-9]*) exit 1;; esac
[ "${#ttl}" -le 4 ] && [ "$ttl" -le 1800 ] || exit 1
deadline=$((start + ttl))
scratch=''
worker=''
janitor=''
finish() {
    if [ -n "$worker" ]; then
        kill -KILL "$worker" 2>/dev/null || :
        wait "$worker" 2>/dev/null || :
    fi
    if [ -n "$janitor" ]; then kill "$janitor" 2>/dev/null || :; wait "$janitor" 2>/dev/null || :; fi
    if [ -n "$scratch" ]; then rm -rf -- "$scratch"; fi
    post close "$token" >/dev/null 2>&1 || :
}
trap finish EXIT
trap 'exit 0' HUP INT TERM
printf 'Read-only audit session open for up to %s seconds. Ctrl+C to close.\n' "$ttl"
while [ "$(uptime_seconds)" -lt "$deadline" ]; do
    job=$(post poll "$token")
    [ "$job" != closed ] || break
    [ "$(uptime_seconds)" -lt "$deadline" ] || break
    if [ "$job" != idle ]; then
        job_id=${job%% *}
        [ "${#job_id}" = 16 ] || exit 1
        case "$job_id" in *[!0-9a-f]*) exit 1;; esac
        op=${job#* }
        case "$op" in
            platform)
                result="kernel=$(uname -r) uid=$(id -u)" ;;
            yara-scan)
                if [ -z "$scratch" ]; then
                    scratch=$(mktemp -d)
                    owner=$$
                    # A hard kill skips EXIT traps. The monitor only owns this private directory.
                    (
                        while IFS= read -r self_stat < /proc/self/stat; do
                            # Linux reparents this monitor immediately, even before its old parent is reaped.
                            fields=${self_stat##*) }
                            parent_and_rest=${fields#* }
                            [ "${parent_and_rest%% *}" = "$owner" ] || break
                            sleep 1
                        done
                        rm -rf -- "$scratch"
                    ) </dev/null >/dev/null 2>&1 &
                    janitor=$!
                fi
                scan_sample > "$scratch/result" || printf scanner_unavailable > "$scratch/result"
                result=$(cat "$scratch/result") ;;
            protection-timeline) result=$(protection_events timeline) || result='diagnostic unavailable' ;;
            protection-events) result=$(protection_events) || result='diagnostic unavailable' ;;
            host-health) result=$(host_health) || result='diagnostic unavailable' ;;
            login-failures) result=$(login_failures) || result='diagnostic unavailable' ;;
            'peer-check '*) result=$(peer_check "${op#peer-check }") || result='diagnostic unavailable' ;;
            tcp-summary)
                set -- /proc/net/tcp
                if [ -r /proc/net/tcp6 ]; then set -- "$@" /proc/net/tcp6; fi
                result=$(awk 'FNR > 1 && $4 != "0A" { n++; if ($4 == "01") e++ }
                    END { printf "tcp_connections=%d established=%d", n, e }' "$@") || result='diagnostic unavailable' ;;
            *) echo 'Unsupported diagnostic' >&2; exit 1 ;;
        esac
        printf 'Diagnostic: %s\n' "$op"
        [ "$(uptime_seconds)" -lt "$deadline" ] || break
        post "result/$job_id" "$token" "$result" >/dev/null
    fi
    sleep 1
done
