#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
# Vulnpocalypse agent installer. Read it before you run it; it prints every file it
# writes and every command it runs.
#
#   sudo sh install.sh [--name NAME] [--paths "/srv/app /opt/tool"]
#                      [--images all|none|"img1 img2"] [--mode docker|binary] [--yes]
#   sudo sh install.sh --uninstall       remove everything this script made
#
# The agent key does not go on the command line, where sudo logs it and ps
# shows it. On a terminal, install.sh asks for it (the input is not shown).
# Without a terminal: --key-file FILE, --key - (the key on standard input), or
# the environment variable VULNPOCALYPSE_KEY.
#
# What it does:
#  1. checks that it runs as root on Linux (amd64 or arm64)
#  2. Docker mode when Docker runs: pulls the agent image by its digest (Docker
#     checks the content against it). Binary mode otherwise: downloads the
#     agent and Trivy, checks their SHA-256 sums (below), and adds the system
#     user vulnpocalypse, which runs the steps that read images and send
#  3. writes /etc/vulnpocalypse/agent.conf (mode 600), /etc/vulnpocalypse/server-id,
#     /usr/local/lib/vulnpocalypse/run.sh and /var/lib/vulnpocalypse/
#  4. a systemd timer once a day at a random time (or a cron line)
#  5. a first run that sends nothing (scan) and shows what it found
#  6. asks before the first report is sent; without a terminal it sends only
#     with --yes
set -eu

VERSION=0.2.2
URL=https://vulnpocalypse.ch                    # the service; the site fills it in
DOWNLOAD=https://vulnpocalypse.ch/dl/agent      # where the agent binaries are served
# Docker mode: the image by its digest (agent/build.sh writes it; registry.invalid is a placeholder)
IMAGE=ghcr.io/cdutsov/vulnpocalypse/agent:0.2.2@sha256:638fa6d29e1207057b225e81033c478d021119bc3bceb06e7449d0ad8d723924
AGENT_SHA256_amd64=975aee9439bae602b87e6ece247120de64ad7c331cc3b6e42fa809751b5cca20
AGENT_SHA256_arm64=67d1d3a1fbae406d00cce4377bc8ca199582ffe56bf17a3b65a694a6c72e31be
TRIVY_VERSION=0.75.0                               # from github.com/aquasecurity/trivy releases
TRIVY_SHA256_amd64=c6e65abddb348e25f10549df887045629cf28cc72453cd1c63acb717316b3f3f
TRIVY_SHA256_arm64=a1ee9f6ffb7d112b64ff726a2a0717c21175c1114361391f4a132956751a13b3

LIB=/usr/local/lib/vulnpocalypse
CONF_DIR=/etc/vulnpocalypse
STATE=/var/lib/vulnpocalypse
UNIT=/etc/systemd/system/vulnpocalypse-agent
CRON_D=/etc/cron.d/vulnpocalypse-agent
CRONTAB=/etc/crontabs/root
SYSUSER=vulnpocalypse

# Colors and a spinner for a person at a terminal; plain text without a
# terminal, with NO_COLOR, TERM=dumb or VULNPOCALYPSE_COLOR=0. run.sh gets the
# choice through VULNPOCALYPSE_COLOR.
UI=""
case ${VULNPOCALYPSE_COLOR:-} in
0 | never) ;;
1 | always | ascii) UI=1 ;;
*) if [ -t 1 ] && [ -t 2 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then UI=1; fi ;;
esac
BOLD="" DIM="" RED="" GREEN="" CYAN="" OFF="" OK="" NOK="" FRAMES="" E=""
if [ -n "$UI" ]; then
	E=$(printf '\033')
	BOLD="${E}[1m" DIM="${E}[2m" RED="${E}[1;31m" GREEN="${E}[32m" CYAN="${E}[36m" OFF="${E}[0m"
	# Unicode signs, or ASCII when the locale is not UTF-8 or on the Linux console
	case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in *[Uu][Tt][Ff]-8* | *[Uu][Tt][Ff]8* | "") ascii="" ;; *) ascii=1 ;; esac
	if [ "${TERM:-}" = linux ] || [ "${VULNPOCALYPSE_COLOR:-}" = ascii ]; then ascii=1; fi
	if [ -n "$ascii" ]; then
		OK='ok ' NOK='x ' FRAMES='- \ | /' VULNPOCALYPSE_COLOR=ascii
	else
		OK='✓ ' NOK='✗ ' FRAMES='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏' VULNPOCALYPSE_COLOR=1
	fi
else
	VULNPOCALYPSE_COLOR=0
fi
export VULNPOCALYPSE_COLOR

say() { printf '%s\n' "$*"; }
die() { printf '%sinstall.sh: %s%s\n' "$RED" "$*" "$OFF" >&2; exit 1; }
run() { printf '%s+ %s%s\n' "$DIM" "$*" "$OFF"; "$@"; }
# write FILE MODE: the text on stdin becomes FILE
write() { printf '%s+ write %s (mode %s)%s\n' "$DIM" "$1" "$2" "$OFF"; (umask 077 && cat >"$1"); chmod "$2" "$1"; }
# ok TEXT: a line that says a step went well
ok() { printf '  %s%s%s%s\n' "$GREEN" "$OK" "$OFF" "$*"; }
# bold TEXT, hint TEXT COMMAND: text in bold; text with a command to type
bold() { printf '%s%s%s\n' "$BOLD" "$*" "$OFF"; }
hint() { printf '%s%s%s%s\n' "$1" "$CYAN" "$2" "$OFF"; }
# spin LABEL: a turning sign and the seconds so far on stderr, until it is
# killed; it ends by itself when install.sh is gone
spin() {
	sp_t0=$(date +%s)
	printf '%s' "${E}[?25l" >&2
	while kill -0 $$ 2>/dev/null; do
		for f in $FRAMES; do
			printf '\r  %s%s%s %s %s%ss%s%s' "$CYAN" "$f" "$OFF" "$1" "$DIM" $(($(date +%s) - sp_t0)) "$OFF" "${E}[K" >&2
			sleep 0.1 2>/dev/null || sleep 1
		done
	done
	printf '\r%s%s' "${E}[K" "${E}[?25h" >&2
}
# run_step LABEL CMD...: as run; on a terminal the spinner shows LABEL while
# CMD runs, and the output of CMD is shown only when it fails
run_step() {
	rs_label=$1
	shift
	if [ -z "$UI" ]; then
		run "$@"
		return
	fi
	printf '%s+ %s%s\n' "$DIM" "$*" "$OFF"
	spin "$rs_label" &
	rs_pid=$!
	"$@" >"$tmp/step.log" 2>&1 && rs_rc=0 || rs_rc=$?
	kill "$rs_pid" 2>/dev/null || true
	wait "$rs_pid" 2>/dev/null || true
	printf '\r%s%s' "${E}[K" "${E}[?25h" >&2
	if [ "$rs_rc" != 0 ]; then
		printf '  %s%s%s%s\n' "$RED" "$NOK" "$rs_label" "$OFF" >&2
		cat "$tmp/step.log" >&2
	fi
	return "$rs_rc"
}
has() { command -v "$1" >/dev/null 2>&1; }
# a number from 0 to 65535 from /dev/urandom
random() { od -An -N2 -tu2 /dev/urandom | tr -d ' \n'; }

KEY=${VULNPOCALYPSE_KEY:-} KEY_FROM="" NAME="" PATHS="" IMAGES=all MODE="" YES="" UNINSTALL="" FROM=""
while [ $# -gt 0 ]; do
	case $1 in
	--key) [ "${2:-}" = - ] || die "the key does not go on the command line (sudo logs it): leave --key out and paste it when asked, or use --key-file FILE or --key - (standard input)"
		KEY_FROM=stdin; shift ;;
	--key-file) KEY_FROM=${2:?--key-file needs a file}; shift ;;
	--url) URL=$2; shift ;;
	--name) NAME=$2; shift ;;
	--paths) PATHS=$2; shift ;;
	--images) IMAGES=$2; shift ;;
	--mode) MODE=$2; shift ;;
	--from) FROM=$2; shift ;; # a directory with the downloads, for servers without internet access
	--yes) YES=1 ;;
	--uninstall) UNINSTALL=1 ;;
	*) die "unknown option $1 (see the comments at the top of this file)" ;;
	esac
	shift
done

[ "$(id -u)" = 0 ] || die "run it as root (sudo sh install.sh ...)"
[ "$(uname -s)" = Linux ] || die "the agent runs on Linux only"

uninstall() {
	bold "Removing the Vulnpocalypse agent:"
	if [ -f "$UNIT.timer" ]; then
		run systemctl disable --now vulnpocalypse-agent.timer || true
		run rm -f "$UNIT.timer" "$UNIT.service"
		run systemctl daemon-reload || true
	fi
	[ -f "$CRON_D" ] && run rm -f "$CRON_D"
	if [ -f "$CRONTAB" ] && grep -q '# vulnpocalypse-agent$' "$CRONTAB"; then
		say "+ remove the vulnpocalypse-agent line from $CRONTAB"
		grep -v '# vulnpocalypse-agent$' "$CRONTAB" >"$CRONTAB.new" || true
		cat "$CRONTAB.new" >"$CRONTAB" && rm -f "$CRONTAB.new"
	fi
	for d in "$LIB" "$CONF_DIR" "$STATE"; do [ -e "$d" ] && run rm -rf "$d"; done
	if id "$SYSUSER" >/dev/null 2>&1; then
		if has userdel; then run userdel "$SYSUSER" || true; else run deluser "$SYSUSER" || true; fi
		if grep -q "^$SYSUSER:" /etc/group && has delgroup; then run delgroup "$SYSUSER" || true; fi
	fi
	if has docker && docker image inspect "$IMAGE" >/dev/null 2>&1; then run docker rmi "$IMAGE" || true; fi
	ok "The agent is removed. To erase its data on our side, delete the server in the dashboard."
}
if [ -n "$UNINSTALL" ]; then uninstall; exit 0; fi

# the key: from a file, standard input, VULNPOCALYPSE_KEY or the terminal
if [ "$KEY_FROM" = stdin ]; then
	IFS= read -r KEY || [ -n "$KEY" ] || die "--key -: standard input is empty"
elif [ -n "$KEY_FROM" ]; then
	[ -r "$KEY_FROM" ] || die "--key-file: cannot read $KEY_FROM"
	KEY=$(head -n 1 "$KEY_FROM")
elif [ -z "$KEY" ] && [ -t 0 ]; then
	printf '%sAgent key (Keys page of the dashboard; the input is not shown):%s ' "$BOLD" "$OFF"
	stty -echo 2>/dev/null || true
	IFS= read -r KEY || true
	stty echo 2>/dev/null || true
	say ""
fi
KEY=$(printf %s "$KEY" | tr -d '\r\n ')
[ -n "$KEY" ] || die "the agent key is missing: create one on the Keys page of the dashboard, then run this again on a terminal, or use --key-file FILE, --key - or VULNPOCALYPSE_KEY"
case $KEY in *[!A-Za-z0-9_-]*) die "the key has characters other than letters, digits, _ and -" ;; esac
case $(uname -m) in
x86_64 | amd64) ARCH=amd64 ;;
aarch64 | arm64) ARCH=arm64 ;;
*) die "the architecture $(uname -m) is not supported (amd64 and arm64 are)" ;;
esac
for tool in sed awk mktemp od; do has $tool || die "$tool is missing"; done

# the server name in the dashboard: asked on a terminal (the host name is the
# suggestion); without a terminal server-<6 random hex digits>, so the host
# name is sent only when you choose it
if [ -z "$NAME" ] && [ -t 0 ]; then
	host=$(uname -n)
	printf '%sServer name in the dashboard [%s]:%s ' "$BOLD" "$host" "$OFF"
	IFS= read -r NAME || true
	[ -n "$NAME" ] || NAME=$host
fi
[ -n "$NAME" ] || NAME=server-$(od -An -N3 -tx1 /dev/urandom | tr -d ' \n')
# one line each in agent.conf
NAME=$(printf %s "$NAME" | tr -d '\r\n') PATHS=$(printf %s "$PATHS" | tr -d '\r\n') IMAGES=$(printf %s "$IMAGES" | tr -d '\r\n')

if [ -z "$MODE" ]; then
	if has docker && docker info >/dev/null 2>&1; then MODE=docker; else MODE=binary; fi
fi
bold "Installing the Vulnpocalypse agent $VERSION in $MODE mode as \"$NAME\"."
# the downloads and the output of run_step
tmp=$(mktemp -d) && trap 'rm -rf "$tmp"' EXIT

# fetch NAME URL SHA256: copy from --from or download, then check the sum
fetch() {
	if [ -n "$FROM" ]; then
		run cp "$FROM/$1" "$tmp/$1"
	elif has curl; then
		run_step "Downloading $1" curl -fsSL --proto =https -o "$tmp/$1" "$2"
	elif has wget; then
		run_step "Downloading $1" wget -q --https-only -O "$tmp/$1" "$2"
	else
		die "curl or wget is needed to download $2"
	fi
	got=$(sha256sum "$tmp/$1" | awk '{ print $1 }')
	[ "$got" = "$3" ] || die "$1: SHA-256 is $got, expected $3; nothing was installed"
	ok "SHA-256 of $1 is correct ($3)"
}

# Docker mode: the image by digest. Binary mode: the agent and Trivy, checked
# before anything is installed, and the user of the unprivileged steps.
if [ "$MODE" = docker ]; then
	printf %s "$IMAGE" | grep -Eq '@sha256:[0-9a-f]{64}$' || die "the image $IMAGE is not pinned by its digest; nothing was installed"
	run_step "Pulling the agent image" docker pull "$IMAGE"
	ok "pulled by its digest ${IMAGE#*@}; Docker checks the content against it"
else
	has sha256sum || die "sha256sum is missing"
	agent=vulnpocalypse-agent-$VERSION-linux-$ARCH
	if [ "$ARCH" = arm64 ]; then
		agent_sum=$AGENT_SHA256_arm64 trivy_sum=$TRIVY_SHA256_arm64 tgz=trivy_${TRIVY_VERSION}_Linux-ARM64.tar.gz
	else
		agent_sum=$AGENT_SHA256_amd64 trivy_sum=$TRIVY_SHA256_amd64 tgz=trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz
	fi
	fetch "$agent" "$DOWNLOAD/$VERSION/$agent" "$agent_sum"
	fetch "$tgz" "https://github.com/aquasecurity/trivy/releases/download/v$TRIVY_VERSION/$tgz" "$trivy_sum"
	run tar -xzf "$tmp/$tgz" -C "$tmp" trivy
	run mkdir -p "$LIB"
	run install -m 755 "$tmp/$agent" "$LIB/vulnpocalypse-agent"
	run install -m 755 "$tmp/trivy" "$LIB/trivy"
	if ! id "$SYSUSER" >/dev/null 2>&1; then
		if has useradd; then
			run useradd --system --user-group --no-create-home --home-dir /nonexistent --shell /sbin/nologin "$SYSUSER"
		elif has adduser; then # busybox (Alpine)
			run addgroup -S "$SYSUSER"
			run adduser -S -D -H -h /nonexistent -s /sbin/nologin -G "$SYSUSER" "$SYSUSER"
		else
			say "useradd and adduser are missing; the image and report steps run as nobody"
		fi
	fi
fi
run mkdir -p "$LIB" "$CONF_DIR"
run mkdir -p -m 700 "$STATE"

write "$CONF_DIR/agent.conf" 600 <<EOF
# Vulnpocalypse agent settings. The agent reads KEY=value lines; a shell does not run this file.
# KEY: agent key (upload only). URL: the service. NAME: the server name in the dashboard.
# PATHS: app directories whose lockfiles are scanned. IMAGES: all, none or a list of images.
# EXCLUDE_IMAGES: images that are not scanned. MODE: docker or binary.
KEY=$KEY
URL=$URL
NAME=$NAME
MODE=$MODE
PATHS=$PATHS
IMAGES=$IMAGES
EXCLUDE_IMAGES=
EOF
if [ ! -s "$CONF_DIR/server-id" ]; then
	id=$(cat /proc/sys/kernel/random/uuid)
	say "$id" | write "$CONF_DIR/server-id" 644
fi

write "$LIB/run.sh" 755 <<'RUN_SH'
#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
# Vulnpocalypse agent wrapper, /usr/local/lib/vulnpocalypse/run.sh (written by install.sh).
# The daily timer runs "run.sh send". By hand:
#   run.sh scan --dry-run      collect and print the payload; nothing is sent
#   run.sh scan --output FILE  also write the payload to FILE
#   run.sh checks              the local checks only
#   --explain                  print each step as it happens
# A run has four parts. This script, as root, runs a few read-only commands
# and docker save, and keeps their output in /var/lib/vulnpocalypse/work (mode
# 700, removed at the end). Then three steps, each its own process (its own
# container in Docker mode), so no step both reads the host and reads image
# content or talks to the network:
#   1. host step: reads the host files, read-only, without network
#   2. image step: reads only the saved images, as an unprivileged user,
#      without network, with memory and time limits
#   3. report step: reads only the results of steps 1 and 2, as an
#      unprivileged user; it prints the summary and, for send, sends them
set -u
umask 077
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
LIB=/usr/local/lib/vulnpocalypse
# the VULNPOCALYPSE_* variables change paths and names for tests
CONF=${VULNPOCALYPSE_CONF:-/etc/vulnpocalypse/agent.conf}
STATE=${VULNPOCALYPSE_STATE:-/var/lib/vulnpocalypse}
# Docker mode: the agent image by its digest, so the registry cannot hand out
# other content. agent/build.sh writes the digest at release; the registry
# name registry.invalid is a placeholder until the image is published.
IMAGE=${VULNPOCALYPSE_IMAGE:-ghcr.io/cdutsov/vulnpocalypse/agent:0.2.2@sha256:638fa6d29e1207057b225e81033c478d021119bc3bceb06e7449d0ad8d723924}
CONTAINER=${VULNPOCALYPSE_CONTAINER:-vulnpocalypse-agent}
setting() { sed -n "s/^$1=//p" "$CONF" 2>/dev/null | tail -n 1 | tr -d "\"'"; }
has() { command -v "$1" >/dev/null 2>&1; }

# Colors and a spinner for a person at a terminal; plain text for the daily
# timer, pipes, NO_COLOR, TERM=dumb and VULNPOCALYPSE_COLOR=0. VULNPOCALYPSE_COLOR=1
# (or ascii) turns them on. The agent steps get VULNPOCALYPSE_COLOR, as they
# cannot see the terminal from their containers.
UI=""
case ${VULNPOCALYPSE_COLOR:-} in
0 | never) ;;
1 | always | ascii) UI=1 ;;
*) [ -t 1 ] && [ -t 2 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ] && UI=1 ;;
esac
DIM="" RED="" GREEN="" CYAN="" OFF="" OK="" NOK="" FRAMES="" E=""
if [ -n "$UI" ]; then
	E=$(printf '\033')
	DIM="${E}[2m" RED="${E}[1;31m" GREEN="${E}[32m" CYAN="${E}[36m" OFF="${E}[0m"
	# Unicode signs, or ASCII when the locale is not UTF-8 or on the Linux console
	case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in *[Uu][Tt][Ff]-8* | *[Uu][Tt][Ff]8* | "") ascii="" ;; *) ascii=1 ;; esac
	[ "${TERM:-}" = linux ] || [ "${VULNPOCALYPSE_COLOR:-}" = ascii ] && ascii=1
	if [ -n "$ascii" ]; then
		OK=ok NOK=x FRAMES='- \ | /' VULNPOCALYPSE_COLOR=ascii
	else
		OK='✓' NOK='✗' FRAMES='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏' VULNPOCALYPSE_COLOR=1
	fi
else
	VULNPOCALYPSE_COLOR=0
fi
export VULNPOCALYPSE_COLOR
die() { printf '%srun.sh: %s%s\n' "$RED" "$*" "$OFF" >&2; exit 1; }

# spin LABEL: a turning sign, LABEL and the seconds so far on stderr, until it
# is killed; it ends by itself when run.sh is gone
spin() {
	sp_t0=$(date +%s)
	printf '%s' "${E}[?25l" >&2
	while kill -0 $$ 2>/dev/null; do
		for f in $FRAMES; do
			printf '\r  %s%s%s %s %s%ss%s%s' "$CYAN" "$f" "$OFF" "$1" "$DIM" $(($(date +%s) - sp_t0)) "$OFF" "${E}[K" >&2
			sleep 0.1 2>/dev/null || sleep 1
		done
	done
	printf '\r%s%s' "${E}[K" "${E}[?25h" >&2
}
# step LABEL DONE CMD...: runs CMD. On a terminal the spinner shows LABEL
# meanwhile, and DONE stays as a line with the time it took (an empty DONE
# leaves no line); the stderr of CMD waits in a file until then.
spid=""
step() {
	st_label=$1 st_done=$2
	shift 2
	if [ -z "$UI" ] || [ -n "$explain" ]; then
		"$@"
		return
	fi
	st_t0=$(date +%s)
	spin "$st_label" &
	spid=$!
	"$@" 2>"$W/step.err" && st_rc=0 || st_rc=$?
	kill "$spid" 2>/dev/null
	wait "$spid" 2>/dev/null
	spid=""
	printf '\r%s%s' "${E}[K" "${E}[?25h" >&2
	if [ "$st_rc" != 0 ]; then
		printf '  %s%s %s%s\n' "$RED" "$NOK" "$st_label" "$OFF" >&2
	elif [ -n "$st_done" ]; then
		done_line "$st_done" $(($(date +%s) - st_t0))
	fi
	cat "$W/step.err" >&2
	return "$st_rc"
}
# done_line TEXT SECONDS
done_line() {
	if [ -n "$UI" ]; then printf '  %s%s%s %s %s%ss%s\n' "$GREEN" "$OK" "$OFF" "$1" "$DIM" "$2" "$OFF" >&2; fi
}

cmd=${1:-}
[ $# -gt 0 ] && shift
case $cmd in scan | send | checks) ;; *) die "usage: run.sh scan|send|checks [--dry-run] [--explain] [--output FILE]" ;; esac
dry="" explain="" output=""
while [ $# -gt 0 ]; do
	case $1 in
	--dry-run) dry=--dry-run ;;
	--explain) explain=--explain ;;
	--output) [ $# -gt 1 ] || die "--output needs a file name"; output=$2; shift ;;
	*) die "unknown option $1" ;;
	esac
	shift
done
[ "$(id -u)" = 0 ] || die "run it as root (sudo)"

# agent.conf holds the key and the URL: only root may change it
conf=""
if [ -f "$CONF" ]; then
	# shellcheck disable=SC2046 # owner and mode as $1 and $2
	set -- $(stat -L -c '%u %a' "$CONF")
	[ "${1:-}" = 0 ] || die "$CONF is not owned by root: chown root:root $CONF and check its content"
	case ${2:-} in *[2367]? | *[2367]) die "group or others may write $CONF: chmod 600 $CONF and check its content" ;; esac
	case ${2:-} in *[1-7]? | *[1-7]) chmod 600 "$CONF" && echo "run.sh: $CONF was readable by group or others, set to mode 600" >&2 ;; esac
	conf=--config
fi
MODE=$(setting MODE) IMAGES=$(setting IMAGES) PATHS=$(setting PATHS | tr ',' ' ')
# without agent.conf (a try-once run): Docker when it runs, else the binary
if [ -z "$MODE" ]; then
	if has docker && docker info >/dev/null 2>&1; then MODE=docker; else MODE=binary; fi
fi
EXCLUDE=" $(setting EXCLUDE_IMAGES | tr ',' ' ') "
if [ "$MODE" = docker ]; then
	printf %s "$IMAGE" | grep -Eq '@sha256:[0-9a-f]{64}$' ||
		die "the agent image $IMAGE is not pinned by its digest (@sha256:...); it is not started"
fi

# one run at a time; the work directory of a run that was killed is removed
made_state=""
[ -d "$STATE" ] || { mkdir -p "$STATE" && made_state=1; }
if has flock; then
	exec 9>"$STATE/run.lock"
	flock -n 9 || die "another run is in progress ($STATE/run.lock)"
fi
W=$STATE/work H=$STATE/work/host
# shellcheck disable=SC2317 # called by the trap
cleanup() {
	if [ -n "$spid" ]; then
		kill "$spid" 2>/dev/null
		printf '\r%s%s' "${E}[K" "${E}[?25h" >&2
	fi
	rm -rf "$W"
	if [ -n "$made_state" ]; then rm -f "$STATE/run.lock" && rmdir "$STATE" 2>/dev/null; fi
}
trap cleanup EXIT
trap 'exit 1' INT TERM HUP
rm -rf "$W"
mkdir -p "$H/images" "$W/host-tmp" "$W/images" "$W/keep" "$W/tmp" || exit 1
: >"$W/images.json"
# the unprivileged user of steps 2 and 3: in the containers 65534 (nobody);
# in binary mode the user vulnpocalypse that install.sh makes (else nobody),
# which may pass through /var/lib/vulnpocalypse and the work directory (mode 710)
if [ "$MODE" = docker ]; then
	SUSER=65534 SUID=65534 SGID=65534
	docker rm -f "$CONTAINER-host" "$CONTAINER-images" "$CONTAINER-report" >/dev/null 2>&1
else
	SUSER=vulnpocalypse
	id "$SUSER" >/dev/null 2>&1 || SUSER=nobody
	SUID=$(id -u "$SUSER") SGID=$(id -g "$SUSER")
	chgrp "$SGID" "$STATE" "$W" && chmod 710 "$STATE" "$W"
fi
chgrp "$SGID" "$W/images" "$W/keep" "$W/tmp" && chmod 750 "$W/images" && chmod 770 "$W/keep" "$W/tmp"

# --- what the agent cannot read from files, into $H (root only)
# shellcheck disable=SC2317 # called by step
read_host() {
	# effective sshd settings, after Include files and defaults; RHEL 8 starts
	# sshd with its crypto policy as options (CRYPTO_POLICY), so they are added
	# here as the service adds them (read with sed, not run as shell code)
	policy=$(sed -n "s/^CRYPTO_POLICY=['\"]\{0,1\}\([^'\"]*\)['\"]\{0,1\}\$/\1/p" \
		/etc/crypto-policies/back-ends/opensshserver.config /etc/sysconfig/sshd 2>/dev/null | tail -n 1)
	# shellcheck disable=SC2086 # the policy is a list of -o options
	has sshd && sshd -T $policy >"$H/sshd-t.txt" 2>/dev/null
	# firewall rules: the agent sends only whether incoming traffic is filtered
	has nft && nft list ruleset >"$H/nft.txt" 2>/dev/null
	has iptables-save && iptables-save >"$H/iptables.txt" 2>/dev/null
	# listening sockets with process names (a container cannot see the names)
	has ss && ss -Hltunpe >"$H/ss.txt" 2>/dev/null
	# upgradable packages from the local package lists: no download, no lock
	if has apt-get; then
		apt-get -s -o Debug::NoLocking=1 dist-upgrade >"$H/apt-upgrade.txt" 2>/dev/null
	elif has dnf; then
		dnf -C -q check-update >"$H/dnf-check-update.txt" 2>/dev/null
		dnf -C -q updateinfo list --security >"$H/dnf-security.txt" 2>/dev/null
	elif has apk; then
		apk version -l '<' >"$H/apk-version.txt" 2>/dev/null
	fi
	# the reboot flag of Debian and Ubuntu (the container does not mount /run)
	cp /run/reboot-required /run/reboot-required.pkgs "$H/" 2>/dev/null
	return 0
}
step "Reading the settings of the host" "Settings of the host" read_host

# Docker: settings of the running containers (only the fields the checks
# read, no environment variables), and their images as tar files in $W/images
docker_ok=""
if has docker && docker info >/dev/null 2>"$H/docker-error.txt"; then
	docker_ok=1
	rm -f "$H/docker-error.txt"
	ids=$(docker ps -q)
	f='{"Name":{{json .Name}},"Image":{{json .Image}},"Config":{"Image":{{json .Config.Image}},"User":{{json .Config.User}}},'
	f=$f'"HostConfig":{"Privileged":{{json .HostConfig.Privileged}},"NetworkMode":{{json .HostConfig.NetworkMode}},"PidMode":{{json .HostConfig.PidMode}},'
	f=$f'"CapAdd":{{json .HostConfig.CapAdd}},"UsernsMode":{{json .HostConfig.UsernsMode}}},"State":{"Pid":{{json .State.Pid}}},'
	f=$f'"Mounts":{{json .Mounts}},"NetworkSettings":{"Ports":{{json .NetworkSettings.Ports}}}}'
	# shellcheck disable=SC2086 # one argument per container id
	if [ -n "$ids" ]; then docker inspect --format "$f" $ids | sed '1s/^/[/; $!s/$/,/; $s/$/]/' >"$H/containers.json"; else echo '[]' >"$H/containers.json"; fi
	docker info --format '{{json .SecurityOptions}}' >"$H/docker-security.json" 2>/dev/null
elif has dockerd || [ -S /var/run/docker.sock ]; then
	# Docker is installed but does not answer: the report says so, and the
	# images of the last run are sent with this error (their findings stay)
	[ -s "$H/docker-error.txt" ] || echo "docker info failed" >"$H/docker-error.txt"
else
	rm -f "$H/docker-error.txt"
fi
if [ -n "$docker_ok" ] || [ -f "$H/docker-error.txt" ]; then
	case ${IMAGES:-all} in
	all) if [ -n "$docker_ok" ]; then list=$(docker ps --format '{{.Image}}' | sort -u); else list=$(cat "$STATE/images.txt" 2>/dev/null); fi ;;
	none) list= ;;
	*) list=$(echo "$IMAGES" | tr ',' ' ') ;;
	esac
	[ "$cmd" = checks ] && list= # the checks do not need the images
	[ -n "$docker_ok" ] && [ "${IMAGES:-all}" = all ] && [ "$cmd" != checks ] && printf '%s\n' "$list" >"$STATE/images.txt"
	# save_image N IMAGE: the image as a tar file for the image step
	# shellcheck disable=SC2317 # called by step
	save_image() { docker save -o "$W/images/$1.tar" "$2" 2>"$H/images/$1.err"; }
	total=0
	for img in $list; do
		case $EXCLUDE in *" $img "*) ;; *) total=$((total + 1)) ;; esac
	done
	n=0 t0=$(date +%s)
	for img in $list; do
		case $EXCLUDE in *" $img "*) continue ;; esac
		n=$((n + 1))
		printf '%s\t%s\n' "$n" "$img" >>"$H/images/list.txt"
		if [ -z "$docker_ok" ]; then
			cp "$H/docker-error.txt" "$H/images/$n.err"
			continue
		fi
		docker image inspect --format '[{"Id":{{json .Id}},"Created":{{json .Created}},"RepoDigests":{{json .RepoDigests}}}]' "$img" >"$H/images/$n.json" 2>/dev/null
		# keep 2 GB free on the disk of the work directory
		size=$(docker image inspect -f '{{.Size}}' "$img" 2>/dev/null || echo 0)
		free=$(df -Pk "$W" | awk 'NR == 2 { print $4 }')
		if [ $((size / 1024 + 2097152)) -gt "$free" ]; then
			echo "not enough disk space for docker save in $W" >"$H/images/$n.err"
		elif step "Saving image $n of $total: $img" "" save_image "$n" "$img"; then
			rm -f "$H/images/$n.err"
		else
			rm -f "$W/images/$n.tar"
			[ -s "$H/images/$n.err" ] || echo "docker save failed" >"$H/images/$n.err"
		fi
	done
	if [ -n "$docker_ok" ] && [ "$n" -gt 0 ]; then
		saved=$(find "$W/images" -name '*.tar' | wc -l | tr -d ' ')
		done_line "Images saved for the scan: $saved of $n" $(($(date +%s) - t0))
	fi
	cp "$H/images/list.txt" "$W/images/" 2>/dev/null
	chgrp -R "$SGID" "$W/images" && chmod -R g+rX "$W/images"
fi

# as_user CMD...: steps 2 and 3 of binary mode, as $SUSER, with at most 4 GB
# of address space and 1 hour of CPU time (the agent stops itself at --time-limit)
as_user() {
	(
		# shellcheck disable=SC3045 # dash, bash and busybox sh have -v and -t
		ulimit -v 4194304
		# shellcheck disable=SC3045
		ulimit -t 3600
		TMPDIR=$W/tmp HOME=$W/tmp
		export TMPDIR HOME
		if setpriv --help 2>&1 | grep -q -- --reuid; then
			exec nice -n 10 setpriv --reuid="$SUID" --regid="$SGID" --clear-groups --no-new-privs -- "$@"
		elif has su; then # busybox (Alpine)
			# shellcheck disable=SC2016 # expanded by the shell of su
			exec nice -n 10 su -s /bin/sh -c 'exec "$0" "$@"' -- "$SUSER" "$@"
		fi
		echo "run.sh: setpriv and su are missing; this step runs as root" >&2
		exec nice -n 10 "$@"
	)
}

# what the spinner says while the agent steps run
if [ "$cmd" = checks ]; then
	label1="Running the checks" done1="Checks"
else
	label1="Listing the packages of the host and running the checks" done1="Packages of the host and checks"
fi
nimg=0
[ -s "$W/images/list.txt" ] && nimg=$(wc -l <"$W/images/list.txt" | tr -d ' ')
label2="Listing the packages of $nimg images" done2="Packages of $nimg images"
[ "$nimg" = 1 ] && label2="Listing the packages of 1 image" done2="Packages of 1 image"

if [ "$MODE" = docker ]; then
	docker image inspect "$IMAGE" >/dev/null 2>&1 ||
		step "Pulling the agent image" "Agent image pulled by its digest" docker pull -q "$IMAGE" >/dev/null ||
		die "could not pull the agent image $IMAGE"

	# --- 1. host step: the host read-only, no network, root with only the
	# right to read any file (DAC_READ_SEARCH: /etc/shadow, package files)
	m=""
	# agent.conf: key, URL, server name, app paths
	[ -n "$conf" ] && m="$m -v $CONF:/config/agent.conf:ro" && conf="--config /config/agent.conf"
	# release files, server-id, sshd, accounts, sudo, updates and firewall settings
	m="$m -v /etc:/host/etc:ro"
	# installed programs and libraries (host package list) and kernels
	m="$m -v /usr:/host/usr:ro"
	# listening sockets, process names, kernel settings, uptime
	m="$m -v /proc:/host/proc:ro"
	# AppArmor or SELinux state, virtualization (DMI vendor and product)
	m="$m -v /sys:/host/sys:ro"
	# package databases and kernels outside /usr
	for d in /var/lib/dpkg /var/lib/rpm /lib/apk/db /lib/modules; do
		[ -d "$d" ] && [ "$(readlink -f "$d")" = "$d" ] && m="$m -v $d:/host$d:ro"
	done
	# app directories of PATHS (the agent reads their lockfiles)
	for d in $PATHS; do [ -d "$d" ] && m="$m -v $d:/host$d:ro"; done
	# the output of the commands above (not the images)
	m="$m -v $H:/input:ro"
	step1=host
	[ "$cmd" = checks ] && step1=checks
	# shellcheck disable=SC2317 # called by step
	host_step() {
		# shellcheck disable=SC2086 # $m holds the mounts, paths without spaces
		docker run --rm --name "$CONTAINER-host" --network none \
			--cpus 1 --memory 1g --cpu-shares 256 --pids-limit 200 \
			--read-only --tmpfs /tmp:size=1g --cap-drop ALL --cap-add DAC_READ_SEARCH \
			--security-opt no-new-privileges -e VULNPOCALYPSE_COLOR \
			$m "$IMAGE" $step1 $explain $conf --mode docker --root /host --input /input --time-limit 30m >"$W/host.json"
	}
	step "$label1" "$done1" host_step || die "the host step failed"
	[ "$cmd" = checks ] && { cat "$W/host.json"; exit 0; }

	# --- 2. image step: only the saved images, read-only; user nobody, no
	# capabilities, no network
	# shellcheck disable=SC2317 # called by step
	images_step() {
		# shellcheck disable=SC2086
		docker run --rm --name "$CONTAINER-images" --network none --user 65534:65534 \
			--cpus 1 --memory 1g --cpu-shares 256 --pids-limit 200 \
			--read-only --tmpfs /tmp:size=1g --cap-drop ALL --security-opt no-new-privileges \
			-v "$W/images:/images:ro" "$IMAGE" images $explain --input /images --time-limit 1h >"$W/images.json"
	}
	if [ -s "$W/images/list.txt" ]; then
		step "$label2" "$done2" images_step ||
			echo "run.sh: the image step failed; the report lists the images without packages" >&2
	fi
	if [ -n "$UI" ] && [ -z "$explain" ]; then echo >&2; fi

	# --- 3. report step: the results of steps 1 and 2 on stdin; user nobody,
	# no capabilities, no host files; network only for send
	net=none
	[ "$cmd" = send ] && [ -z "$dry" ] && net=bridge
	out=""
	[ -n "$output" ] && out="--output /keep/payload.json"
	# shellcheck disable=SC2086
	cat "$W/host.json" "$W/images.json" | docker run --rm -i --name "$CONTAINER-report" --network "$net" --user 65534:65534 \
		--cpus 1 --memory 512m --cpu-shares 256 --pids-limit 100 \
		--read-only --tmpfs /tmp:size=64m --cap-drop ALL --security-opt no-new-privileges \
		-e HTTPS_PROXY -e https_proxy -e NO_PROXY -e no_proxy -e VULNPOCALYPSE_COLOR \
		-v "$W/keep:/keep" "$IMAGE" report "$cmd" $dry $explain $out --state /keep --time-limit 30m
	rc=$?
else
	# --- 1. host step: root, reads the host files (no network use)
	[ -n "$conf" ] && conf="--config $CONF"
	step1=host
	[ "$cmd" = checks ] && step1=checks
	# shellcheck disable=SC2317 # called by step
	host_step() {
		# shellcheck disable=SC2086
		TMPDIR=$W/host-tmp nice -n 10 "$LIB/vulnpocalypse-agent" $step1 $explain $conf --mode binary --root / --input "$H" \
			--trivy "$LIB/trivy" --time-limit 30m >"$W/host.json"
	}
	step "$label1" "$done1" host_step || die "the host step failed"
	[ "$cmd" = checks ] && { cat "$W/host.json"; exit 0; }

	# --- 2. image step: only the saved images, as $SUSER
	# shellcheck disable=SC2317 # called by step
	images_step() {
		# shellcheck disable=SC2086
		as_user "$LIB/vulnpocalypse-agent" images $explain --input "$W/images" --trivy "$LIB/trivy" --time-limit 1h >"$W/images.json"
	}
	if [ -s "$W/images/list.txt" ]; then
		step "$label2" "$done2" images_step ||
			echo "run.sh: the image step failed; the report lists the images without packages" >&2
	fi
	if [ -n "$UI" ] && [ -z "$explain" ]; then echo >&2; fi

	# --- 3. report step: the results of steps 1 and 2 on stdin, as $SUSER
	out=""
	[ -n "$output" ] && out="--output $W/keep/payload.json"
	# shellcheck disable=SC2086
	cat "$W/host.json" "$W/images.json" | as_user "$LIB/vulnpocalypse-agent" report "$cmd" $dry $explain $out --state "$W/keep" --time-limit 30m
	rc=$?
fi

# the copies of the last payload and answer (send), and --output
for f in last-payload.json.gz last-response.json; do
	if [ -f "$W/keep/$f" ] && [ ! -h "$W/keep/$f" ]; then cat "$W/keep/$f" >"$STATE/$f"; fi
done
if [ -n "$output" ]; then
	if [ -f "$W/keep/payload.json" ] && [ ! -h "$W/keep/payload.json" ]; then cat "$W/keep/payload.json" >"$output"; fi
fi
exit $rc
RUN_SH

# once a day at a random time between 01:00 and 05:59 (local time)
r=$(($(random) % 300))
hour=$((1 + r / 60)) minute=$((r % 60))
if [ -d /run/systemd/system ]; then
	# the limits apply to run.sh and, in binary mode, to the agent steps
	write "$UNIT.service" 644 <<EOF
[Unit]
Description=Vulnpocalypse agent: send the daily security report
After=network-online.target docker.service
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=$LIB/run.sh send
Nice=10
IOSchedulingClass=idle
TimeoutStartSec=3h
MemoryMax=2G
CPUQuota=100%
NoNewPrivileges=yes
ProtectSystem=full
ProtectHome=read-only
PrivateTmp=yes
ProtectKernelTunables=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
EOF
	write "$UNIT.timer" 644 <<EOF
[Unit]
Description=Vulnpocalypse agent, once a day

[Timer]
OnCalendar=*-*-* $hour:$minute:00
RandomizedDelaySec=10min
Persistent=true

[Install]
WantedBy=timers.target
EOF
	run systemctl daemon-reload
	run systemctl enable --now vulnpocalypse-agent.timer
	when="the timer vulnpocalypse-agent.timer (systemctl list-timers vulnpocalypse-agent.timer)"
elif { has cron || has crond; } && [ -d /etc/cron.d ]; then
	say "$minute $hour * * * root $LIB/run.sh send >/dev/null 2>&1" | write "$CRON_D" 644
	when="cron ($CRON_D)"
elif has crond && [ -f "$CRONTAB" ]; then # busybox crond (Alpine)
	say "+ add a line to $CRONTAB"
	say "$minute $hour * * * $LIB/run.sh send >/dev/null 2>&1 # vulnpocalypse-agent" >>"$CRONTAB"
	when="cron ($CRONTAB)"
else
	when=""
	say "There is no systemd and no cron here: run $LIB/run.sh send once a day yourself."
fi

say ""
bold "First run, nothing is sent:"
run "$LIB/run.sh" scan || say "The scan failed; the output above says why."
say ""
say "Files: $CONF_DIR/agent.conf, $CONF_DIR/server-id, $LIB/, $STATE/"
hint "To see the payload before it is sent: " "sudo $LIB/run.sh scan --dry-run"
send=""
if [ -n "$YES" ]; then
	send=1
elif [ -t 0 ]; then
	printf '%sSend the first report now? [y/N]%s ' "$BOLD" "$OFF"
	read -r answer || answer=""
	case $answer in y | Y | yes) send=1 ;; esac
fi
if [ -n "$send" ]; then
	run "$LIB/run.sh" send
elif [ -t 0 ]; then
	hint "Not sent now. The first report goes out with ${when:-your daily run} at $hour:$(printf %02d "$minute"). To send it now: " "sudo $LIB/run.sh send"
else
	say "Not sent now: without a terminal, install.sh sends the first report only with --yes."
	[ -n "$when" ] && say "The first report goes out with $when at $hour:$(printf %02d "$minute")."
	hint "To send it now: " "sudo $LIB/run.sh send"
fi
hint "To remove the agent: " "sudo sh install.sh --uninstall"
