I can add the status of a sudo session to the bash prompt like this:
function sudo_active() {
if sudo -n /bin/true 2> /dev/null
then
printf '(sudo) '
fi
}
PS1="$PS1"'$(sudo_active)'
This way I can run a series of sudo commands
and afterward I'll know if the sudo session is still active or not.
I can end the session early with sudo -k
,
close the shell,
or just remember to be careful.
One issue with this approach
is that every time a new prompt runs without sudo privileges
it adds a message like this to the system log:
sudo[25653]: myusername : a password is required ; TTY=pts/13 ; PWD=/home/myusername/ ; USER=root ; COMMAND=/bin/true
The other problem is that because this runs a sudo
command
in the prompt every time,
it will re-extend the timeout every time I run a command
(depending on the value of passwd_timeout
),
even if I don't run a command that requires sudo
.
Is there a way I can test if the sudo session is still active
and show this in the bash prompt
without continually re-extending the session as a side effect?
Best Answer
You can use the timestamp file that sudo creates per-user to find how long ago a sudo command was used by that user; if it is further than the configured
timestamp_timeout
(default 5 minutes), then a new sudo will need a password.The per-user file is created under
/var/run/sudo/ts/
(on my system). Its format is partially described inman sudoers
and you can see from the sources timestamp.c and check.h that it consists of several records described by the structstruct timestamp_entry_v1
or the newerstruct timestamp_entry
.The git version is newer than the sources corresponding to my old-ish system so I'm using the older struct, version 1. You may need need the newer version 2 with an extra field.
Here's a minimal C program to dump the records for a hard-wired user:
Compiling and running this setuid root on my system gave me lines like
The first entry of type 4 is used to lock the records. The other lines can be per-tty and so on. flags of 1 are for a disabled entry (for example due to
sudo -k
). The last line was for my uid 1000 having done a sudo command 12 seconds ago from process 4378. Since this is less than 5*60 seconds, further sudo's do not yet need a password.