#!/bin/sh
#
#   Search for setuid-root binaries, and put them in thier own groups.
#

# Written by Menno Duursma <druiloor@zonnet.nl>

# This program is free software. It comes without any warranty.
# Granted WTFPL Version 2, as published by Sam Hocevar, December 2004.
# See http://sam.zoy.org/wtfpl/COPYING for more details.

if [ -z "$1" ]; then
  echo "Usage: $0 <directory>"
  exit 1
else
  DIR="$1"
fi

for f in `find "$DIR" -mount -type f -uid 0 -perm +4000 -print`; do
  # Convert file names to lowercase and stuff it in F
  F=`echo $f |tr '[A-Z]' '[a-z]'| cut -d- -f1,2`

  # Create groups if they don't already exist
  if ! grep -q "^`basename $F`:" /etc/group; then
    if ! groupadd -r `basename $F` ; then
      echo "Error: groupadd  -r `basename $F`" >&2
    fi
  fi

  # See if it's suid
  if [ "`ls -l $f |awk '{print $1}' |cut -c4`" == "s" ]; then
    SUIDEXEC=yes
  else
    SUIDEXEC=no
  fi

  # See if sgid
  if [ "`ls -l $f |awk '{print $1}' |cut -c7`" == "s" ]; then
    SGIDEXEC=yes
  else
    SGIDEXEC=no
  fi

  # Set the file protection bits:
  if [ "$SUIDEXEC" == "yes" -a "$SGIDEXEC" == "yes" ]; then

    # Both SUID and SGID (procmail still worksForMe just SGID):
    if ! chmod u-s,g+s-r,o-r $f ; then
      echo "Error: chmod u-s,g+s-r,o-r $f" >&2
    fi

  elif [ "$SUIDEXEC" == "yes" ]; then

    # Change group ownership to our group
    if ! chgrp `basename $F` $f ; then
      echo "Error: chgrp `basename $F` $f" >&2
    fi
    # SUID:
    if ! chmod 4710 $f ; then
      echo "Error: chmod 4710 $f" >&2
    fi

  else
    echo "Warning: this is odd: `ls -l $f`" >&2
  fi
done

