#!/bin/bash
# Detects changes to the boot chain (docs/SICHERHEIT.md, "Manipulation erkennen").
# The bootloader stays unlocked: whoever holds the phone can swap kernel and initramfs,
# e.g. to capture the encryption password. That cannot be prevented, but it is noticed
# after the next boot.
#
# Only what starts this installation is judged: the partitions of the active slot (the other
# slot holds the Volla OS of the delivery) and, on a boot menu card, the entries that start the
# system on the phone's storage. An Arch on card partitions (Plinius Boot) also has its own
# entries judged: those whose command line names its partition as the running start does
# (systempart=, or datapart= alone for a system in rootfs.img on its data partition), with the
# trial and fallback entries plinius-kernel-install makes from it. Entries of other systems on
# card partitions are left alone.
#
# Usage: plinius-bootcheck check | accept [--written] [PATH...] | forget | status
#   check   compare checksums with the reference state (plinius-bootcheck.service at boot).
#           New list entries are recorded without an alarm, dropped ones removed silently.
#           Exception: a new own entry on the boot menu card raises the alarm, since it would
#           start this system with a kernel and ramdisk of its own.
#   accept  take the current state as reference; without PATH for all entries (as root).
#           Packages that write boot partitions call this only for their own paths, with
#           --written: then a path that this start already reported as changed is kept as an
#           alarm (the changed content has run), the user confirms it.
#           "abm-entry:NAME" stands for the card entry NAME with the files it names.
#           Entries the lists no longer name leave the reference, as at "check".
#   forget  only that: a package removed own entries (a trial entry on the card once its
#           start was confirmed). Else the copy in the LUKS2 header kept them until the next
#           "check", and the password prompt of the next start reported them as changed.
#   status  result of the last check
# Exit status: 0 unchanged, 1 error, 2 changed
#
# What is checked is defined by the lists in /usr/lib/plinius-bootcheck.d/*.list (device
# package): one path per line (file or block device), shell globs allowed, "#" for comments.
# "@slot" in a path is the active slot's suffix (_a or _b). A line "abm DEVICE" names the
# partition of the boot menu (Android Boot Manager); its own entries count as "abm:/PATH".
#
# On an encrypted system the reference also goes into the LUKS2 header, as token TOKEN_ID: the
# password prompt of plinius-crypt (hook, bootcheck_begin) compares the boot chain with it before
# the password is typed and warns of a change. That copy can be forged without the password, so
# "check" compares it with the encrypted reference here. Two findings of "check" are no paths of
# the lists, they stay until accepted ("accept" with them, or without paths):
#   luks:token      the copy in the LUKS2 header differs from the reference, or is gone
#   ramdisk:prompt  this start ran without the prompt's check (PROMPT_MARK), after one had run
set -euo pipefail

LISTS=/usr/lib/plinius-bootcheck.d
STATE=/var/lib/plinius-bootcheck
REF=$STATE/reference
RUN=/run/plinius-bootcheck
# The token's place in the LUKS2 header (the prompt reads the same one)
TOKEN_ID=31
# The mark the prompt leaves at every start of the encrypted system, carried over in /run
PROMPT_MARK=/run/plinius-crypt/prompt-check

die() { echo "plinius-bootcheck: $*" >&2; exit 1; }

# The active slot ("_a" or "_b"). A start from a card entry may come without bootconfig,
# so the slot of the last normal start is remembered.
slot() {
	local s
	s=$(sed -n 's/^androidboot.slot_suffix = "\(_[ab]\)"$/\1/p' /proc/bootconfig 2>/dev/null || true)
	if [[ $s == _[ab] ]]; then
		if [[ $(cat "$STATE/slot" 2>/dev/null) != "$s" && $(id -u) -eq 0 ]]; then
			install -d -m755 "$STATE"
			echo "$s" > "$STATE/slot.new" && mv -f "$STATE/slot.new" "$STATE/slot"
		fi
	else
		s=$(cat "$STATE/slot" 2>/dev/null || true)
	fi
	[[ $s == _[ab] ]] || return 1
	echo "$s"
}

# Fills "files" (paths from the lists; a glob without matches stays as a literal path, then
# counts as missing) and "card" (boot menu partition, empty without an abm line)
read_lists() {
	local list p rest s=
	files=() card=
	shopt -s nullglob
	for list in "$LISTS"/*.list; do
		while read -r p rest; do
			[[ -z $p || $p == \#* ]] && continue
			if [[ $p == abm ]]; then
				[[ -n $card ]] || card=${rest%%[[:space:]]*}
				continue
			fi
			if [[ $p == *@slot* ]]; then
				# Without the slot an unchecked entry would vanish from the reference: stop instead
				[[ -n $s ]] || s=$(slot) || die "active slot unknown (androidboot.slot_suffix in /proc/bootconfig)"
				p=${p//@slot/$s}
			fi
			# Unquoted: globs like lk_? are meant to expand
			# shellcheck disable=SC2206
			local m=($p)
			((${#m[@]})) || m=("$p")
			files+=("${m[@]}")
		done < "$list"
	done
	shopt -u nullglob
	((${#files[@]})) || return 0
	mapfile -t files < <(printf '%s\n' "${files[@]}" | sort -u)
}

# --- boot menu card, read with debugfs: no mount, read-only, the menu's files stay untouched ---
card_cat() { debugfs -c -R "cat $1" "$card" 2>/dev/null; }
card_has() { debugfs -c -R "stat $1" "$card" 2>/dev/null | grep -q '^Inode:'; }
card_ok() { [[ -n $card && -b $card ]] && card_has /db/entries; }

# The files an entry starts with (linux, initrd, dtb, logo; relative to the card's root)
entry_files() {
	awk '$1 == "linux" || $1 == "initrd" || $1 == "dtb" || $1 == "logo" { print "abm:/" $2 }'
}

# The word of the command line that names the card partition this system started from:
# systempart=, or datapart= alone for a system in rootfs.img on its data partition on the card.
# Empty for a system on the phone's storage, which names neither.
own_card_word() {
	local w sys= data=
	for w in $(cat /proc/cmdline 2>/dev/null); do
		case $w in
		systempart=?*) sys=$w ;;
		datapart=/dev/mmcblk*) data=$w ;;
		esac
	done
	echo "${sys:-$data}"
}

# Own entries start the system on the phone's storage: "xpart real" (plinius-kernel's trial and
# fallback entries) or no xpart at all (real.conf, which starts the active slot). Entries with
# "xpart N:M" start systems on card partitions and are only judged when this system is one of
# them: when their command line carries own_card_word. db/removed is not read.
# Prints "abm:/PATH" for each own entry file and the files it names.
card_paths() {
	local e conf xpart own
	own=$(own_card_word)
	while read -r e; do
		[[ $e == *.conf ]] || continue
		conf=$(card_cat "/db/entries/$e")
		xpart=$(awk '$1 == "xpart" { print $2; exit }' <<< "$conf")
		if [[ -n $xpart && $xpart != real ]]; then
			[[ -n $own ]] || continue
			awk -v w="$own" '$1 == "options" { for (i = 2; i <= NF; i++) if ($i == w) f = 1 }
				END { exit !f }' <<< "$conf" || continue
		fi
		echo "abm:/db/entries/$e"
		entry_files <<< "$conf"
	done < <(debugfs -c -R 'ls -p /db/entries' "$card" 2>/dev/null | cut -d/ -f6)
}

# All paths to check: the lists (read_lists first, in this shell, so that its errors stop the
# run), plus the own card entries when the card is there
all_paths() {
	{
		((${#files[@]} == 0)) || printf '%s\n' "${files[@]}"
		! card_ok || card_paths
	} | sort -u
}

# "HASH  PATH" per path; "-" for missing ones
hashes() {
	local p
	for p; do
		if [[ $p == abm:* ]]; then
			if card_has "${p#abm:}"; then
				printf '%s  %s\n' "$(card_cat "${p#abm:}" | sha256sum | cut -d' ' -f1)" "$p"
			else
				printf '%s  %s\n' - "$p"
			fi
		elif [[ -e $p ]]; then
			printf '%s  %s\n' "$(sha256sum < "$p" | cut -d' ' -f1)" "$p"
		else
			printf '%s  %s\n' - "$p"
		fi
	done
}

# --- the copy of the reference in the LUKS2 header (see the top) ---

# The LUKS2 device of the encrypted system: the data partition on the phone (plinius-data), the
# root file system in the VM (plinius-root). Fails on a system without encryption.
luks_dev() {
	local name dev
	command -v cryptsetup > /dev/null || return 1
	for name in plinius-data plinius-root; do
		dev=$(cryptsetup status "$name" 2>/dev/null | awk '$1 == "device:" { print $2; exit }')
		[[ -n $dev ]] && { echo "$dev"; return 0; }
	done
	return 1
}

# The token for the reference: what the prompt can read of it. Paths outside a plain set of
# characters stay out (the prompt parses it without a JSON parser); "check" judges them after
# the start as before.
token_json() {
	local c=$card
	[[ $c =~ ^[A-Za-z0-9_./@+-]*$ ]] || c=
	awk -v card="$c" '
		BEGIN { printf "{\"type\":\"plinius-bootcheck\",\"keyslots\":[],\"card\":\"%s\",\"entries\":[", card }
		NF == 2 && ($1 == "-" || $1 ~ /^[0-9a-f]{64}$/) && $2 ~ /^[A-Za-z0-9_.\/:@+-]+$/ {
			printf "%s\"%s %s\"", (n++ ? "," : ""), $1, $2 }
		END { print "]}" }' "$REF"
}

# A token on stdin as "card DEVICE" and its sorted entries, for comparing
token_norm() {
	local t
	t=$(cat)
	sed -n 's/.*"card": *"\([^"]*\)".*/card \1/p' <<< "$t"
	sed -n 's/.*"entries": *\[\([^]]*\)\].*/\1/p' <<< "$t" | tr ',' '\n' |
		sed -n 's/^ *"\(.*\)" *$/\1/p' | sort
}

# The token in the header of $1 on stdout; status 1 without one, 2 if another program's token is
# in its place
token_get() {
	local t
	t=$(cryptsetup token export --token-id "$TOKEN_ID" "$1" 2>/dev/null) || return 1
	grep -q '"type": *"plinius-bootcheck"' <<< "$t" || return 2
	printf '%s\n' "$t"
}

# Does the copy in the header of $1 match the reference? Also when it is missing and was never
# written, or when its last write did not finish (token-pending): "check" writes it then.
token_matches() {
	local have rc=0
	have=$(token_get "$1") || rc=$?
	if ((rc == 2)); then
		echo "plinius-bootcheck: token $TOKEN_ID of $1 belongs to another program, no copy of the reference" >&2
		return 0
	fi
	if [[ -e $STATE/token-pending ]]; then
		echo "plinius-bootcheck: the last write of the copy in the LUKS2 header did not finish, writing it anew"
		return 0
	fi
	if ((rc == 1)); then
		[[ -e $STATE/token-written ]] || return 0
		echo "plinius-bootcheck: the copy of the reference in the LUKS2 header of $1 is gone" >&2
		return 1
	fi
	[[ $(token_norm <<< "$have") == "$(token_json | token_norm)" ]] && return 0
	echo "plinius-bootcheck: the copy of the reference in the LUKS2 header of $1 was changed" >&2
	return 1
}

# Write the reference into the header of $1 unless it is there already
token_sync() {
	local want have rc=0
	want=$(token_json)
	have=$(token_get "$1") || rc=$?
	((rc != 2)) || return 0
	if ((rc == 0)) && [[ $(token_norm <<< "$have") == "$(token_norm <<< "$want")" ]]; then
		rm -f "$STATE/token-pending"
		touch "$STATE/token-written"
		return 0
	fi
	if cryptsetup token import --token-id "$TOKEN_ID" --token-replace --json-file - "$1" <<< "$want"; then
		rm -f "$STATE/token-pending"
		touch "$STATE/token-written"
		echo "plinius-bootcheck: reference copied into the LUKS2 header of $1 for the password prompt"
	else
		echo "plinius-bootcheck: could not copy the reference into the LUKS2 header of $1" >&2
	fi
}

# The prompt of plinius-crypt leaves a mark at every start of the encrypted system. Once one was
# seen, a start without it ran another prompt: a ramdisk loaded without writing any partition, or
# one of an older plinius-crypt (the fallback entry of the boot menu card may still hold one).
prompt_check() {
	if [[ -e $PROMPT_MARK ]]; then
		echo "plinius-bootcheck: password prompt: $(head -n 1 "$PROMPT_MARK")"
		touch "$STATE/prompt-seen"
	elif [[ -e $STATE/prompt-seen ]]; then
		echo "plinius-bootcheck: this start ran without the boot chain check of the password prompt" >&2
		alarm_add ramdisk:prompt
	fi
}

# The findings that are no paths of the lists (see the top), kept until accepted
is_alarm() { [[ $1 == luks:token || $1 == ramdisk:prompt ]]; }
alarm_add() {
	grep -qxF -- "$1" "$STATE/alarms" 2>/dev/null || echo "$1" >> "$STATE/alarms"
}
alarm_remove() {
	[[ -s $STATE/alarms ]] || return 0
	grep -vxF -f <(printf '%s\n' "$@") "$STATE/alarms" > "$STATE/alarms.new" || true
	mv -f "$STATE/alarms.new" "$STATE/alarms"
	[[ -s $STATE/alarms ]] || rm -f "$STATE/alarms"
}

# Take paths $@ out of what this start reported as changed
unreport() {
	[[ -s $RUN/changed ]] || return 0
	grep -vxF -f <(printf '%s\n' "$@") "$RUN/changed" > "$RUN/changed.new" || true
	mv -f "$RUN/changed.new" "$RUN/changed"
	[[ -s $RUN/changed ]] || rm -f "$RUN/changed"
}

# The reference without the entries the lists no longer name ("list": all_paths); without the
# card its entries stay (taking the card out is no change), as at "check"
ref_named() {
	[[ -s $REF ]] || return 0
	local keep_card=
	card_ok || keep_card=1
	printf '%s\n' "${list[@]}" | awk -v keep_card="$keep_card" '
		NR == FNR { named[$0] = 1; next }
		($2 in named) || (keep_card && $2 ~ /^abm:/)' - "$REF"
}

# Write the reference from stdin, sorted by path, atomically; on an encrypted system ("luks", the
# device) its copy in the LUKS2 header too. token-pending covers the time in between.
save_ref() {
	install -d -m755 "$STATE"
	[[ -z ${luks:-} ]] || touch "$STATE/token-pending"
	sort -k2 > "$REF.new"
	mv -f "$REF.new" "$REF"
	[[ -z ${luks:-} ]] || token_sync "$luks"
}

cmd=${1:-}
shift || true
case $cmd in
check)
	(($# == 0)) || die "usage: plinius-bootcheck check"
	mkdir -p "$RUN"
	rm -f "$RUN/changed" "$RUN/done"
	read_lists
	mapfile -t list < <(all_paths)
	[[ ${list[*]:-} ]] || { echo "plinius-bootcheck: no lists in $LISTS, nothing to check"; touch "$RUN/done"; exit 0; }
	luks=$(luks_dev) || luks=
	now=$(hashes "${list[@]}")
	if [[ ! -s $REF ]]; then
		save_ref <<< "$now"
		[[ -z $luks ]] || prompt_check
		echo "plinius-bootcheck: no reference yet, recorded the current state (${#list[@]} entries)"
		touch "$RUN/done"
		exit 0
	fi
	# Before the reference changes: its copy for the prompt, and whether the prompt ran
	if [[ -n $luks ]]; then
		token_matches "$luks" || alarm_add luks:token
		prompt_check
	fi
	# Without the card its entries keep their reference (taking the card out is no change)
	if ! card_ok; then
		kept=$(awk '$2 ~ /^abm:/' "$REF")
		[[ -z $kept ]] || now+=$'\n'$kept
	fi
	# Only paths in both the reference and the lists can raise an alarm, and new own card
	# entries once the card is known
	changed=$(awk 'NR == FNR { ref[$2] = $1; if ($2 ~ /^abm:/) card = 1; next }
		(($2 in ref) ? ref[$2] != $1 : (card && $2 ~ /^abm:/)) { print $2 }' "$REF" - <<< "$now")
	added=$(awk 'NR == FNR { ref[$2] = 1; next } !($2 in ref) { print $2 }' "$REF" - <<< "$now")
	# Reference: changed entries keep the old value and new card entries stay out (the alarm
	# stays until "accept"), other new ones are added, dropped ones go away
	alarm=$changed awk 'BEGIN { n = split(ENVIRON["alarm"], a, "\n"); for (i = 1; i <= n; i++) skip[a[i]] = 1 }
		NR == FNR { ref[$2] = $1; next }
		($2 in ref) { print ref[$2] "  " $2; next }
		!($2 in skip) { print $1 "  " $2 }' "$REF" - <<< "$now" | save_ref
	[[ -z $changed || -z $added ]] || added=$(grep -vxF -f <(printf '%s\n' "$changed") <<< "$added" || true)
	[[ -z $added ]] || echo "plinius-bootcheck: new entries recorded: $(tr '\n' ' ' <<< "$added")"
	# The findings without a path of the lists, until accepted
	if [[ -s $STATE/alarms ]]; then
		changed=$(printf '%s\n' "$changed" | cat - "$STATE/alarms" | sed '/^$/d')
	fi
	if [[ -n $changed ]]; then
		printf '%s\n' "$changed" > "$RUN/changed"
		touch "$RUN/done"
		echo "plinius-bootcheck: CHANGED since the last accepted state: $(tr '\n' ' ' <<< "$changed")" >&2
		exit 2
	fi
	touch "$RUN/done"
	echo "plinius-bootcheck: unchanged (${#list[@]} entries)"
	;;
accept)
	[[ $(id -u) -eq 0 ]] || die "must run as root"
	written=
	if [[ ${1:-} == --written ]]; then written=1; shift; fi
	read_lists
	luks=$(luks_dev) || luks=
	mapfile -t list < <(all_paths)
	if (($#)); then
		all=$(printf '%s\n' "${list[@]}")
		want=() findings=()
		for p; do
			if is_alarm "$p"; then
				# Only the user takes these back, never a package that wrote its own paths
				[[ -z $written ]] || die "$p is not a path a package writes"
				findings+=("$p")
			elif [[ $p == abm-entry:* ]]; then
				card_ok || die "no boot menu card for $p"
				conf=/db/entries/${p#abm-entry:}.conf
				card_has "$conf" || die "no entry ${p#abm-entry:} on the card"
				want+=("abm:$conf")
				mapfile -t -O "${#want[@]}" want < <(card_cat "$conf" | entry_files)
			else
				want+=("$p")
			fi
		done
		set --
		for p in "${want[@]}"; do
			grep -qxF -- "$p" <<< "$all" || die "not in the lists: $p"
			if [[ -n $written && -s $RUN/changed ]] && grep -qxF -- "$p" "$RUN/changed"; then
				echo "plinius-bootcheck: $p was reported as changed at this start, left for the user to confirm" >&2
				continue
			fi
			set -- "$@" "$p"
		done
		if ((${#findings[@]})); then
			alarm_remove "${findings[@]}"
			unreport "${findings[@]}"
			echo "plinius-bootcheck: accepted ${findings[*]}"
		fi
		(($#)) || exit 0
		new=$(hashes "$@")
	else
		new=$(hashes "${list[@]}")
		if [[ -s $STATE/alarms ]]; then
			mapfile -t findings < "$STATE/alarms"
			rm -f "$STATE/alarms"
			unreport "${findings[@]}"
		fi
	fi
	# Replace the accepted paths, keep the other entries the lists still name
	{ ref_named | awk 'NR == FNR { skip[$2] = 1; next } !($2 in skip)' <(printf '%s\n' "$new") -
	  printf '%s\n' "$new"; } | save_ref
	mapfile -t accepted < <(cut -d' ' -f3- <<< "$new")
	unreport "${accepted[@]}"
	echo "plinius-bootcheck: accepted $(wc -l <<< "$new") entries"
	;;
forget)
	[[ $(id -u) -eq 0 ]] || die "must run as root"
	(($# == 0)) || die "usage: plinius-bootcheck forget"
	[[ -s $REF ]] || exit 0
	read_lists
	luks=$(luks_dev) || luks=
	mapfile -t list < <(all_paths)
	kept=$(ref_named)
	gone=$(awk 'NR == FNR { kept[$2] = 1; next } !($2 in kept) { print $2 }' <(printf '%s\n' "$kept") "$REF")
	# Nothing to drop: the copy in the header stays as it is ("check" judges it at the next start)
	[[ -n $gone ]] || exit 0
	printf '%s\n' "$kept" | sed '/^$/d' | save_ref
	mapfile -t dropped <<< "$gone"
	unreport "${dropped[@]}"
	echo "plinius-bootcheck: forgot $(wc -l <<< "$gone") entries no longer there"
	;;
status)
	(($# == 0)) || die "usage: plinius-bootcheck status"
	if [[ ! -e $RUN/done ]]; then
		echo "not checked yet"
	elif [[ -s $RUN/changed ]]; then
		echo "changed since the last accepted state:"
		sed 's/^/  /' "$RUN/changed"
		exit 2
	else
		echo "unchanged"
	fi
	;;
*)
	die "usage: plinius-bootcheck check | accept [--written] [PATH...] | forget | status"
	;;
esac
