#!/bin/bash # # verify-packages.sh - check installed packages' files against dpkg's recorded MD5 sums # # For Debian-based systems (Raspberry Pi OS, Debian, Ubuntu). Every file that a # package installed is hashed and compared with the checksum dpkg recorded at # install time (/var/lib/dpkg/info/.md5sums). Any package whose files # no longer match is listed so it can be reinstalled - useful after a power # loss or other unclean shutdown. # # Usage: # sudo ./verify-packages.sh [-o OUTDIR] [-q] [PACKAGE...] # # -o OUTDIR where to write the report files (default: ./pkgverify-) # -q no progress display # PACKAGE... check only these packages (default: every installed package) # # Exit status: 0 = all files match, 1 = damaged/missing files found, # 2 = the check could not be run. # # Limits: only files shipped inside packages are covered. Your own data, logs, # databases, home directories and files generated after installation (e.g. # Python .pyc caches) are not in the md5sums lists. Config files under /etc # are reported separately because editing them is normal. set -u set -o pipefail INFO_DIR=/var/lib/dpkg/info OUTDIR="" QUIET=0 usage() { cat <<'EOF' Usage: sudo ./verify-packages.sh [-o OUTDIR] [-q] [PACKAGE...] -o OUTDIR where to write the report files (default: ./pkgverify-) -q no progress display -h show this help PACKAGE... check only these packages (default: every installed package) EOF } die() { printf 'ERROR: %s\n' "$*" >&2; exit 2; } warn() { printf 'WARNING: %s\n' "$*" >&2; } while getopts ':o:qh' opt; do case $opt in o) OUTDIR=$OPTARG ;; q) QUIET=1 ;; h) usage; exit 0 ;; *) usage >&2; exit 2 ;; esac done shift $((OPTIND - 1)) # ---------------------------------------------------------------- preflight -- command -v dpkg-query >/dev/null 2>&1 \ || die "dpkg-query not found; this script is for Debian-based systems (Raspberry Pi OS, Debian, Ubuntu)." command -v md5sum >/dev/null 2>&1 || die "md5sum not found." [[ -d $INFO_DIR ]] || die "$INFO_DIR not found; is the dpkg database intact?" ROOT=0 [[ $EUID -eq 0 ]] && ROOT=1 (( ROOT )) || warn "not running as root: files only root may read will be reported as unreadable. Use sudo for a complete check." [[ -n $OUTDIR ]] || OUTDIR=./pkgverify-$(date +%Y%m%d-%H%M%S) mkdir -p "$OUTDIR" || die "cannot create $OUTDIR" OUTDIR=$(cd "$OUTDIR" && pwd) MISMATCH=$OUTDIR/mismatched.txt # package /path : content differs from what was installed MISSING=$OUTDIR/missing.txt # package /path : file no longer exists UNREADABLE=$OUTDIR/unreadable.txt # package /path : exists but could not be read (I/O error or permissions) CONFMOD=$OUTDIR/conffiles-changed.txt # package /path : /etc config files that differ (editing them is normal) DIVERTED=$OUTDIR/diverted.txt # package /path : moved aside with dpkg-divert (expected) EXCLUDED=$OUTDIR/excluded-by-dpkg.txt # package /path : never installed because of a dpkg path-exclude rule SYMLINKED=$OUTDIR/replaced-by-symlink.txt # package /path : shipped as a file, now a symlink (alternatives, p11-kit, ...) NOMD5=$OUTDIR/no-md5sums.txt # packages without an md5sums list (cannot be checked) BADMD5=$OUTDIR/damaged-md5sums-lists.txt # md5sums lists that are themselves corrupt AFFECTED=$OUTDIR/affected-packages.txt # packages that should be reinstalled AUDIT=$OUTDIR/dpkg-audit.txt SUMMARY=$OUTDIR/summary.txt for f in "$MISMATCH" "$MISSING" "$UNREADABLE" "$CONFMOD" "$DIVERTED" "$EXCLUDED" "$SYMLINKED" "$NOMD5" "$BADMD5" "$AFFECTED"; do : > "$f" || die "cannot write to $OUTDIR" done rm -f "$AFFECTED.tmp" PROGRESS=0 [[ $QUIET -eq 0 && -t 2 ]] && PROGRESS=1 # ------------------------------------------------------- list the packages -- # ${binary:Package} gives "name" or "name:arch", which is also how the files in # /var/lib/dpkg/info are named. Only fully installed packages are checked. mapfile -t PKGS < <(dpkg-query -W -f='${binary:Package}\t${Status}\n' "$@" \ | awk -F'\t' '$2 ~ / installed$/ { print $1 }') (( ${#PKGS[@]} > 0 )) \ || die "no installed packages found. If dpkg-query printed errors, /var/lib/dpkg/status may be damaged; compare it with the copies in /var/backups/dpkg.status.*" # Packages dpkg itself considers broken (half-installed, unconfigured, ...). dpkg --audit > "$AUDIT" 2>&1 || true # Files moved aside with dpkg-divert will not match the owning package's md5sum; # that is expected, so they are reported separately. # "dpkg-divert --list" prints e.g. # diversion of /usr/bin/foo to /usr/bin/foo.real by somepkg # local diversion of /usr/bin/foo to /usr/bin/foo.real declare -A DIVERT=() divert_re='^(local )?diversion of ([^ ]+) to ' if command -v dpkg-divert >/dev/null 2>&1; then while IFS= read -r line; do [[ $line =~ $divert_re ]] && DIVERT["${BASH_REMATCH[2]#/}"]=1 done < <(dpkg-divert --list 2>/dev/null) fi # Files dpkg was told never to install (path-exclude rules in /etc/dpkg/dpkg.cfg # and /etc/dpkg/dpkg.cfg.d/*, e.g. to drop man pages) are legitimately absent. # Rules apply in order and the last matching rule wins, as in dpkg. EXCL_RULES=() while IFS= read -r line; do line=${line%%#*} if [[ $line =~ ^[[:space:]]*path-(exclude|include)[[:space:]=]+([^[:space:]]+) ]]; then EXCL_RULES+=("${BASH_REMATCH[1]} ${BASH_REMATCH[2]}") fi done < <(cat /etc/dpkg/dpkg.cfg /etc/dpkg/dpkg.cfg.d/* 2>/dev/null) path_excluded() { # usage: path_excluded /abs/path -> true if dpkg would not have installed it local p=$1 verdict=include rule (( ${#EXCL_RULES[@]} )) || return 1 for rule in "${EXCL_RULES[@]}"; do # shellcheck disable=SC2053 # unquoted on purpose: the rule is a glob [[ $p == ${rule#* } ]] && verdict=${rule%% *} done [[ $verdict == exclude ]] } # ------------------------------------------------------------ verification -- declare -A CONF=() total=${#PKGS[@]} checked=0 n=0 for pkg in "${PKGS[@]}"; do n=$((n + 1)) (( PROGRESS )) && printf '\r\033[K[%d/%d] %s' "$n" "$total" "$pkg" >&2 md5file=$INFO_DIR/$pkg.md5sums [[ -f $md5file ]] || md5file=$INFO_DIR/${pkg%%:*}.md5sums if [[ ! -f $md5file ]]; then printf '%s\n' "$pkg" >> "$NOMD5" continue fi checked=$((checked + 1)) # The md5sums list itself may have been hit by the power loss (truncated or # filled with NUL bytes). Count lines that are not "<32 hex> ". bad=$(LC_ALL=C grep -acvE '^[0-9a-f]{32} [ *].+$' "$md5file") if (( ${bad:-0} > 0 )); then printf '%s\t%s\t%s malformed line(s)\n' "$pkg" "$md5file" "$bad" >> "$BADMD5" printf '%s\n' "$pkg" >> "$AFFECTED.tmp" fi # Conffiles (config files under /etc) are expected to be edited by the # admin, so differences there are reported separately. CONF=() conffile=${md5file%.md5sums}.conffiles if [[ -f $conffile ]]; then while IFS= read -r line; do line=${line% remove-on-upgrade} line=${line% newconffile} [[ -n $line ]] && CONF["${line#/}"]=1 done < "$conffile" fi # md5sum -c --quiet prints one line per problem: # : FAILED content differs # : FAILED open or read missing or unreadable # plus its own "md5sum: ..." warnings, which are ignored here. while IFS= read -r line; do case $line in 'md5sum: '*) continue ;; *': FAILED open or read') path=${line%: FAILED open or read}; kind=unreadable ;; *': FAILED') path=${line%: FAILED}; kind=mismatch ;; *) continue ;; esac path=${path#\\} # md5sum prefixes a backslash when it escapes odd characters if [[ -n ${DIVERT[$path]:-} ]]; then printf '%s\t/%s\n' "$pkg" "$path" >> "$DIVERTED" elif [[ -n ${CONF[$path]:-} ]]; then printf '%s\t/%s\n' "$pkg" "$path" >> "$CONFMOD" elif [[ $kind == mismatch && -L /$path ]]; then # md5sums only lists regular files, so a symlink here was put in place # deliberately after install (update-alternatives, p11-kit, ...). printf '%s\t/%s\n' "$pkg" "$path" >> "$SYMLINKED" elif [[ $kind == mismatch ]]; then printf '%s\t/%s\n' "$pkg" "$path" >> "$MISMATCH" printf '%s\n' "$pkg" >> "$AFFECTED.tmp" elif [[ ! -e /$path ]]; then if path_excluded "/$path"; then printf '%s\t/%s\n' "$pkg" "$path" >> "$EXCLUDED" else printf '%s\t/%s\n' "$pkg" "$path" >> "$MISSING" printf '%s\n' "$pkg" >> "$AFFECTED.tmp" fi else printf '%s\t/%s\n' "$pkg" "$path" >> "$UNREADABLE" # Unreadable even as root almost always means an I/O error on the card. (( ROOT )) && printf '%s\n' "$pkg" >> "$AFFECTED.tmp" fi done < <(cd / && LC_ALL=C md5sum -c --quiet -- "$md5file" 2>&1) done (( PROGRESS )) && printf '\r\033[K' >&2 [[ -f $AFFECTED.tmp ]] && sort -u "$AFFECTED.tmp" > "$AFFECTED" rm -f "$AFFECTED.tmp" # ----------------------------------------------------------------- summary -- count() { local c; c=$(wc -l < "$1"); echo $((c)); } n_mismatch=$(count "$MISMATCH") n_missing=$(count "$MISSING") n_unreadable=$(count "$UNREADABLE") n_badmd5=$(count "$BADMD5") n_conf=$(count "$CONFMOD") n_diverted=$(count "$DIVERTED") n_excluded=$(count "$EXCLUDED") n_symlinked=$(count "$SYMLINKED") n_nomd5=$(count "$NOMD5") n_affected=$(count "$AFFECTED") { printf '==== Package file verification, %s (%dm%02ds) ====\n' \ "$(date '+%Y-%m-%d %H:%M')" $((SECONDS / 60)) $((SECONDS % 60)) printf 'Checked %d of %d installed packages (%d have no md5sums list).\n\n' \ "$checked" "$total" "$n_nomd5" printf ' %-44s %6d %s\n' \ 'Mismatched files (content damaged)' "$n_mismatch" "${MISMATCH##*/}" \ 'Missing files' "$n_missing" "${MISSING##*/}" \ 'Unreadable files' "$n_unreadable" "${UNREADABLE##*/}" \ 'Damaged md5sums lists' "$n_badmd5" "${BADMD5##*/}" \ 'Changed conffiles (normally harmless)' "$n_conf" "${CONFMOD##*/}" \ 'Diverted files (expected)' "$n_diverted" "${DIVERTED##*/}" \ 'Skipped by dpkg path-exclude (expected)' "$n_excluded" "${EXCLUDED##*/}" \ 'Replaced by a symlink (normally intentional)' "$n_symlinked" "${SYMLINKED##*/}" printf '\nReports are in %s\n' "$OUTDIR" [[ -s $AUDIT ]] && printf 'dpkg --audit also reports broken packages; see %s\n' "${AUDIT##*/}" if (( n_affected > 0 )); then printf '\nPackages with damaged or missing files (%d):\n' "$n_affected" sed 's/^/ /' "$AFFECTED" printf '\nTo reinstall them:\n' printf ' sudo apt-get update\n' printf ' xargs -a %q sudo apt-get install --reinstall\n' "$AFFECTED" printf '\nNotes:\n' printf ' - Check the filesystem first if you have not already (fsck from another machine,\n' printf ' or "sudo touch /forcefsck && sudo reboot"); look for mmc or I/O errors in dmesg.\n' (( n_unreadable > 0 && ROOT )) \ && printf ' - Files unreadable even as root usually mean a bad sector, i.e. a hardware problem.\n' printf ' - If apt, dpkg or libc6 are in the list and reinstalling fails, download the .deb\n' printf ' on another machine ("apt-get download ") and install it with "dpkg -i".\n' (( n_conf > 0 )) && { printf ' - Changed conffiles are not reinstalled automatically. Review %s;\n' "${CONFMOD##*/}" printf ' to restore one you did not edit yourself, delete it and run\n' printf ' sudo apt-get install --reinstall -o Dpkg::Options::=--force-confmiss \n' } else printf '\nAll checked files match their recorded checksums.\n' fi } | tee "$SUMMARY" (( n_affected > 0 )) && exit 1 exit 0