Search code examples
linuxbashshellpermissionssudo

Shell script getting superuser privilege without being run as sudo


Here is my script:

script.sh:

sudo cat /etc/passwd-

If I am in a sudo session (e.g I ran an other command with sudo a few minutes ago), and now run

script.sh

The script will get sudo access. However if I run cat /etc/passwd-/, I will get a permission denied error.

As a user, I wouldn't expect script.sh to be able to get super user privileges so simply (e.g without me giving access to superuser privileges with sudo script.sh).

Is this expected behavior ? Is it configurable ?

I see that behavior as being completely similar to sudo su, e,g potentially giving superuser access to any script you run in that session, but even worse, because you might not even be aware of it, and don't know when it ends (at least not without checking manually)


Solution

  • 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-sudo
    sudo second-command
    sudo third
    and 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.