#!/bin/sh
# rootkits-collect-linux.sh: collect the files rootkits.dev's offline checker
# reads on a Linux host (kernel modules and their indexes, module load
# configuration, ld.so.preload and the libraries it names, the dpkg file
# lists, kernel logs, the EFI system partition, the TPM event log) plus a few
# live outputs (/proc/modules, /sys/module, the taint value, uname, dmesg).
#
# Read-only: it changes nothing on the host. It writes only inside the output
# directory you choose: one .tar.gz, and a temporary folder for the live
# outputs that it removes when it exits. No network access.
#
# Usage:  sudo sh rootkits-collect-linux.sh -o /media/usb [-a]
#   -o DIR   where to write the archive (required)
#   -a       collect the modules of every installed kernel, not only the running one
#   -h       this help
# Testing: ROOT=/path/to/fake/root sh rootkits-collect-linux.sh -o DIR
#   reads every file and /proc, /sys value under ROOT instead of /.
#
# Caveat: this runs on the suspect system. A kernel rootkit or an
# ld.so.preload library can hide files and processes from it, and live
# outputs come from the suspect kernel. Prefer an image of the disk taken
# offline, 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=""
ALL_KERNELS=no
ROOT="${ROOT:-/}"

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

while getopts "o:ah" opt; do
  case "$opt" in
    o) OUT="$OPTARG" ;;
    a) ALL_KERNELS=yes ;;
    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: some files (dmesg, module trees, logs) may 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)
ARCHIVE="$OUT/rootkits-$HOST-$STAMP.tar.gz"
if [ -e "$ARCHIVE" ]; then
  say "error: $ARCHIVE already exists" >&2
  exit 2
fi

STAGE=$(mktemp -d "$OUT/.rootkits-collect.XXXXXX") || { say "error: cannot create a temporary folder in $OUT" >&2; exit 1; }
DONE=no
# Interrupted: no half-written archive is left to pass for a complete one.
cleanup() {
  rm -rf "$STAGE"
  [ "$DONE" = yes ] || rm -f "$ARCHIVE"
}
trap cleanup EXIT
trap 'exit 130' INT TERM HUP
LIVE="$STAGE/_live"
mkdir "$LIVE"
LIST="$STAGE/files.txt"
: > "$LIST"

# ------------------------------------------------------------ file list ---
# Paths are relative to ROOT. Only regular files are listed, so symbolic
# links inside the trees (such as lib/modules/*/build) are never followed.
# tar reads the list one path per line: a name holding a line break would
# add a second, planted path (bsdtar even a whole directory), so such names
# are left out.
NL='
'
add_file() { # relative path
  [ -f "$R/$1" ] && [ -r "$R/$1" ] && printf '%s\n' "$1" >> "$LIST"
}
add_tree() { # relative directory, then find(1) name tests
  dir="$1"
  shift
  [ -d "$R/$dir" ] || return 0
  (cd "$R/" && find "$dir" "$@" -type f ! -path "*$NL*" -print 2>/dev/null) >> "$LIST"
}
# A library ld.so.preload names (path relative to ROOT): only an ELF file of
# at most 128 MiB inside ROOT, what the loader can load. A planted entry or
# link never brings /etc/shadow or /proc/kcore into the archive, and never
# reads or writes outside ROOT and the output folder.
add_lib() {
  case "$1" in
    "" | -* | /* | .. | ../* | */.. | */../*) return 0 ;;
  esac
  [ -f "$R/$1" ] && [ -r "$R/$1" ] || return 0
  [ "$(dd if="$R/$1" bs=4 count=1 2>/dev/null | od -An -tx1 | tr -d ' \n')" = 7f454c46 ] || return 0
  [ "$(dd if="$R/$1" bs=65536 count=2049 2>/dev/null | wc -c | tr -d ' ')" -le 134217728 ] || return 0
  add_file "$1"
}

# Merged /usr: /lib is /usr/lib; list each file once.
LIB_IS_LINK=no
[ -L "$R/lib" ] && LIB_IS_LINK=yes

RELEASE=$(cat "$R/proc/sys/kernel/osrelease" 2>/dev/null || uname -r)
if [ -d "$R/lib/modules" ]; then MODBASE=lib/modules; else MODBASE=usr/lib/modules; fi
if [ "$ALL_KERNELS" = yes ]; then
  KTREES=$(cd "$R/$MODBASE" 2>/dev/null && ls -1)
else
  KTREES="$RELEASE"
fi
nkernels=0
set -f
for k in $KTREES; do
  [ -d "$R/$MODBASE/$k" ] || { warn "no module tree for kernel $k"; continue; }
  nkernels=$((nkernels + 1))
  (cd "$R/" && find "$MODBASE/$k" -type f \( -name '*.ko' -o -name '*.ko.zst' -o -name '*.ko.xz' -o -name '*.ko.gz' \
    -o -name 'modules.order' -o -name 'modules.dep' -o -name 'modules.builtin' -o -name 'modules.builtin.modinfo' \) \
    ! -path "*/build/*" ! -path "*/source/*" ! -path "*$NL*" -print 2>/dev/null) >> "$LIST"
done
set +f

add_file etc/modules
for d in etc/modules-load.d etc/modprobe.d run/modules-load.d run/modprobe.d usr/lib/modules-load.d usr/lib/modprobe.d \
  usr/local/lib/modules-load.d usr/local/lib/modprobe.d etc/depmod.d usr/lib/depmod.d; do
  add_tree "$d"
done
if [ "$LIB_IS_LINK" = no ]; then
  add_tree lib/modules-load.d
  add_tree lib/modprobe.d
  add_tree lib/depmod.d
fi

# ld.so.preload and every library it names.
PRELOAD_NOTE=""
if [ -f "$R/etc/ld.so.preload" ]; then
  add_file etc/ld.so.preload
  PRELOAD_NOTE="etc/ld.so.preload exists: a preloaded library may have hidden files from this collection"
  # Entries are separated by whitespace or colons; no globbing.
  set -f
  # shellcheck disable=SC2013
  for lib in $(sed -e 's/#.*//' -e 's/:/ /g' "$R/etc/ld.so.preload" 2>/dev/null); do
    case "$lib" in
      /*) add_lib "${lib#/}" ;;
    esac
  done
  set +f
fi

add_tree var/lib/dpkg/info -name '*.list'
add_tree var/log -maxdepth 1 -name 'kern.log*'
add_tree var/log -maxdepth 1 -name 'messages*'
add_tree boot/efi/EFI

# ------------------------------------------------------------ live outputs ---
run_live() { # name, then the command
  name="$1"
  shift
  "$@" > "$LIVE/$name" 2>/dev/null || { [ -s "$LIVE/$name" ] || rm -f "$LIVE/$name"; }
}
run_live proc_modules cat "$R/proc/modules"
run_live tainted cat "$R/proc/sys/kernel/tainted"
run_live modules_disabled cat "$R/proc/sys/kernel/modules_disabled"
run_live uname uname -a
# shellcheck disable=SC2016
run_live boot_time awk '/^btime/ { print $2 }' "$R/proc/stat"
if [ -d "$R/sys/module" ]; then
  (cd "$R/sys/module" && ls -1) > "$LIVE/sys_module" 2>/dev/null
  # name, initstate (only loadable modules have one), taint letters.
  for m in "$R"/sys/module/*; do
    [ -d "$m" ] || continue
    st=$(cat "$m/initstate" 2>/dev/null)
    tn=$(cat "$m/taint" 2>/dev/null)
    printf '%s %s %s\n' "${m##*/}" "${st:--}" "${tn:--}"
  done > "$LIVE/sys_module_detail"
fi
# dmesg reads the running kernel, so only without ROOT.
[ "$R" = "" ] && run_live dmesg dmesg
# The TPM event log is a sysfs file whose size reads as 0: copy its content.
if [ -r "$R/sys/kernel/security/tpm0/binary_bios_measurements" ]; then
  mkdir -p "$STAGE/sys/kernel/security/tpm0"
  cat "$R/sys/kernel/security/tpm0/binary_bios_measurements" > "$STAGE/sys/kernel/security/tpm0/binary_bios_measurements" 2>/dev/null
fi
{
  say "rootkits-collect-linux.sh $VERSION"
  say "host: $HOST"
  say "started: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  say "uid: $(id -u)"
  say "root: $ROOT"
  say "running kernel: $RELEASE"
  say "all kernels: $ALL_KERNELS"
  [ -n "$PRELOAD_NOTE" ] && say "note: $PRELOAD_NOTE"
} > "$LIVE/collect.txt"

# ---------------------------------------------------------------- archive ---
# Every member goes under "<host>/": GNU tar --transform, bsdtar -s.
nfiles=$(wc -l < "$LIST" | tr -d ' ')
STAGED="_live"
[ -d "$STAGE/sys" ] && STAGED="_live sys"
if tar --version 2>/dev/null | grep -q 'GNU tar'; then
  # shellcheck disable=SC2086
  tar -czf "$ARCHIVE" --dereference --no-recursion --transform="s,^,$HOST/," -C "$R/" -T "$LIST" --recursion -C "$STAGE" $STAGED
elif tar --version 2>/dev/null | grep -q 'bsdtar'; then
  # bsdtar reads directory changes from the list itself: "-C" on a line, the folder on the next.
  BLIST="$STAGE/bsdtar-files.txt"
  { printf -- '-C\n%s\n' "$R/"; cat "$LIST"; printf -- '-C\n%s\n' "$STAGE"; for s in $STAGED; do printf '%s\n' "$s"; done; } > "$BLIST"
  tar -czf "$ARCHIVE" -h -s ",^,$HOST/," -T "$BLIST"
else
  # Other tar (busybox): copy into the temporary folder first.
  mkdir -p "$STAGE/$HOST"
  while IFS= read -r f; do
    mkdir -p "$STAGE/$HOST/$(dirname "$f")" && cp -p "$R/$f" "$STAGE/$HOST/$f" 2>/dev/null
  done < "$LIST"
  for s in $STAGED; do mv "$STAGE/$s" "$STAGE/$HOST/"; done
  tar -czf "$ARCHIVE" -C "$STAGE" "$HOST"
fi
status=$?
if [ $status -ne 0 ] && [ ! -s "$ARCHIVE" ]; then
  say "error: tar failed (status $status)" >&2
  exit 1
fi
DONE=yes

if command -v sha256sum >/dev/null 2>&1; then
  SUM=$(sha256sum "$ARCHIVE" | cut -d' ' -f1)
elif command -v shasum >/dev/null 2>&1; then
  SUM=$(shasum -a 256 "$ARCHIVE" | cut -d' ' -f1)
else
  SUM=$(openssl dgst -sha256 "$ARCHIVE" 2>/dev/null | sed 's/.*= //')
fi

say "Collected $nfiles files from $ROOT ($nkernels kernel module tree(s)) and the live outputs in _live/."
[ -n "$PRELOAD_NOTE" ] && say "Note: $PRELOAD_NOTE."
say "Archive: $ARCHIVE"
say "SHA-256: $SUM"
say "Open it at https://www.rootkits.dev/ (nothing is uploaded)."
