Linux user identity switching (su, sudo)

Article directory

  • Linux User Identity Switching
    • su
      • Use Cases
    • sudo
      • Use Cases
    • visudo and /etc/sudoers
      • A single user can use all root commands, with sudoers file syntax
      • Use the function of the wheel user group to avoid passwords to process visudo
      • Limited command operations
      • Create visudo by alias
      • sudo time interval problem
      • How to use sudo with su

Linux user identity switch

What? Do you still need to switch identity in the Linux system? why is that? There may be several reasons

  1. Security: Identity switching can limit user permissions to prevent malicious operations and data leakage.
  2. Multi-user environment: In a multi-user environment, each user has its own account and permissions, and users need to be switched through identity switching.
  3. Program running: Some programs need to run with different permissions, such as administrator permissions or ordinary user permissions, and the permissions need to be switched through identity switching.
  4. System management: System administrators need to switch between different identities in order to perform different system management tasks.
  5. Learning and practice: Learning Linux system management requires understanding the operation and principle of identity switching in order to better manage and maintain the system.

So how to make ordinary users become root? There are two main ways

  • You can directly change your identity to root through [su -], but this command requires the root password. That is to say, if you want to become root through su, your general user must know the root password. .

  • Execute the root command string through [sudo command]. Since sudo needs to be set up in advance, and sudo needs to enter the user’s own password, so when multiple people manage a host, sudo is better than su, at least the root password will not flow out

su

In the Linux system, the su command is used to switch user identities, and its syntax is as follows:

su [options] [username]
options explain
Indicates switching to the target user’s environment variable, that is, switching to the target user’s home directory
-l is the same as -, which means switching to the target user’s Environment variable
-c After executing the command, exit the target user identity and return to the original user identity
-m -m is the same as -p, which means [use the current environment settings without reading the configuration file of the new user]

Use case

Suppose you are originally zhw and want to use the su command to turn yourself into root

[zhw@root ~]$ su # Now it is the identity of zhw, use su to switch root
Password: # enter password
[root@root zhw]# id # View prompt character is root
uid=0(root) gid=0(root) group=0(root) environment=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 # is indeed root
[root@root zhw]# env |grep 'zhw'
USER=zhw <== is still the identity of zhw
PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/zhw/.local/bin:/home/zhw/bin <==This has the greatest impact
MAIL=/var/spool/mail/zhw
PWD=/home/zhw <== not root's home directory
LOGNAME=zhw
#Although your UID already has root status, have you seen the above output information?
# There are still a bunch of variables that belong to the original zhw, so a lot of data still cannot be used directly
[root@root zhw]# exit <== This can exit the environment of su or Ctrl + D

Simply use [su] to switch to the root identity, and the read variable setting method is a non-login shell method. In this way, many original variables will not be modified. Since there is no environment for modifying root, many commands commonly used by root Can only be executed using absolute paths. There is also the MAIL variable. When you enter mail, the received mail is actually from the zhw user, not from root itself. So be sure to use the following cases when switching identities

Use the login shell to switch to the identity of root

[zhw@root ~]$ su -
password:
Last login: on Tue Apr 11 14:52:22 CST 2023pts/2
[root@root ~]# env |grep root
HOSTNAME=root
USER=root
MAIL=/var/spool/mail/root
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
PWD=/root
HOME=/root
LOGNAME=root
# Do you understand the difference? The next time you switch to root, remember to use su -
[root@root ~]# exit <== exit exit su environment

The above method is to make the user’s identity become root and start using the system. If you want to exit the identity of root, you have to use exit. If I at least want to execute [a command that only root can execute, and the execution is completed Just restore the original identity]?

zhw wants to execute [head -n 3 /etc/shadow] once, and knows the root password

[zhw@root ~]$ head -n 3 /etc/shadow
head: Unable to open "/etc/shadow" to read data: Insufficient permissions
[zhw@root ~]$ su - -c 'head -n 3 /etc/shadow'
password:
root:$6$0x0W5U0lAIGfNePS$fQegjEeiYdvyV7xK7zyhR9jsXzAwkB6XoA6RxpGo0X/uz8uPhblK9frf36sRtpdyNgJY4jZPQplMR1b/Hqgb9/::0:99999:7:::
bin:*:18353:0:99999:7:::
daemon:*:18353:0:99999:7:::
[zhw@root ~]$ # Pay attention to the identity of zhw after executing the command here

So if I am root or someone else, and I want to switch to some special account, I can use the following method to switch

Originally a zhw user, want to switch to pro1?

[zhw@root ~]$ su -l pro1
password:
-bash-4.2$ env |grep pro1
USER=pro1
MAIL=/var/spool/mail/pro1
PWD=/home/pro1
HOME=/home/pro1
LOGNAME=pro1
-bash-4.2$ su -
password:
Last login: on Tue Apr 11 15:19:01 CST 2023pts/2
[root@root ~]# su -l sshd
This account is currently not available. <== It actually says that this account cannot be switched?
[root@root ~]# finger sshd
Login: sshd Name: Privilege-separated SSH
Directory: /var/empty/sshd Shell: /sbin/nologin # <== The original shell is /sbin/nologin
Last login Tue Apr 11 15:24 (CST) on pts/2
No mail.
No Plan.

[root@root ~]# exit <== exit the second su
-bash-4.2$ exit <== exit first su
[zhw@root ~]$ <== This is the initial environment

Advantages of the su command:

The su command can allow a user to temporarily switch to another user identity to facilitate the execution of commands that require specific permissions.

The su command can prevent users from frequently logging in and out, and improves the system usage efficiency.

The su command can control the user’s access to the system and enhance system security.
Disadvantages of the su command:

The su command requires the user to enter the password of the target user. If the password is leaked, it may cause system security problems.

After the su command switches to the root user status, the user can execute any command, which may cause system damage or data loss.

The su command cannot control the range of user access to the system. If the target user has too many permissions, the security of the system may be reduced.

sudo

Compared with su, which needs to know the password of the newly switched user (often the password of root), the execution of sudo only needs its own password, and it can even be set to execute sudo without a password. Since sudo allows you to execute commands as other users (usually using root to execute commands), not everyone can execute sudo, but only the specification to /etc/sudoers Only users within can execute the sudo command. Let’s introduce sudo

sudo [options] [commands]
options
-u: Specifies the user identity to switch to
-b: run the command in background mode

Use case

Want to create a file named mysshd under /tmp as sshd

[root@root zhw]# sudo -u sshd touch /tmp/mysshd
[root@root zhw]# ll /tmp/mysshd
-rw-r--r--. 1 sshd sshd 0 Apr 11 15:47 /tmp/mysshd
# Note the following, the permissions of this file are established by sshd

But only root can use sudo by default, why? Because the execution of sudo is such a process

The execution flow of the sudo command is as follows:

  1. The user enters the sudo command and specifies the command to be executed.
  2. The system checks whether the user has the corresponding authority in the sudoers file, and if not, prompts that the user has no authority to execute the command.
  3. If the user has permission to execute the command, the user is asked to enter their own password, not the target user’s password.
  4. The system checks whether the password is correct, and if it is correct, switches the user to the target user identity and executes the command.
  5. After executing the command, return to the original user identity.

Therefore, the focus of sudo execution is [whether sudo can be used depends on the setting value of /etc/sudoers] Since whether it can be used is related to /etc/sudoers, of course we have to edit it sudoers file, but the content of this file has certain specifications, so it is not good to use vi to edit directly. At this time, we need to modify this file through visudo

visudo and /etc/sudoers

From the above description, we can know that if other accounts other than root want to use sudo to execute commands belonging to root, root needs to use visudo to modify /etc/sudoers first, so that the account can use all or part of root Command function, why use visudo? ?

Using the visudo command to modify the sudoers file can avoid grammatical errors, race conditions and automatic backups, improve the security and correctness of the sudoers file modification, and facilitate the management of the sudoers file by the system administrator

Generally speaking, there are several simple ways to set up visudo, here we illustrate with a few simple examples:

Single user can use all root commands, and sudoers file syntax

If we want to allow the zhw account to use any command of root, there are basically two syntaxes, the first one is to directly modify the /etc/sudoers file

[root@root zhw]# visudo
...(Omit in front)...
root ALL=(ALL) ALL # searched for this line
zhw ALL=(ALL) ALL # This line is added
...(omitted later)...

Let’s explain the above parameters (root ALL=(ALL) ALL)

  1. The first component: represents the authorized user or user group, here is the root user.
  2. The second component: indicates the host where the user or user group executes the command, here is ALL, which means that the command can be executed on any host.
  3. The third component: indicates the target user that the user or user group can switch to, here is ALL, which indicates the identity that can be switched to any user.
  4. The fourth component: indicates the command that the user or user group can execute, here is ALL, which means that any command can be executed.

Save and exit after modification, log in to the zhw user, and test it

[zhw@root ~]$ tail -n 5 /etc/shadow
tail: Unable to open "/etc/shadow" to read data: Insufficient permission
# Because it is not root, of course /etc/shadow cannot be queried
[zhw@root ~]$ sudo tail -n 5 /etc/shadow # execute through sudo
[sudo] zhw password: # Enter your own password
myuser2:$6$WHRvq32S$d40vM5Qgw8q7zelrSyCPaeugrRQE94KLICed2RHjWaru3aN6gHoycRN6PTpRIL/rx271Oiqds/M5p2me2IUd11:19458:0:99999:7:::
myuser3:$6$1EIWjK3Y$V07xoA9T2zWtWjbq.C8zbfH1jD6uF5PzqGHS2JANbJyLcLVmNr6mNTJlD6Du7O2369k756FUbouyrQJUsRwqj0:19458:0:99999:7:::
pro1:$6$JyB/VQok$uLn7kywLiGZzYE1CpwZprx5U1fc8EX6JJv2f1e50lJNByJ7Out/JidM8C4GxpAJgESpufvDQxU3iUfYEJGoMG.:19458:0:99999:7:::
pro2:$6$tStx6sam$nn6PawgEIgeqK886H1iWtuhC98h2s0BkawWMFfX98W.RyWcwaeZmL1kesXC3gRFCLf8/5TPqCr8.KzwXOogA50:19458:0:99999:7:::
pro3:$6$IAko7jZE$Mw6oy.c80tcqc/.WpXTLK3Zm7QkHCCKiX.DxyAhUARQY1N5tRAPQEPBXe0oFssxeDFxFGglSdcEud/ij8VEt/.:19458:0:99999:7:::
# See if the execution is successful, you can query the shadow

zhw can execute root commands by entering your own password. In addition, it is too troublesome to set up one by one. Can you use the user group to set up? Refer to the following plan

Using the function of wheel user group to avoid password to process visudo

Previous case blog address , Task 1 and Task 2

We established pro1, pro2, and pro3 in the previous account management case. Can these three people manage the department through the function of user group? It can be very simple, as in the following case

[root@root zhw]# visudo
...(Omit in front)...
%wheel ALL=(ALL) ALL # Remove # from this line
# Add % on the far left, which means that it is followed by a [user group], save and exit after changing
...(omitted later)...
[root@root zhw]# usermod -aG wheel pro1 # add pro1 to wheel support

The above setting value will cause [any user who joins the wheel user group can use sudo to switch any identity to operate any command], you can also change wheel to the group name you want, and then switch the identity successfully pro1 , pro2, try running with sudo

[pro1@localhost ~]$ sudo tail -n 5 /etc/shadow # The identity here is pro1
[sudo] password for pro1:
zhw:!!:19459:0:99999:7:::
csq:!!:19459:0:99999:7:::
pro1:$6$8XzICuAG$PCIjmv4s13f4x4IRcb4thG96JX6Tnl.Ots08wlnmc6Ndkgrq4u9e2EYfhWn5YLksFgEX.ySPSGlfj839f7eyh/:19459:0:99999:7:::
pro2:$6$3.4UjuHd$v1lUPlXjpZ6vn9ewVN1NicSGv5tx9BhyCmrWNWd/xBAsxlXdJJJbovrB/ohR5AUeB5VRRSHcRSGv5o3AcuhS01:19459:0:99999:7:::
pro3:$6$ARlJULFa$BVrVHjmRQp7IgS5c4ViqpgN8DDN9O5b2qbnxhzPQvxessejHO0iVqmDcEikNMelu.Mni76NIfh.V3JlUn6nTQ0:19459:0:99999:7:::

[pro2@localhost ~]$ sudo tail -n 5 /etc/shadow # The identity here is pro2
[sudo] password for pro2:
pro2 is not in the sudoers file. This matter will be reported.
[pro2@localhost ~]$

This is the immediate user group, right? If you want pro3 to also support this sudo, you don’t need to use visudo again, just use usemod to modify the user group support of pro3, let pro3 users join the wheel user group, then it can perform sudo.

Starting from Centos7, in the sudoers file, the %wheel line has been developed by default, and the old version of Centos has not been enabled

However, since we all trust these sudo users, can we achieve [use sudo without password]?

This can be achieved by:

[root@localhost ~]# visudo
.....
..
%wheel ALL=(ALL) NOPASSWD: ALL # Find this line and remove the previous #
...
....

The key point is NOPASSWD This keyword means exempting password input

Restricted command operations

Both of the above points allow the user to do anything as root, which is not always good if I want the user to only be able to perform some system tasks. For example, when myuser1 on the system can only help root change the passwords of other users, that is, when the user can only use the passwd command to help root change the passwords of other users, how should it be written? can do this

[root@localhost ~]# visudo
....
..
myuser1 ALL=(ALL) /usr/bin/passwd # Add this line of content, and the following path must use an absolute path!
...
..


In the above content, the setting value refers to [myuser1 can be switched to root and use the passwd command], it should be noted that the absolute path must be written, otherwise visudo will have a syntax error

Let’s test whether passwd is available:

[myuser1@localhost ~]$ sudo passwd myuser3 # The identity here is myuser1
[sudo] myuser1's password: # Enter myuser1's password
Change the password for user myuser3. # Change the password of myuser3
new password:
Re-enter the new password:
passwd: All authentication tokens have been successfully updated.
[myuser1@localhost ~]$ sudo passwd root # Found that root password can be changed! How can this be?
Change the password for user root.
new password:
Invalid Password: The password is a palindrome
Re-enter the new password:
passwd: All authentication tokens have been successfully updated.

The password of root can be modified by the user myuser1. The next time root logs in, he will not be able to log in. We want to cry without tears, so we need to add command parameters to limit users. The modification method is as follows

[root@localhost ~]# visudo
....
..
myuser1 ALL=(ALL) !/usr/bin/passwd,/usr/bin/passwd [A-Za-z]*,!/usr/bin/passwd root
....
..

Adding an exclamation point [ ! ] in the setting value means [not executable]. Therefore, the above line will become: [passwd any character] can be executed, but the two commands [passwd] and [passwd root] are exceptions, so myuser1 cannot modify the root password. This user can have the ability of root to help root modify the passwords of other users, but cannot modify root passwords at will.

Create visudo by alias

As mentioned in the third point above, if I have 15 users who need to join the ranks of administrators just now, do I have to set the above long 15 lines? And if you want to modify the command or add a new command, it is very troublesome to set each line. Is there an easier way to do this? You can set an alias, and the alias of visudo can be [command alias, account alias, host alias], etc. Here we only introduce the account alias

If my pro1, pro2, pro3, and myuser1, myuser2 are to be added to the sudo list of the above-mentioned password administrator, then I can create an account, alias ADMPW, and then process this name, the processing method is as follows

[root@localhost ~]# visudo # Here is the root identity
....
..
User_Alias ADMPW = pro1, pro2, pro3, myuser1, myuser2
Cmnd_Alias ADMPWCOM = !/usr/bin/passwd,/usr/bin/passwd [A-Za-z]*, !/usr/bin/passwd root
ADMPW ALL = (root) ADMPWCOM
....
..

I create a new account through User_Alias, the account name must use uppercase characters, including Cmnd_Alias (command alias), Host_Alias (source host alias), all need to use uppercase characters.

User_Alias ADMPW = pro1, pro2, pro3, myuser1, myuser2

This line specifies a user alias named ADMPW, which contains 5 users: pro1, pro2, pro3, myuser1 and myuser2

Cmnd_Alias ADMPWCOM = !/usr/bin/passwd,/usr/bin/passwd [A-Za-z]* , !/usr/bin/passwd root
This line specifies a command alias named ADMPWCOM, which contains 3 commands: !/usr/bin/passwd, /usr/bin/passwd [A-Za-z]* !/usr/bin/passwd root. Among them, !/usr/bin/passwd indicates that the passwd command is prohibited, /usr/bin/passwd [A-Za-z]* indicates that the passwd command is used to modify the password of a non-root user, and !/usr/bin/passwd root indicates that the password is prohibited Run the passwd command to change the password of the root user.

ADMPW ALL = (root) ADMPWCOM
This line specifies an authorization policy that allows all users in the ADMPW user alias to execute the commands in the ADMPWCOM command alias in any way (ALL) on all hosts, but must be executed as the root user. That is, only users in the ADMPW user alias can execute the commands in the ADMPWCOM command alias, and they must be executed as the root user.

== When we want to modify it in the future, we only need to modify the two lines User_Alias and Cmnd_Alias, and the settings are more flexible ==

Sudo time interval problem

Maybe you have discovered that if we use the same account to repeatedly operate sudo to run commands in a short period of time, when we execute sudo for the second time, we don’t need our own password, and sudo will still run correctly. why? The first time you execute sudo, you need to enter a password, because you are worried that because the user leaves your seat temporarily, someone will come to your seat to use your account to operate the system, so you need to enter the password to reconfirm your identity.

If the interval between executing sudo twice is within 5 minutes, then you don’t need to re-enter the password when you execute sudo again. This is because the system believes that you will not leave within 5 minutes. However, the interval between two sudo operations exceeds 5 minutes minutes, you will have to re-enter your password

How to use sudo with su

Many times we need to perform a lot of root work, so it is annoying to execute sudo all the time, so is there a way to use sudo with su to change the identity to root in one go, and use the user’s own password to become root? as follows

[root@localhost ~]# visudo
User_Alias ADMPW = pro1, pro2, pro3, myuser1, myuser2
ADMPW ALL = (root) /bin/su-
[pro2@localhost ~]$ sudo su -
[sudo] password for pro2:
Last login: on Wed Apr 12 17:36:49 CST 2023pts/2
[root@localhost ~]#

As long as we enter [sudo su -] and enter [our password], we will immediately become root. Not only the root password will not leak out, user management is also very convenient. These users you join are all users you can trust

Summarize:

The sudo command is more secure and flexible, and can provide finer-grained authorization control, which is suitable for authority management in a multi-user environment;

The su command is more convenient. You can switch identities directly on the command line, which is suitable for working in a single-user environment. When using these two commands, you need to choose the appropriate method according to the actual situation to avoid unnecessary troubles caused by misoperation.

This article refers to the book "Bird Brother's Linux Private Kitchen"