#!/bin/sh
# bootkits-collect-linux.sh: collect what bootkits.dev's offline checker
# reads on a Linux host: the EFI system partition, the TPM event log
# (binary_bios_measurements), and the boot regions of the disks that hold the
# EFI system partition and the root file system: each disk's first 4 MiB as
# diskN.img and its last MiB as diskN.tail-<byte offset>.img.
#
# Read-only: it changes nothing on the host and never writes to a disk. dd
# only reads the disks; everything is written into the script's own staging
# folder inside the output directory, archived as one .tar.gz, and the
# staging folder is removed when the script exits. No network access.
#
# Usage:  sudo sh bootkits-collect-linux.sh -o /media/usb
#   -o DIR   where to write the archive (required)
#   -h       this help
# Testing: ROOT=/path/to/fake/root sh bootkits-collect-linux.sh -o DIR
#   reads every file, every /proc and /sys value and the disks under ROOT
#   (a disk is then ROOT/dev/<name>, a regular file) instead of /.
#
# Caveat: this runs on the suspect system. A running bootkit can filter disk
# reads and hide files, so the sectors and files read here are what it lets
# through. Prefer images of the disks taken offline (powered off, or booted
# from trusted media), and capture memory first if you can.
#
# MIT License
#
# Copyright (c) 2026 Florian Amette
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

set -u
umask 077

VERSION="1.0"
OUT=""
ROOT="${ROOT:-/}"
# 512-byte sectors read from each disk: its first 4 MiB and its last MiB.
HEAD_SECTORS=8192
TAIL_SECTORS=2048
MAX_DISKS=8
MAX_ESP_FILES=20000
# Larger files on the EFI system partition are counted, not copied.
MAX_ESP_FILE=268435456

usage() {
  # The header comment, up to the licence.
  sed -n '2,/^# MIT License/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'
}

while getopts "o:h" opt; do
  case "$opt" in
    o) OUT="$OPTARG" ;;
    h) usage; exit 0 ;;
    *) usage >&2; exit 2 ;;
  esac
done

say() { printf '%s\n' "$*"; }
warn() { printf 'warning: %s\n' "$*" >&2; }

if [ -z "$OUT" ]; then
  usage >&2
  say "error: choose an output directory with -o" >&2
  exit 2
fi
if [ ! -d "$OUT" ] || [ ! -w "$OUT" ]; then
  say "error: $OUT is not a writable directory" >&2
  exit 2
fi
case "$ROOT" in
  /) R="" ;;
  *) R="${ROOT%/}" ;;
esac
if [ ! -d "$ROOT" ]; then
  say "error: ROOT=$ROOT is not a directory" >&2
  exit 2
fi
if [ "$(id -u)" != "0" ]; then
  warn "not running as root: the disks and the TPM event log will be unreadable"
fi

# ----------------------------------------------------------------- naming ---
HOST=$(cat "$R/etc/hostname" 2>/dev/null || hostname 2>/dev/null || echo host)
HOST=$(printf '%s' "$HOST" | head -n 1 | tr -c 'A-Za-z0-9._-' '_' | cut -c1-63)
# The host folder of every member: never "." or "..", never an option to tar.
case "$HOST" in
  .* | -*) HOST="_$HOST" ;;
esac
[ -n "$HOST" ] || HOST=host
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
NAME="bootkits-$HOST-$STAMP.tar.gz"
ARCHIVE="$OUT/$NAME"
if [ -e "$ARCHIVE" ]; then
  say "error: $ARCHIVE already exists" >&2
  exit 2
fi

# Everything the script writes goes into this private folder (mode 700, a
# name no one can guess), the archive included; only the finished archive is
# then renamed into the output folder. Interrupted, it leaves nothing.
STAGE=$(mktemp -d "$OUT/.bootkits-collect.XXXXXX") || { say "error: cannot create a temporary folder in $OUT" >&2; exit 1; }
cleanup() {
  rm -rf "${STAGE:?}"
}
trap cleanup EXIT
trap 'exit 130' INT TERM HUP
H="$STAGE/$HOST"
mkdir "$H"
# The script's own files start with a dot: no host folder does.
NOTES="$STAGE/.notes"
DISKLOG="$STAGE/.disks"
: > "$NOTES"
: > "$DISKLOG"
note() {
  printf '%s\n' "$*" >> "$NOTES"
  warn "$*"
}
NL='
'

# ------------------------------------------------- EFI system partition ---
# The first of /boot/efi, /efi and /boot that holds an EFI folder, copied as
# ESP/. No part of its path may be a symbolic link, and only regular files on
# its own file system are listed: a planted link never brings another tree
# into the archive. Names holding a line break are left out (the list is read
# one name per line).
ESP_MP=""
for mp in boot/efi efi boot; do
  [ -d "$R/$mp/EFI" ] || continue
  if [ -L "$R/$mp" ] || [ -L "$R/$mp/EFI" ] || { [ "$mp" = boot/efi ] && [ -L "$R/boot" ]; }; then
    note "/$mp goes through a symbolic link: not collected"
    continue
  fi
  ESP_MP=$mp
  break
done
nesp=0
nbig=0
if [ -n "$ESP_MP" ]; then
  (cd "$R/" && find "$ESP_MP" -xdev -type f -size -$((MAX_ESP_FILE + 1))c ! -path "*$NL*" -print 2>/dev/null) | head -n "$MAX_ESP_FILES" > "$STAGE/.esp"
  nbig=$( (cd "$R/" && find "$ESP_MP" -xdev -type f -size +${MAX_ESP_FILE}c -print 2>/dev/null) | wc -l | tr -d ' ')
  mkdir "$H/ESP"
  while IFS= read -r f; do
    rel=${f#"$ESP_MP"/}
    case "$rel" in
      */*) dir=${rel%/*} ;;
      *) dir=. ;;
    esac
    [ -f "$R/$f" ] && [ ! -L "$R/$f" ] || continue
    mkdir -p "$H/ESP/$dir" && cp -p "$R/$f" "$H/ESP/$rel" 2>/dev/null && nesp=$((nesp + 1))
  done < "$STAGE/.esp"
  [ "$nbig" = 0 ] || note "$nbig file(s) larger than $((MAX_ESP_FILE >> 20)) MiB on /$ESP_MP were not copied"
else
  note "no EFI system partition at /boot/efi, /efi or /boot (is it mounted?)"
fi

# ------------------------------------------------------- TPM event log ---
# A sysfs file whose size reads as 0: copy its content.
TPM="sys/kernel/security/tpm0/binary_bios_measurements"
TPM_STATE="not readable: no TPM, securityfs not mounted, or not root"
if [ -r "$R/$TPM" ]; then
  mkdir -p "$H/sys/kernel/security/tpm0"
  if cat "$R/$TPM" > "$H/$TPM" 2>/dev/null && [ -s "$H/$TPM" ]; then
    TPM_STATE="copied"
  else
    rm -f "${H:?}/$TPM"
    TPM_STATE="empty or unreadable"
  fi
fi

# --------------------------------------------------------------- disks ---
# The whole disks under the block devices that hold / and the EFI system
# partition, found from /proc/self/mountinfo and /sys: through partitions,
# and through device-mapper and RAID devices (LVM, LUKS, md) by their slaves.
valid_name() {
  case "$1" in
    "" | .* | *[!A-Za-z0-9._-]*) return 1 ;;
  esac
  return 0
}

# "major:minor source" of the mount at $1 (the last one stacked there).
mount_of() {
  awk -v mp="$1" '{ for (i = 7; i <= NF && $i != "-"; i++) ; if ($5 == mp && i + 2 <= NF) found = $3 " " $(i + 2) } END { if (found != "") print found }' "$R/proc/self/mountinfo" 2>/dev/null
}

# The block device name of a mount: by its major:minor in /sys/dev/block, or
# by its /dev source (btrfs and others report an anonymous major:minor).
device_of() { # major:minor, source
  case "$1" in
    *[!0-9:]* | "") ;;
    *)
      if [ -e "$R/sys/dev/block/$1" ]; then
        p=$(cd -P "$R/sys/dev/block/$1" 2>/dev/null && pwd -P) && { printf '%s\n' "${p##*/}"; return 0; }
      fi
      ;;
  esac
  case "${2:-}" in
    /dev/mapper/*)
      # Called in a command substitution while globbing is off: on here only.
      set +f
      for m in "$R"/sys/class/block/dm-*; do
        [ "$(cat "$m/dm/name" 2>/dev/null)" = "${2#/dev/mapper/}" ] && { printf '%s\n' "${m##*/}"; return 0; }
      done
      ;;
    /dev/*) printf '%s\n' "${2##*/}" ;;
  esac
  return 0
}

# The whole disks under a block device, at most 8 levels down, at most 256
# devices looked at. Level by level, each device once: LVM volumes share
# their physical volumes, so a walk per path would grow exponentially.
# Called in a command substitution while globbing is off.
disks_of() { # name
  level=$1
  seen=" "
  looked=0
  depth=0
  while [ -n "$level" ] && [ "$depth" -le 8 ]; do
    next=""
    for x in $level; do
      valid_name "$x" || continue
      case "$seen" in *" $x "*) continue ;; esac
      seen="$seen$x "
      looked=$((looked + 1))
      [ "$looked" -le 256 ] || return 0
      d="$R/sys/class/block/$x"
      [ -d "$d" ] || continue
      if [ -f "$d/partition" ]; then
        p=$(cd -P "$d/.." 2>/dev/null && pwd -P) && next="$next ${p##*/}"
        continue
      fi
      s=$(ls -1 "$d/slaves" 2>/dev/null)
      if [ -n "$s" ]; then
        next="$next $s"
        continue
      fi
      case "$x" in
        loop* | ram* | zram* | nbd* | sr*) ;;
        *) printf '%s\n' "$x" ;;
      esac
    done
    level=$next
    depth=$((depth + 1))
  done
}

DISKS=""
set -f
for target in / ${ESP_MP:+"/$ESP_MP"}; do
  info=$(mount_of "$target")
  if [ -z "$info" ]; then
    note "$target is not a mount point in /proc/self/mountinfo: its disk was not looked for"
    continue
  fi
  # shellcheck disable=SC2086
  name=$(device_of $info)
  found=no
  for disk in $(disks_of "$name"); do
    found=yes
    case " $DISKS " in
      *" $disk "*) ;;
      *) DISKS="${DISKS:+$DISKS }$disk" ;;
    esac
  done
  # The mount's source as the kernel shows it: only space, tab, line feed and backslash are escaped.
  [ "$found" = yes ] || note "the disk holding $target could not be found (mounted from $(printf '%s' "${info#* }" | tr -c 'A-Za-z0-9/._:+=,@-' '_' | cut -c1-128))"
done

n=0
for disk in $DISKS; do
  if [ "$n" -ge "$MAX_DISKS" ]; then
    note "more than $MAX_DISKS disks: $disk and the next ones were not read"
    break
  fi
  size=$(cat "$R/sys/class/block/$disk/size" 2>/dev/null)
  case "$size" in
    "" | *[!0-9]* | 0) note "the size of $disk is unknown: not read"; continue ;;
  esac
  if [ ${#size} -gt 15 ]; then
    note "the size of $disk is not plausible: not read"
    continue
  fi
  if [ "$R" = "" ]; then
    dev="/dev/$disk"
    [ -b "$dev" ] || { note "$dev is not a block device: not read"; continue; }
  else
    dev="$R/dev/$disk"
    [ -f "$dev" ] || [ -b "$dev" ] || { note "$dev is missing: not read"; continue; }
  fi
  # dd only reads the disk (if=); what it writes (of=) is in the staging folder.
  if [ "$size" -le $((HEAD_SECTORS + TAIL_SECTORS)) ]; then
    dd if="$dev" of="$H/disk$n.img" bs=512 count="$size" 2>/dev/null || { rm -f "${H:?}/disk$n.img"; note "reading $dev failed"; continue; }
    ends="the whole disk"
  else
    dd if="$dev" of="$H/disk$n.img" bs=512 count="$HEAD_SECTORS" 2>/dev/null || { rm -f "${H:?}/disk$n.img"; note "reading $dev failed"; continue; }
    at=$((size - TAIL_SECTORS))
    if dd if="$dev" of="$H/disk$n.tail-$((at * 512)).img" bs=512 skip="$at" count="$TAIL_SECTORS" 2>/dev/null; then
      ends="its first 4 MiB, and its last MiB from byte $((at * 512))"
    else
      rm -f "${H:?}/disk$n.tail-$((at * 512)).img"
      note "the end of $dev could not be read: only its first 4 MiB were kept"
      ends="its first 4 MiB"
    fi
  fi
  model=$(head -n 1 "$R/sys/class/block/$disk/device/model" 2>/dev/null | tr -cd 'A-Za-z0-9 ._-' | cut -c1-64)
  say "disk$n: $dev, $size sectors of 512 bytes${model:+, $model}: $ends" >> "$DISKLOG"
  n=$((n + 1))
done
set +f
[ "$n" -gt 0 ] || note "no disk was read: the boot regions are not in this collection"

{
  say "bootkits-collect-linux.sh $VERSION"
  say "host: $HOST"
  say "started: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  say "uid: $(id -u)"
  say "root: $ROOT"
  if [ -n "$ESP_MP" ]; then say "EFI system partition: /$ESP_MP, $nesp files, as ESP/"; else say "EFI system partition: not found"; fi
  say "TPM event log: $TPM_STATE"
  cat "$DISKLOG"
  sed 's/^/note: /' "$NOTES"
} > "$H/collect.txt"

# ---------------------------------------------------------------- archive ---
# Written in the staging folder, hashed there, then renamed into the output
# folder: a rename replaces whatever another account may have planted at that
# predictable name (a link to a file or to a disk) instead of writing through it.
if ! tar -czf "$STAGE/$NAME" -C "$STAGE" "$HOST"; then
  say "error: tar failed" >&2
  exit 1
fi

if command -v sha256sum >/dev/null 2>&1; then
  SUM=$(sha256sum "$STAGE/$NAME" | cut -d' ' -f1)
elif command -v shasum >/dev/null 2>&1; then
  SUM=$(shasum -a 256 "$STAGE/$NAME" | cut -d' ' -f1)
else
  SUM=$(openssl dgst -sha256 "$STAGE/$NAME" 2>/dev/null | sed 's/.*= //')
fi
if ! mv -f "$STAGE/$NAME" "$OUT/"; then
  say "error: cannot move the archive into $OUT" >&2
  exit 1
fi

if [ -n "$ESP_MP" ]; then say "EFI system partition: /$ESP_MP, $nesp files"; else say "EFI system partition: not found"; fi
say "TPM event log: $TPM_STATE"
say "Disks read: $n"
say "Archive: $ARCHIVE"
say "SHA-256: $SUM"
say "Open it at https://www.bootkits.dev/ (nothing is uploaded)."
