#!/bin/sh
#
# verify_processes.sh
# 2011-11-19
# by Gernot WALZL
#
# Creates checksums of all running processes.

CWD="$(pwd)"
TMP=${TMP:-/tmp}
DATETIME=$(date +%Y-%m-%d_%H%M%S)
HOST=$(hostname)
OUTPUT=${OUTPUT:-processes_${HOST}_${DATETIME}.sha1}

if [ "$(id -u)" != "0" ]; then
  echo "This script must be run as root." 1>&2
  exit 1
fi

# verify kernel
# TODO: verify correct kernel & verify kernel modules
sha1sum /boot/vmlinuz > "$CWD/$OUTPUT"

# verify all running binaries
PIDs="$(ps -A | awk '{print $1}' | sed '/PID/d')"
rm -f "$TMP/$OUTPUT.tmp"
for PID in $PIDs; do
  BIN="$(readlink /proc/$PID/exe)"
  if [ "$BIN" != "" ]; then
    echo "$BIN" >> "$TMP/$OUTPUT.tmp"
  fi
done
sort "$TMP/$OUTPUT.tmp" | uniq | xargs sha1sum >> "$CWD/$OUTPUT"

# verify linked shared libraries
rm -f "$TMP/$OUTPUT.tmp"
for PID in $PIDs; do
  if [ -f /proc/$PID/maps ]; then
    cat /proc/$PID/maps \
      | awk '{print $6}' \
      | sed '/^\[.*\]$/d' | sed '/^\/dev\/.*$/d' | sed '/^$/d' \
      | sort | uniq \
      >> "$TMP/$OUTPUT.tmp"
  fi
done
sort "$TMP/$OUTPUT.tmp" | uniq | xargs sha1sum >> "$CWD/$OUTPUT"

# clean up
rm -f "$TMP/$OUTPUT.tmp"

echo ""
echo "run 'diff -u [old].sha1 ${OUTPUT}' to see differences"
echo ""