#!/bin/sh --

# Check :include: aliases (in files configured in sendmail.cf) and .forward
# files to make sure the files and their parent directory paths all have
# proper permissions.  And check the master alias file(s) too.
#
# See http://www.sendmail.org/sun-specific/migration.html#Security for details.
#
# Copyright (c) 1998-2000 by Sun Microsystems, Inc.
# All Rights Reserved.
#
# @(#)check-permissions.sh	1.8 (Sun) 08/18/00
# ident	"@(#)check-permissions.sh	1.8	00/08/18 SMI"

PATH=/bin

# Check the group- and world-writable bits on the given file.

analyze() {
	case "`ls -Lldn $1`" in
		?????w??w?*) 
			echo $2: $1 is group and world writable
			bogus_dirs=true ;;
		????????w?*) 
			echo $2: $1 is world writable
			bogus_dirs=true ;;
		?????w????*) 
			echo $2: $1 is group writable
			bogus_dirs=true ;;
	esac
}

# Break down the given file name into its components, and call analyze with
# each of them.  E.g., an argument of /usr/local/aliases/foo.list would call
# analyze in turn with arguments:
# * /usr/local/aliases/foo.list
# * /usr/local/aliases
# * /usr/local
# * /usr

break_down() {
	for j in `echo $1 | \
		awk '{
			n = split($0, parts, "/");
			for (i = n; i >= 2; i--){
				string = "";
				for (j = 2; j <= i; j++){
					string = sprintf("%s/%s", string, parts[j]);
				}
				print string
			}
		}'` "/"
	do
		analyze $j $1
	done
}

config=/etc/mail/sendmail.cf
bogus_dirs=false

afl1=`grep "^OA" $config | sed 's/^OA//' | sed 's/,/ /g' | sed 's/.*://'`
afl2=`grep "^O AliasFile=" $config | sed 's/^O AliasFile=//' | \
    sed 's/,/ /g' | sed 's/.*://'`

# These should be OK themselves, but other packages may have screwed up the
# permissions on /etc or /etc/mail .  And best to check in case non-standard
# alias paths are used.

break_down $afl1 $afl2

# Find all valid :include: files used in alias files configured in sendmail.cf

for i in `sed 's/^[#].*$//' $afl1 $afl2 | \
	grep :include: | \
	sed 's/.*:include://' | \
	sed 's/,.*$//'`
do
	break_down $i
done

# Check .forward files as well.  If the argument "ALL" is given, do it for
# everyone.  If no argument to the script is given, just do it for the current
# user.  O/w, do it for all arguments.

if [ $# -eq 0 ] ; then
	arg=`who am i | awk '{print $1}'`
elif [ $1 = "ALL" ] ; then
	arg=""
else
	arg="$*"
fi

for i in `getent passwd $arg | nawk '{FS=":";print $6}'`
do
	if [ -f $i/.forward ] ; then
		break_down $i/.forward
	fi
done

$bogus_dirs || echo "No unsafe directories found."
