Sunday, March 15, 2009

Sudo Voodoo

The Unix sudo command can be quite useful when one needs to give another user access to a select group of commands that need to be run as a certain user without having to give up the password for that user account. The easiest way to do this is to edit the sudoers file (usually in /etc/sudoers). The file allows an administrator to configure a list of commands that a user can execute as another user without a password. The policy file follows a fairly simple context-free grammer (defined quite concisely in the man page for sudoers). There are a few things to keep in mind when editing the sudoers file:

  • You must edit the file using the visudo command as root
  • When defining a command, you must use the fully qualified path to the command. The system will report a syntax error if you attempt to save the sudoers file with a command that does not start with a /character. This makes sense when one condiders that the whole point of the command is to run something as another user. That being the case, the system can make no guarantees as to what the working directory will be when running the command so requiring the absolute path is a reasonable constraint.
  • The command(s) defined in the sudoers file must exactly match the command to be run.


Here is an example of a simple sudoers configuration:

Cmnd_Alias SOME_COMMANDS = /home/somedir/command1.sh,/home/somedir/command2.sh

user1 ALL=(ALL) NOPASSWD: SOME_COMMANDS

The first line sets up a "command alias" or a list of commands specified using their absolute path with each command separated by a comma. If you needed to pass a comma into a command as an argument, for example, it would need to be escaped using the backslash character.

The next line tells the system that the user user1 is allowed to run any of the commands listed in SOME_COMMANDS as any other user without having to specify a password.

Once you've installed these lines in the sudoers policy file, the user1 user can log in and execute sudo -u user2/home/somedir/command1.sh to run the command1.sh script as user2 without ever having to provide user2's credentials.

For a full treatment of how to configure sudo policies, the man pages are the best resource.

No comments:

Post a Comment