MacOS sudo wtf

19 Oct 2017 22:55 | macOS | security

I've just discovered something totally batshit about sudo on macOS.

Spot the difference..

Linux:

$ ls -la /tmp/wtf
ls: cannot access '/tmp/wtf': No such file or directory
$ echo "touch /tmp/wtf" >> ~/.bashrc
$ sudo bash
# ls -la /tmp/wtf
ls: cannot access '/tmp/wtf': No such file or directory

macOS:

$ ls -la /tmp/wtf
ls: /tmp/wtf: No such file or directory
$ echo "touch /tmp/wtf" >> ~/.bashrc
$ sudo bash
# ls -la /tmp/wtf
-rw-r--r--  1 root  wheel  0 19 Oct 22:58 /tmp/wtf

!!!!!

So when sudo'ing to root it executes ~/.bashrc in the original user's home
directory.. as root?!

Just to make sure I wasn't going crazy or that this wasn't an artefact of my
customised dotfiles I tried it on a fresh 10.13 VM with a fresh user account.

---- Update 19/10 23:16

Turns out this is the default on macOS:

# grep HOME /etc/sudoers
Defaults env_keep += "HOME MAIL"

So when you elevate you retain your home dir and it will execute the dotfiles
there rather than in /var/root/

Madness.