[user - authorization - permission management]

linux user management

Basic user overview

What are users

Users refer to those who can log in to the linux system normally, such as users who log in to King glory and users who log in to QQ

Why users

  • 1. Each process (running program) on the system needs a specific user;
  • 2. In the company, ordinary users are usually used to manage the server. Because the root permission is too large, it is easy to cause failure and irreparable conditions

What categories do users have

  • Meaning agreed in the system
usermeaning
0Super administrator, with the highest authority, has strong destructive ability
1~200System user, used to run the system's own process. It is created by default
201~999System users are used to run programs installed by users, so such users do not need to log in to the system
1000+Ordinary users, who can log in to the system normally, have small permissions and can perform limited tasks

Query user ID information

  • Use the id command to query the information of the currently logged in user
[root@localhost ~]# id       #View the currently logged in user information
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@localhost ~]# id zj		#View information about other users
uid=1041(zj) gid=1041(zj) groups=1041(zj)

User related profiles

  • When we create a new user, the system will store the user information in / etc/passwd and the password separately in / etc/shadow. These two files are very important and cannot be deleted or modified easily

passwd file

  • /The explanation of the etc/passwd configuration file is as follows:

shadow file

  • /etc/shadow configuration file, as shown below
  • Example of changing a user password using chage
-d //Set the last time to change the password. 0. The next time you log in to the system, you will be forced to change the password
-m //Set the "minimum number of days" to be used between user password changes
-M //Set the "maximum number of days" to be used between user password changes
-W //Set the password change warning time and set the expired warning days to "warning days"
-I //After the password expiration days are set, the password is invalid
-E //Set the user expiration time. You cannot log in after the account becomes invalid
-l //Display user information


#The modification time is August 31, 2014, which matches the time in the figure for subsequent verification
[root@xuliangwei ~]# date -s '20140831'
Sun Aug 31 00:00:00 CST 2014
[root@xuliangwei ~]# date
Sun Aug 31 00:00:01 CST 2014
[root@xuliangwei ~]# usereadd bgx1
[root@xuliangwei ~]# echo "123" |passwd --stdin bgx1
[root@xuliangwei ~]# tail -1 /etc/shadow
bgx1:!!:16312:0:99999:7:::


#Set the time when the password was last modified
[root@xuliangwei ~]# chage -d "2014-09-01" bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:0:99999:7:::

#Set minimum password usage time
[root@xuliangwei ~]# chage -m 2 bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:99999:7:::

#Set maximum password usage time
[root@xuliangwei ~]# chage -M 15 bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:15:7:::

#Set password warning time
[root@xuliangwei ~]# chage -W 6 bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:15:6:::
[root@xuliangwei ~]# chage -W 7 bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:15:7:::

#Set password expiration time
[root@xuliangwei ~]# chage -I 5 bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:15:6:5::

#Set user expiration time
[root@xuliangwei ~]# chage -E "20115-08-31" bgx1
[root@xuliangwei ~]# tail -n1 /etc/shadow
bgx1:!!:16314:2:15:6:5:6627567:

[root@xuliangwei ~]# chage -l bgx1
Last password change			: Sep 01, 2014              #Last password change time
Password expires				: Sep 16, 2014      #Password expiration time
Password inactive				: Sep 21, 2014      #Password expiration time
Account expires					: Aug 31, 2015      #User failure time
Minimum number of days between password change      : 2     #Minimum password usage time
Maximum number of days between password change      : 15   #Maximum password usage time
Number of days of warning before password expires   : 7        #Warning days before password expiration



#How to verify? Only adjust the time as follows:
1.Verify whether ordinary users can change passwords, There is no need to adjust the time.
2.After ordinary users log in the system, You will be prompted with a warning about how many days left for the password to expire
[root@xuliangwei ~]# date -s "2014-09-12"

3.After ordinary users log in the system, Mandatory password change
[root@xuliangwei ~]# date -s "2014-09-18"

4.After ordinary users log in the system, Prompt that the account has expired
[root@xuliangwei ~]# date -s "2014-09-23"

User related commands

Add user useradd

option
-u			#Specifies the UID of the user to be created. No conflicts are allowed
-g			#Specify the base group to create the user
-G			#Specify additional groups to create users, separated by commas. Multiple additional groups can be added
-d			#Specify the user home directory to create
-s			#Specify the bash shell to create the user
-c			#Specify the comment information to create the user
-M			#Do not create home directory for users created
-r			#Create a system account, and there is no home directory by default

Add user instance

Example 1

  • Create test user
  • The user ID is 6966
  • The basic group is opt and the additional group is dev
  • Comment information HelloWord, login shell: / bin/bash
[root@localhost ~]# groupadd opt
[root@localhost ~]# groupadd dev
[root@localhost ~]# useradd -u 6966 -g opt -G dev -c "HelloWord" -s /bin/bash test

Example 2

  • Create a test1 system user
  • This user does not need a home directory
  • This user does not need to log in to the system
 [root@localhost ~]# useradd -r tset1 -M -s /sbin/nologin`

Modify user usermod

option
-u			#Specifies the UID of the modified user
-g			#Specifies the base group of the modified user
-G			#Specify the additional group of the modified user, separate multiple additional groups with commas, and overwrite the original additional group
-d			#Specify and modify user home directory
-s			#Specifies the bash shell of the modified user
-c			#Specifies to modify the user's comment information

-l			#Specify the login name of the user to modify
-L			#Specify the user to lock
-U			#Specify the user to unlock

Modify user instance

Example 1

  • Modify test user
  • uid is 5008
  • The basic group is network, and the additional group is opt dev sa
  • The annotation information is student and the login name is new_test
[root@localhost ~]# usermod -u 5008 -g network -G opt,dev,sa -l new_test -c "student" test`

Example 2

  • Modify new_test user
  • Is new_test user configuration password
  • Lock the user and test the remote connection login
  • Unlock the user and test the connection login again
Change password 1:[root@localhost ~]# echo "123" |passwd --stdin new_test

Change password 2:[root@localhost ~]# passwd new_test
Changing password for user new_test.
New password: 
BAD PASSWORD: The password is a palindrome
Retype new password: 
passwd: all authentication tokens updated successfully.

[root@localhost ~]# usermod -L new_test  	#Cannot log in
[root@localhost ~]# usermod -U new_test		#You can log in


Delete user userdel

Delete user instance

Example 1

  • Delete new_test
  • Delete with home directory
[root@localhost home]# userdel -r new_test

Example 2

  • Batch delete all useless users created in the system
  • Extract useless user names using awk
  • Delete user's command using sed splice
  • Call the userdel command and delete it together with the home directory
[root@localhost home]# awk -F ':' '$3>1000{print $1}' /etc/passwd | sed -r 's#(.*)#userdel -r \1#g'|bash

Set password passwd

  • Set password using passwd
  • 1. Ordinary users are only allowed to change their own passwords and cannot change the passwords of others, and the password length must be 8 characters
  • 2. The administrator is allowed to modify the password of any user, regardless of the password length
  • Recommended password protection kit tool link: lastpass official website

Interactive password setting

[root@localhost ~]# passwd 			#Change password for current user
[root@localhost ~]# passwd root		#Change password for root user
[root@localhost ~]# passwd drzk		#Change the password for drzk users. Ordinary users can only change their password at home

Non interactive password setting

  • Non interactive simple password setting
[root@localhost ~]# echo "123" |passwd --stdin new_test
  • Non interactive setting random password
[root@localhost ~]# yum install -y expect
[root@localhost ~]# echo $(mkpasswd -l 10 -d 2 -c 2 -C 2 -s4)| tee pass.txt|passwd --stdin zhaojie

linux user group management

What are user groups

  • Group is a logical definition
  • Logically summarize multiple users into a group. When we operate on a group, it is actually equivalent to operating on all users in the group.

There are several categories of groups

  • For users, components are divided into these categories

Default group: if no group is specified when creating a user, a group with the same name as the user is created by default
Basic group: the user has and can only have one basic group, which can be specified with - g when creating
Additional groups: users can have multiple additional groups, which are specified with - G when creating

Group related profiles

  • The group account information is saved in / etc/group and / etc/gshadow files, focusing on group

group file

  • /etc/group configuration file interpretation

gshadow file

  • /etc/gshadow file

User group related commands

Add group groupadd

option
-f			#If the group already exists, the status of successful creation will be prompted
-g			#Set GID for the new group. If GID already exists, it will prompt that GID already exists
-r			#Create a system group

Modify group groupmod

option
-g			#Modify group GID
-o: 		#Same as groupadd
-n			#Rename to new group

Delete groupdel

[root@localhost ~]#groupdel group name

How do ordinary users raise rights

su and sudo

  • 1. Switch the identity of su switch user, log in as an ordinary user, and then use the su command to switch to root
    • Advantages: simple
    • Disadvantages: you need to know the root password
  • 2.sudo authorization. When you need to use root permission, you need not switch to root
    • Advantages: safe and convenient
    • Disadvantages: rules need to be defined in advance, which is complex

su command identity switching

  • Before using su and changing identity, we need shell login classification, environment variables and loading order of configuration files

Shell login classification

  • To log in to the shell, you need to enter the user name and password to enter the shell
  • The non login shell can enter the shell without entering the user name and password

Environment variable profile

  • profile class file: set environment variables, scripts and commands to run before login
  • bashrc class file: set local variables and define command aliases
  • User profile
    • ~/.bash_profile
    • ~/.bashrc
  • Global environment variables:
    • /etc/profile
    • /etc/profile.d/*.sh
    • /etc/basrc
  • Loading order of login shell configuration file: / etc / profile - > / etc / profile. D / *. SH - > /. Bash_ profile->/.bashrc->/etc/bashrc
  • Loading order of non login shell configuration file: /. Bashrc - > / etc / bashrc - > / etc / profile. D / *. Sh

Relationship between su and environment variables

  • su - username is a login shell
  • su username is a non login shell
    • Difference: loading environment variables is different
1.For ordinary users su Switch to root User, input required root Super administrator password
[zhaojie@localhost ~]$ su - root
Password: 

2.Execute a service as a user, using su -c username
 [zhaojie@localhost ~]$ su - zhaojie -c 'ifconfig'

sudo command right raising

The su command needs to get the root administrator password when switching user identities. If a user divulges the root password, the system will be very insecure. In order to improve this problem, the current sudo is available

sudo fast start

  • Quickly configure sudo mode
1.Add user wheel Group, default wheel Group has sudo jurisdiction
 [root@localhost ~]# usermod -G wheel zhaojie
2.Switch to normal user identity
[root@localhost ~]# su - zhaojie 
3.Ordinary users cannot be deleted under normal circumstances/opt catalogue
[zhaojie@localhost ~]$ 	rm -rf /opt/
rm: cannot remove `/opt: Permission	denied
4.use sudo Raise the right, and then enter the common user password. Normally, unauthorized users can be deleted/opt catalogue
[zhaojie@localhost ~]$ sudo rm -rf /opt
5.In the later stage, you can view the operations performed by ordinary users in authorization raising through the audit log
[root@localhost ~]# tail -f /var/log/secure

linux basic permissions

Introduction to linux permissions

What are permissions

  • Permission is used to restrict the user's operation on the system
  • Permission means that a specific user has a specific right to use system resources

Why do I need permissions

  • Linux is a multi-user operating system. For each user, the protection of personal privacy is very important, so it is necessary to divide permissions
    • 1. Security: reduce the risk of false deletion and reduce the risk of human caused failure and data leakage
    • 2. Data isolation: different permissions can see and operate different data
    • 3. Clear responsibilities: in the e-commerce scenario, customer service can only view complaints, not store revenue, while operators can see complaints and store revenue

Relationship between permissions and users

  • In linux system, permissions are used to define what users can and cannot do
    • 1. Three identities are defined for files: owner, group and others
    • 2. Each identity has three corresponding permissions: read, write and execute
  • When a user accesses a file, the process is as follows:
    • 1) Judge whether the user is the owner of the file. If so, access according to the owner permission
    • 2) Judge whether the user belongs to the file group. If so, access according to the group permissions
    • 3) If the file does not belong to the owner or the group, it can be accessed according to the permissions of others

Meaning of rwx in permission

lettermeaningBinaryOctal authority identification method
r- -Read permissions1004
-w-Write permission0102
- -xExecution Authority0011
- - -No permission0000

Modify file permissions

Meaning of modifying permissions

  • Give a user or group - > how (read / write execution) - > access to files

How to modify permissions

  • Modify permission usage command: chmod
    • For the root user, you can modify anyone's file permissions
    • Ordinary users can only modify their own file permissions

UGO mode

1)Add read / write execution permission to the file owner
[root@localhost ~]# chmod a=rwx test
2)Remove all permissions from the file
[root@localhost ~]# chmod a= -rwx test
3)It belongs to master read-write execution, belongs to group read-write, and others have no permission
[root@localhost ~]# chmod u=rwx,g=rw,o=- test
4)Read / write execution by the owner group, and read permission by others
[root@localhost ~]# chmod ug=rwx,o=r test

NUM mode

1)Set file permissions 644, rw-r--r--
[root@localhost ~]# chmod 644 test
2)Set file permissions 600, rw-------
[root@localhost ~]# chmod 600 test
3)Set file permissions, 755, recursive authorization rwx-r-xr-x
[root@localhost ~]# chmod -R 755 test1

The difference between file and directory by permission setting

jurisdictionImpact on documentsImpact on Directory
Read pe r missionsHave read \ read file content permissionWith browse directory and subdirectory
Write permissionHave the permission to add and modify file contentHave the permission to add and delete files in the target
Execute permission (x)Have permission to execute filesHave access to the contents of the directory (depending on the file permissions in the directory)

Summary of file permissions

  • 1. Read permission r: have the permission to read and read file contents
    • You can only use the view class commands: cat, head, tail, less, more
  • 2. Write permission w: it has the permission to add and modify file contents
    • Using vim will prompt permission rejection, but you can force saving, which will overwrite all the contents of the file
    • You can write data to the file content by using the echo command redirection, > > you can append content
    • You cannot delete a file using rm, because deleting a file depends on whether the parent directory has w permission
  • 3. Execute permission x: has the permission to execute files
    • Execution permissions are useless
    • If ordinary users need to execute files, they need to cooperate with r permissions

Summary of directory permissions

  • 1. Read permission r: have the permission to browse directories and subdirectories
    • Use the ls command to browse directories and subdirectories, but you will also be prompted for permission denial
    • Use the ls -l command to browse directories and subdirectories. The file properties will be marked with a question mark, and only the file name can be seen
  • 2. Write permission w: it has the permission to add, modify, delete or modify the file name in the directory, which needs the cooperation of x permission
    • You can create files in the directory and delete files (independent of the permissions of the file itself)
    • You cannot enter a directory, copy a directory, delete a directory, or move a directory
  • 3. Execute permission x: has the permission to execute files
    • You can only enter the directory
    • Cannot browse, copy, move, delete

Summary of file and directory permissions

  • File permission setting:
    • File r permissions, only for users to view, no other operations
    • File rw permissions to view and edit file contents
    • File rx permission, which allows you to view and execute files, but you cannot modify files
    • File rwx permissions can be read, written, executed, and cannot be deleted
  • Directory permission setting:
    • Directory rx permission, which allows you to browse files and subdirectories in the directory. It is not allowed to create files or delete files in this directory
    • Directory rw permission. You can view the directory and write files to the directory, but you cannot enter the directory – > (too few cases)
  • Security permissions set by the default system
    • File permissions: 644
    • Directory permissions: 755

Significance of modifying the relationship of the document

How to modify the ownership of a file

  • Commands can be used; chown,chgrp
    • chown can change the owner and group of documents
    • chgrp can only change the group of the file
chown command
1.Prepare the environment and create files and directories
[root@localhost ~]# mkdir /data
2.Modify the primary as bin
[root@localhost ~]# chown bin/data
3.Modify the group to admin
[root@localhost ~]# chown .admin /data
4.Modify the primary directory to root,The group is root,And recursive authorization
[root@localhost ~]# chown -R root.root dir
========================================================================================
chgrp command
1.Prepare the environment, create files and directories
[root@localhost ~]# mkdir /data1
 Modify group admin
[root@localhost ~]# chgrp .admin /data

File special permissions

Special permission SUID

SUID production background

In linux system, every ordinary user can change his password, which is a reasonable setting; However, the user's password is stored in the / etc/shadow file, that is, ordinary users will update the contents of the / etc/shadow file when they change their password
But the / etc/shadow file is not allowed to be modified by anyone? Why can ordinary users modify their permissions?

[root@localhost ~]# ll /etc/shadow
----------. 1 root root 813 Dec  2 04:45 /etc/shadow

In fact, the password that ordinary users can change depends on the passwd command itself, which has a special permission setUID, that is, the execution permission of the master permission bit is s
[root@localhost ~]# ll /usr/bin/passwd
-rwsr-xr-x. 1 root root 33600 Apr 6 2020 /usr/bin/passwd
Explanation: when SUID is set for an execution file, the user will execute the file as the file owner

  • What happens when we use ordinary users to execute the passwd command
    • 1. Because the passwd command has suid special permission (Master: s)
    • 2. Therefore, during the execution of the passwd command, the command will be run as the owner of the command (that is, as root)
    • 3. User - > passwd - > convert the command to the primary identity root - > operate / etc/shadow information change

SUID configuration syntax

[root@localhost ~]# chmod u+s test 
[root@localhost ~]# chmod 4755 test

SUID role summary

  • 1. Let ordinary users temporarily have the master permission of the executable binary file
  • 2. If the set binary file does not have execution permission, the permission display of suid is big S
  • 3. Special permission suid is only valid for binary executable programs, and other files or directories are invalid
  • Note: suid is relatively dangerous. It is not recommended to set suid for vim or rm

Special permission SGID

  • SGID:
    • Set the binary executable file. During the execution of the command, the command will be run as the group of the command
    • Set on the directory. At this time, the new file / directory under the directory automatically inherits the parent directory's group

SGID configuration syntax

[root@localhost ~]# chmod g+s /dir
[root@localhost ~]# chmod 2755 /dir

SGID scenario description

Requirement description
1.The system has two users, namely zj1 And zj2,Both users have example Additional group
2.These two users need to share/data/code Development right of catalogue
3.Each other can modify each other's files, and the directory is not allowed to be accessed by others
[root@localhost ~]# groupadd example
[root@localhost ~]# useradd zj2 -G example
[root@localhost ~]# useradd zj1 -G example
[root@localhost ~]# mkdir /data/code
[root@localhost ~]# chgrp project /data/code/
[root@localhost ~]# chmod 770 /data/code/
[root@localhost ~]# chmod 2770 /data/code/

Special rights SBIT

What is SBIT

Once the directory is given the sticky bit, all files in the directory can be deleted except root. Even if ordinary users have w permission on the directory, they can only delete the files created by themselves, not those created by other users.

SBIT configuration example

Requirements: by default/mnt If it is not a sticky bit, how to set this directory to a sticky bit
[root@localhost data]# chmod 1755 /tmp
[root@localhost data]# chmod o+t /tmp

SBIT usage scenarios

Later, when we want to initialize the MySql service, the service will create some temporary files and store them in the / tmp directory. After initialization, the service will clean up the data in it, which others cannot clean up (if this directory is not a sticky bit, an error will be reported when initializing MySql)

  • Write shell script simulation
    • 1. Simulate MySql initialization and create files to the / tmp directory
    • 2. Log in as an ordinary user and delete the MySql initialization file
    • 3. If the normal user is deleted successfully, the initialization fails
    • 4. If the deletion of an ordinary user fails, the MySql service attempts to delete it. If the deletion succeeds, the initialization succeeds
#!/bin/bash
#********************************************************************
#Author:        ZhaoJie
#QQ:            631455878
#Date:          2021-12-03
#FileName:      my_ql_init.sh
#URL;          https://www.zhaojie.com
#Description:   The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
mysql_tmp_file=/tmp/mysql.init
User=oldxu
#1. Initialize mysql service
touch ${mysql_tmp_file}
#2. Simulate users to delete files
useradd oldxu
su - ${User} -c "rm -f ${mysql_tmp_file} &>/dev/null"
#3. Check whether the deletion is successful
if [ $? -eq 0 ];then
        echo "${mysql_tmp_file} File by ${User} User deleted successfully. The directory is not SBIT, mysql initialization failed"                                          
else
        echo "${mysql_tmp_file}File by ${User} The user failed to delete the directory SBIT,mysql Initialization succeeded"
fi
==========================================================================================
//Default viscous level test
[root@localhost data]# sh my_ql_init.sh 
/tmp/mysql.init File by oldxu The user failed to delete the directory SBIT,mysql Initialization succeeded

//Modify bit common directory test
[root@localhost data]# chmod 777 /tmp/
[root@localhost data]# sh my_ql_init.sh 
useradd: user 'oldxu' already exists
/tmp/mysql.init File by oldxu User deleted successfully. The directory is not SBIT, mysql initialization failed

Summary of SBIT role

  • 1. Let all ordinary users have write permission to the directory, and realize that each user can only delete his own files
  • 2. The sticky bit directory is represented in the x bit of others, which is represented by T. If there is no execution permission, it is displayed as t
  • 3. The owner of the sticky bit directory and the contents in the root user permission directory. Other users have no permission to delete

File special properties

What are special attributes

This kind of file attribute is a kind of advanced attribute, which is superior to rwx basic permission

Role of special attributes

  • 1. Create a file that cannot be modified, moved or deleted, including root – > suitable for / etc/passwd
  • 2. When creating a file, only data can be added to the file, and modification, movement and deletion are not allowed. – > Suitable for sudo audit log

How are special properties configured

linux system realizes special attribute configuration through chatr

Command format: chattr [+ - =] [option] File or directory
a: Additional contents can be added to the file
i: Lock the file. No other operations are allowed

1. The configuration / etc/passwd file cannot be modified, appended or deleted

1.give i jurisdiction
[root@localhost data]# chattr +i /etc/passwd
2.Verify permissions
[root@localhost data]# rm -f /etc/passwd
rm: cannot remove '/etc/passwd': Operation not permitted

2. Configure the / var/log/secure file, which can only be appended to the log, and cannot be manually modified or deleted

1.give a jurisdiction
[root@localhost data]# chattr +a /var/log/secure
[root@localhost data]# lsattr /var/log/secure
-----a----------	/var/log/secure
2.Test additional data
[root@localhost ~]# echo "test" >> /var/log/secure
[root@localhost ~]# echo "test" >> /var/log/secure
3.Cannot delete or modify
[root@localhost ~]# rm -f /var/log/secure
rm:	cannot remove '/var/log/secure': Operation not	permitted

3. If you want to cancel the special attribute, you need to use the root identity

[root@localhost ~]# chattr -i /etc/passwd
[root@localhost ~]# chattr -a /var/log/secure

Special attribute scene

  • Simulate the virus string to change Zhang Dian, then lock the file with chatr to make the virus program unable to string change, and then track and kill the virus program
    • 1. Install and start the http service
    • 2. Simulate virus script to tamper with web page content
    • 3. Lock the tampered file, then find the virus and kill it
1.install http Service, and then start external
[root@localhost ~]# setenforce 0
[root@localhost ~]# systemctl stop firewalld
[root@localhost ~]# systemctl disable firewalld
[root@localhost ~]# yum	install	httpd -y
[root@localhost ~]# systemctl	start	httpd

2. Write a virus script to try to tamper with the content of the web page

#!/bin/bash
#********************************************************************
#Author:        ZhaoJie
#QQ:            631455878
#Date:          2021-12-03
#FileName:      virus.sh
#URL;          https://www.zhaojie.com
#Description:   The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
web_site=/var/www/html/index.html
while true
do
        echo "I'm a virus" > ${web_site}
        sleep 20
done                      

3. Lock the tampered file and kill the virus

[root@localhost ~]# chatttr +i /var/www/html/index.html
[root@localhost ~]# kill $(ps -ef | grep virus | grep -v grep|awk '{print $2}')

Tags: Linux Operation & Maintenance CentOS server

Posted on Fri, 03 Dec 2021 09:33:58 -0500 by ih8telepathy.cm