Hacking Linux Exposed

About
Authors
Contents
Reviews
Foreword
Purchase

Articles
Books
Sourcecode
Tools
Errata

Home

 


(view this code in a separate window)

#!/bin/sh -
#
# visudopw
#
# Allow admin but non-root users to edit
# the password file.  Called via sudo.
#
# Copyright 2001, Bri Hatch
#
# Released under the GPL.  See COPYING file
# for more information.

# Create a directory for temporary files.
# Because we only want to allow one instance to edit the file
# at one time, we will use a common directory as a locking
# mechanism. If this fails, the superuser may have to recover
# the lock manually.

TMPDIR=/tmp/vipw.lock
TMPFILE=$TMPDIR/passwd
ORIGFILE=$TMPDIR/passwd.orig

umask 077
if ! mkdir $TMPDIR ; then
	echo "Password file is locked. Try back later"
	exit 255
fi

# Copy the password file to a temporary file for editing by
# the user "nobody". It must be owned and writable by nobody.

cp /etc/passwd $TMPFILE
chown nobody $TMPFILE

# Copy the password file to a non-writable file for later comparison
cp /etc/passwd $ORIGFILE

# Set a default editor if one is not already specified
: ${EDITOR:=/bin/vi}


# Now let the user edit the file as user "nobody"
su nobody -c "$EDITOR $TMPFILE"

# Now that the user edits are complete, apply the sanity checks
# This is left as a reader exercise...
#
# 1. Check to see if modifications have been made?
#    Compare /tmp/vipw.lock/passwd to /tmp/vipw.lock/passwd.orig
#    and exit if no change.
# 2. Check that no system accounts have been modified.
# 3. Check that no system accounts have been added.
# 4. Check that no system accounts have been deleted.
# 5. Perform formatting checking to insure a working file
# 6. Check to see if modifications have been made to the real file
#    Compare /etc/passwd to /tmp/vipw.lock/passwd.orig
#    and exit with an error if changes present.


# Finally, install the new password file.
cat /tmp/vipw.lock/passwd > /etc/passwd

rm $ORIGFILE $TMPFILE
rmdir $TMPDIR