Execute a script as root on every ssh login

Is there a possible way that I can execute a script, say abc.sh; as root user on every login to my system via SSH?

I've gone through a similar question which says to add the script execution to .bashrc file. This is not much helpful as I'd have to add it to every users' config file. Also, they'd still have ability to remove it.

Execution as root is not as important as denying the users' the power to stop its execution. The OS is debian, if that helps in any way.


Solution 1:

This is a late answer, but you can execute it on every login AND have it run as root (or any other user you want), by doing the following:

  1. Write your script, with the commands you want to run as root, and save it e.g. as /path/to/root-script.sh .
  2. Make root (or the desired user) the owner of the script.

    chown root:root /path/to/root-script.sh`
    
  3. Set the setuid bit on the script, with other desired permissions. (make sure it is not universally writable etc.)

    chmod 4755 /path/to/root-script.sh
    

    The 4 means set the setuid bit, which will cause the script to be run as the owner of the script. This is what sudo uses to ensure execution as root.

  4. To ensure it is run on every login, run the sticky-bit-set root-script.sh from within /etc/profile . The /etc/profile should be run regardless of the shell used by the user. Note this will only apply to interactive logins however.

Edit. As noted by Scott in comments, this solution does NOT generally work on any modern system with any shebang script other than Perl < 5.12.0. Modern kernels would ignore scripts with a setuid bit unless they have been patched, which would not be recommended for security reasons.

Rather, setuid only generally works on compiled binaries and [old versions of Perl][https://stackoverflow.com/questions/21597300/can-i-setuid-for-perl-script] that can use (Perl <5.12.0) with suidperl.

This Unix/Linux SE question has thorough answer of why setuid is ignored for shebang scripts, with its summarized TL;DR:

Setuid shebang is insecure but usually ignored. If you run a program with privileges (either through sudo or setuid), write native code or perl, or start the program with a wrapper that sanitizes the environment (such as sudo with the env_reset option).

Solution 2:

You could add the call into /etc/bash.bashrc - this is processed on every Bash login, so assuming your users are using Bash as their shell, it should run the script.