How does the "su" command work?

8,378

Solution 1

The man page for su is quite clear on this point:

The command will be executed by the shell specified in /etc/passwd for the target user.

and

-s, --shell SHELL The shell that will be invoked.

-m, -p, --preserve-environment Preserve the current environment [...]

The reason you land in a bash shell after calling su - is that this the default shell for root. I can see three ways to override this default shell:

  1. Call su -s /path/to/your/shell instead of just su
  2. Ensure export SHELL=/path/to/yourshell has been set and then call su -m
  3. Change the default shell for root in /etc/passwd (not recommended)

Solution 2

Is there any way to make my own su provision, maybe even my custom su executable which just asks for the root password and gives you the privileges, sending you back to the shell you were using without taking you to bash? Thanks a lot.

No. The privilege elevation mechanism in Unix involves the execution of a new process. The su executable has a special permission bit on it, called the "set-user-ID bit" or "setuid" which causes it to execute such that the effective user ID of the process is that of the owner of that executable file.

If su successfully authenticates, it then executes a new shell.

The usual way to have superuser powers while staying in the same shell is to run individual commands in privileged mode with the sudo utility.

If you often administer some machine, you can set up a custom environment for your use as the root user. When you become root, just execute that shell that you like, and set up its configuration files in root's home directory.

$ su
password:
root # exec /path/to/favorite/shell

If you're the boss, you could make that shell root's login shell.

Share:
8,378

Related videos on Youtube

GNU Geek
Author by

GNU Geek

Updated on September 18, 2022

Comments

  • GNU Geek
    GNU Geek over 1 year

    I'm trying to write my own shell without looking at any bash source code, but there's one thing I'm not able to do. Whenever I run "su" from any custom shell including my own, it takes my password and takes me to the bash prompt with the hash indicating root power. I've entered code to make sure my shell gives the hash prompt itself when it has root power but thats only when run as root since whenever I try to become root with su from within my shell, it forcibly takes me to bash. Is there any way to make my own su provision, maybe even my custom su executable which just asks for the root password and gives you the privileges, sending you back to the shell you were using without taking you to bash? Thanks a lot.

  • GNU Geek
    GNU Geek almost 7 years
    Thanks! With that info I can begin to seriously use my shell.
  • GNU Geek
    GNU Geek almost 7 years
    Welp, atleast I know it can't be done. Thanks a lot, this will help in my further development.