How do I tell sudo to write files with a umask of 0022?

11

7

I recently upgrading to Snow Leopard. I have noticed that some files written by MacPorts are installed with the wrong permission -- they are written with a umask of 0077. I think I have narrowed down the problem:

  1. The port command is invoked via sudo.
  2. My .bashrc file specifies a umask of 0077.
  3. On older versions of OS X (10.5 and below), sudo used the umask of the root user (which was 0022); however, now it uses my umask of 0077.

Is there anyway to have sudo use the old behavior? Right now, it's kind of annoying because I have to use sudo to run simple commands like port installed, port outdated, etc.

(The problem is described in more detail in this MacPorts ticket.)

Edit

I discovered the umask option for sudo, and in /etc/sudoers I added the following line:

Defaults umask=0022

However, this did not function as desired, because the real umask used by sudo is the union of the user mask with this default mask. In order to override the behaviour of sudo's umask and use the default directly (i.e., not the union of the user and default sudo mask), one can add the following:

Defaults umask_override

mipadi

Posted 2009-12-07T16:19:05.193

Reputation: 3 980

Answers

6

I ended up adding the following to my .bashrc configuration script:

# Mimic old behavior of `sudo` on OS X Snow Leopard
sudo() {
    old=$(umask)
    umask 0022
    command sudo "$@"
    umask $old
}

mipadi

Posted 2009-12-07T16:19:05.193

Reputation: 3 980

7

Mac OS X 10.7 (Lion) finally has a version of sudo that supports umask_override. For the record, this works for me:

Defaults umask_override
Defaults umask=0022

Alec Thomas

Posted 2009-12-07T16:19:05.193

Reputation: 171

1Can you make this work on a per command basis? I would like to umask 0022 normally, but then invoke umask 0006 in a single circumstance, but the above ignores that. – Michael – 2013-09-15T23:59:44.727

3

how about:

sudo22() {
   local UMASK=`umask`;
   umask 22;
   sudo "$@";
   umask $UMASK
}

akira

Posted 2009-12-07T16:19:05.193

Reputation: 52 754

2

For the record: the current version of sudo as a new option 'umask_override', which should prevent the umask's from being merged, so you should be able to lower the umask, too. Sadly, Mac OS X 10.6.6 does not seem to sport this version of sudo ...

Gabriel

Posted 2009-12-07T16:19:05.193

Reputation: 21

2

With your .bashrc

if [[ $EUID -eq 0 ]]; then
   umask 0022
else
   umask 0077
fi

Darren Hall

Posted 2009-12-07T16:19:05.193

Reputation: 6 354

2Good idea! Unfortunately, a little investigation shows that Snow Leopard's sudo doesn't actually (re-)source .bashrc, but inherits the current setting from the user that invoked sudo. – mipadi – 2009-12-07T18:26:28.337

You'll have to use the function workaround as listed in the other answer then. – Darren Hall – 2009-12-07T22:29:28.113