views:

2385

answers:

4

I need to edit /etc/sudoers from a script to add/remove stuff from white lists.

Assuming I have a command that would work on a normal file, how could I apply it to .etc/sudoers?

Can I copy and modify it, then have visudo replace the original with the modified copy? By providing my own script in EDITOR?

Or can I just use the same locks and cp?

The question is more about potential issues than about just finding something that works.

+6  A: 

You should make your edits to a temporary file, then use visudo -c -f sudoers.temp to confirm that the changes are valid and then copy it over the top of /etc/sudoers

#!/bin/sh
if [ -f "/etc/sudoers.tmp" ]; then
    exit 1
fi
touch /etc/sudoers.tmp
edit_sudoers /tmp/sudoers.new
visudo -c -f /tmp/sudoers.new
if [ "$?" -eq "0" ]; then
    cp /tmp/sudoers.new /etc/sudoers
fi
rm /etc/sudoers.tmp
Brian C. Lane
It looks like you're using sudoers.tmp as a lock file, not sure how that confirms changes are valid. Shouldn't we be checking the exit status of visudo to make sure there are no errors?
converter42
/etc/sudoers.tmp is the lockfile checked by visudo in interactive mode. visudo -c -f returns a 1 if there was an error, hence the check of the return code.
Brian C. Lane
I'm worried about using sudoers.tmp, as it looks like using visudo's internal interface, i.e., a hack. Is it standard, meaning that it is guaranteed to always be sudoers.tmp that gets used as the lock? Or do they have the freedom to change that in future?
n-alexander
it also produces a race condition, doesn't it?
n-alexander
need to use lockfile instead of test/touch
n-alexander
The manpage says it uses /tmp/sudoers.tmp so that is currently the standard. Of course it could change in the future. And yes, you are right there is a race condition.
Brian C. Lane
A: 

visudo is supposed to be the human interface for editing /etc/sudoers. You can achieve the same by replacing the file directly, but you have to take care yourself about concurrent editing and syntax validation. Mind the r--r----- permissions.

ngn
+3  A: 

Set up a custom editor. Basically it will be a script that accepts the filename (in this case /etc/sudoers.tmp), and modify and save that in place. So you could just write out to that file. When you are done, exit the script, and visudo will take care of modifying the actual sudoers file for you.

sudo EDITOR=/path/to/my_dummy_editor.sh visudo
Ali A
A: 

Use visudo for this with a custom editor. This solves all the race conditions and "hack" problems with Brian's solution.

if [ -z "$1" ]; then
  echo "Starting up visudo with this script as first parameter"
  export EDITOR=$0 && sudo -E visudo
else
  echo "Changing sudoers"
  echo "# Dummy change to sudoers" >> $1
fi

This script will add the line "# Dummy change to sudoers" to the end of sudoers. No hacks and no race conditions.

sstendal