I got a bit of a puzzle at work today. I had a script that was executed as another user via sudo, but I wanted to access the original username in the script, to know who was executing it. Sudoers manual suggest working with “Defaults env_keep“. Looking into the /etc/sudoers, I noticed that $USERNAME variable was whitelisted (in line #3 below):
Defaults env_reset Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS" Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE" Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES" Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE" Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
So, I tried to use the $USERNAME variable in my script but it was coming up with empty results. That made me look deeper into default Bash initialization, and I found out that $USERNAME variable setup wasn’t a part of it. However, $LOGNAME was (in /etc/profile). I think, so few people actually use it that nobody noticed or bothered about it until now. Anyway, the solution now was obvious – simply add $LOGNAME variable to the sudo white list. Appending this line to the above env_keep ones did the job:
Defaults env_keep += "LOGNAME"
There. In hopes it will help future generations…
P.S.: All that happened on a more or less default installation of CentOS 6.3, but I’m sure other Red Hat based distributions have a similar issue.
P.P.S.: If your script is ALWAYS invoked via sudo, also have a look at $SUDO_UID, $SUDO_GID, and $SUDO_USER variables.
Maria Iacob liked this on Facebook.
SUDO_USER, SUDO_UID, SUDO_GID?
Yup, these are useful, but only if you ALWAYS invoke the script via sudo. I’ll add them to the post anyway. :)
Or you could ask ‘who am i’ :)
whoami under sudo reports the sudo user, not the one who invoked the script
You’re right, my bad.
meh.. ${SUDO_USER:-$USER}
On CentOS, $USER is not white listed by default … :)
It doesn’t have to be. Fucking with sudo configs makes scripts non-portable.
Brain fart .. yeah, I see now. I think that it’s actually a bug that USERNAME is white-listed, while not set, and LOGNAME is set, but not white-listed.