Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most reliable way to identify the current user through a sudo

I have an application that may or may not be run while users are sudo'ed to a shared user account. I would like to reliably identify who the real user is for a sort of "honor-system" ACL. I think there's some way by tracing parent/group/session process ids the way that the pstree command does, but I'm not sure how to do that best or if there are better alternatives.

I tried getlogin() originally. That works if ./myapp is used, but it fails with 'cat input | ./myapp` (because the "controlling terminal" is a pipe owned by the shared account).

I'd rather not trust environment variables, as I don't want my "honor system" to be completely thwarted by a simply unset, when the information is still available elsewhere.

I'd also like to avoid forcing a lookup in the password database, as that is a remote RPC (NIS or LDAP) and I'm pretty sure wtmp already contains the information I need.

like image 893
Tom Avatar asked Oct 20 '25 09:10

Tom


2 Answers

For a shell script, you might use this to get the sudo'ing user:

WHO=$(who am i | sed -e 's/ .*//'`)

and extract the id from the login using:

ID_WHO=$(id -u $WHO)

I'll ferret out the C library equivalent later.

like image 171
martin clayton Avatar answered Oct 21 '25 23:10

martin clayton


sudo sets the environment variables SUDO_USER, SUDO_UID, and SUDO_GID.

You can test this with:

$ sudo env
[sudo] password for shteef: 
TERM=xterm
# [...snip...]
SHELL=/bin/bash
LOGNAME=root
USER=root
USERNAME=root
SUDO_COMMAND=/usr/bin/env
SUDO_USER=shteef
SUDO_UID=1000
SUDO_GID=1000

But if your users have shell access on the shared account, then I suppose you cannot blindly trust this either.

like image 36
Stéphan Kochen Avatar answered Oct 21 '25 22:10

Stéphan Kochen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!