#!/bin/bash
#
# check_perms.sh - list non-standard SUID/SGID files and world-writable
# directories on local Linux filesystems (ext2/3/4, xfs, reiserfs).
#
# Read-only: it only runs find/mount and prints results, nothing is changed.
# Run as root for complete results. As a normal user, find cannot read some
# directories and those are silently skipped.
#
# Usage:  sudo ./check_perms.sh
#
# Review every hit by hand. Standard system binaries are filtered out below,
# but a hit is a lead to investigate, not proof of a problem.

if [ "$(id -u)" -ne 0 ]; then
    echo "Warning: not running as root, results may be incomplete." >&2
    echo "" >&2
fi

filesystems=$(mount | grep -E "type (ext[234]|xfs|reiserfs)" | awk '{print $3}')
suid_results=""
ww_results=""

for p in $filesystems; do
    if [ -d "$p" ]; then
        # SUID (4000) or SGID (2000) regular files
        suid=$(find "$p" -xdev -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null)
        # World-writable directories without the sticky bit (1000)
        ww=$(find "$p" -xdev -type d -perm -002 ! -perm -1000 2>/dev/null)
        [ -n "$suid" ] && suid_results="$suid_results"$'\n'$suid
        [ -n "$ww" ] && ww_results="$ww_results"$'\n'$ww
    fi
done

# Drop well-known system binaries. Each pattern is anchored to the whole path,
# so a file with a similar name (for example /usr/bin/sux) is NOT hidden.
cleaned_suid=$(echo "$suid_results" | sed '/^$/d' \
    | grep -vE '^/usr/bin/(chage|gpasswd|newgrp|mount|su|umount|write|pkexec|passwd|crontab|fusermount3?|sudo)$|^/usr/sbin/(grub2-set-bootflag|pam_timestamp_check|unix_chkpwd|userhelper|mount\.nfs)$|^/usr/lib(exec)?/(polkit-1|dbus-1(\.0)?|utempter|openssh)/' \
    | sort -u)
cleaned_ww=$(echo "$ww_results" | sed '/^$/d' | sort -u)

echo "The following files have the SUID, SGID bits set, or are globally writable files:"
echo ""
echo "[Non-Standard SUID / SGID Files]:"
if [ -z "$cleaned_suid" ]; then
    echo "none"
else
    echo "$cleaned_suid"
fi
echo ""
echo "[Globally Writable Directories]:"
if [ -z "$cleaned_ww" ]; then
    echo "none"
else
    echo "$cleaned_ww"
fi
