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.