Shell script getting superuser privilege without being run as sudo Shell script getting superuser privilege without being run as sudo shell shell

Shell script getting superuser privilege without being run as sudo


Is this expected behaviour ?

Yes, indeed, it is expected behavior. User's cached credential for sudo is responsible for it.

Is it configurable?

Yes, it is configurable.

And I think your security concern is a valid one. Running script.sh in a terminal where a sudo command is run before (within a certain timeout), will give the script superuser privilege if the script is written with explicit sudo commands.

You can avoid any script not prompting for a password when run as sudo by running it with:

sudo -k script.sh

It will ask for a password regardless of any previous sudo command/s or session.

And to run script.sh without sudo i.e with just script.sh and still prompt for a password for the sudo command/s:

You can change the timeout value (the duration sudo maintains the session) permanently:

run sudo visudo

Then change the line:

Defaults        env_reset

To

Defaults        env_reset,timestamp_timeout=0

Save and exit (ctrl+X then Y)

This will ensure that sudo asks for a password every time it is run.

Or If you don't want to change it permanently and want your script to prompt for password at least once (while maintaining a session), then you can change your script like this:

sudo -k first-command-with-sudosudo second-commandsudo thirdand so on

This script will prompt for password at least once regardless of any previous sudo command/s or session.

In case you are unaware of (or don't have access to) the content of the script script.sh (it can have sudo commands inside it or not)

And you want to be sure that any sudo command will surely prompt for password at least once, then run sudo -K (capital K) before running the script.

Now if you run script.sh and if it contains a sudo command, it will surely prompt for password.