Linux system security and application (with detailed operation screenshots attached)

1. Account security control

A user account is the ID or identification of a computer user. Everyone who wants to access system resources must rely on his user account to access the computer. In the Linux system, a variety of mechanisms are provided to ensure the proper and safe use of user accounts

1.1 System account cleanup

  • Set the shell of non-login users to /sbin/nologin or /bin/falsh
usermod -s /sbin/nologin 用户名
  • Lock accounts that have not been used for a long time
usermod -L 用户名             锁定用户账户  
passwd  -l  用户名            锁定用户密码
passwd  -S  用户名            查看用户状态
  • Delete useless accounts
userdel [-r] 用户名           删除用户-r宿主目录一起删除
  • Lock account files passwd, shadow
chattr +i /etc/passwd /etc/shadow      锁定文件
lsattr /etc/passwd /etc/shadow         查看文件状态
chattr -i /etc/passwd /etc/shadow      解锁文件

Insert picture description here
Insert picture description here

  • Usage of chattr command
    1. "+": add parameters based on the original parameter settings;

2. "-": Remove the parameter based on the original parameter setting;

3. "="; update to the specified parameter setting.

“A”:文件或目录的atime(access time)不可被修改(modified),可以有效预防例如手提电脑,磁盘I/O错误的发生;

“S”:硬盘I/O同步选项,功能类似sync;

“a”:即append,设定参数后,只能向文件中添加数据,而不能删除,多用来服务器日志文件安全,只有root才能设定这个属性;

“c”,即compresse,设定文件是否经压缩后再存储,读取时需要经过自动解压操作;

“d”:即no dump 设定文件不能成为dump程序的备份目标;

“i”:设定文件不能被删除、改名、设定链接关系,同时不能写入或新增内容。i参数对文件系统的安全设置有很大帮助;

“j”:即journal,设定此参数使得当通过mount参数:data=ordered或者data=writeback挂载的文件系统,文件在写入时会被记录(在journal中)。如果filesystem被设定参数为data=journal,则该参数自动失效;

“s”:保密性地删除文件或者目录,即硬盘空间被全部收回;

“u”:与s相反,当设定为u时,数据内容其实还存在磁盘中,可以用于undeletion。

Commonly used in each parameter option are "a" and "i". The "a" option forces only add and cannot be deleted. It is mostly used for the security settings of the log system, while "i" is a more stringent security setting, which can only be applied by superuser (root) or processes with CAP_Linux_IMMUYABLE processing capability (identification) The option.

1.2 Password security control

In an insecure network environment, in order to reduce the risk of password guessing or brute force cracking, users win the habit of changing passwords regularly to avoid using the same password for a long time. The administrator can limit the maximum number of valid days for a user's password on the server side. For users whose passwords have expired, they will be asked to reset their passwords when logging in, otherwise they will be refused to log in.

1.2.1 Set Password Validity Period

方法一:修改密码配置文件适用于新建用户
vim /etc/login.defs     
……
PASS_MAX_DAYS 30
方法二:适用于已有用户
[root@localhost ~]# chage -M 30 用户
[root@localhost ~]# cat /etc/shadow | grep 用户

method one:

[root@localhost c7-1]#vi /etc/login.defs

#   QMAIL_DIR is for Qmail
#
#QMAIL_DIR      Maildir
MAIL_DIR        /var/spool/mail
#MAIL_FILE      .mail

# Password aging controls:
#
#       PASS_MAX_DAYS   Maximum number of days a password may be used.
#       PASS_MIN_DAYS   Minimum number of days allowed between password changes.
#       PASS_MIN_LEN    Minimum acceptable password length.
#       PASS_WARN_AGE   Number of days warning given before a password expires.
#
PASS_MAX_DAYS   99999   // 系统默认99999 ,永久
PASS_MIN_DAYS   0
PASS_MIN_LEN    5
PASS_WARN_AGE   7

Insert picture description here
Insert picture description here
Method two demonstration:
Insert picture description here

1.2.2 Require users to change their password the next time they log in

chage -d 0 lisi                    强制在下次登陆时更改密码               
cat /etc/shadow | grep 用户        shadow文件中的第三个字段被修改为0

Insert picture description here
Insert picture description here
Insert picture description here

1.2.3 Command history restrictions

  • Reduce the number of recorded commands
[root@localhost ~]# vi /etc/profile           #编辑profile文件    
 export HISTSIZE=30                            #保存30条历史记录
[root@localhost ~]# source /etc/profile        #执行一次配置文件,让配置文件生效

Insert picture description here

Insert picture description here

Insert picture description here

  • Automatically clear the command history when logging in
[root@localhost ~]#vi ~/.bashrc
 echo " " > ~/.bash_history  

Insert picture description here

After restarting, you can see that the previous commands are all emptied
Insert picture description here
Insert picture description here

1.2.4 Terminal automatic logout

  • Automatically log out after 600 seconds of inactivity
vim /etc/profile                #编辑profile文件
export TMOUT=600                #设定时间600秒
[root@localhost ~]# source /etc/profile    #调用配置文件

Insert picture description here

2. User switching and privilege escalation

Most Linux servers do not recommend that users log in directly as the root user. On the one hand, it can greatly reduce the damage caused by misoperation, and on the other hand, it also reduces the risk of the privileged password being leaked in an insecure network. For these reasons, it is necessary to provide an identity switching or privilege escalation mechanism for ordinary users to perform management tasks when necessary.
The Linux system provides us with su and sudo two commands. The su command is mainly used to switch users, and the sudo command is used to increase the execution authority.

2.1 Use su command to switch users

1) Purpose and usage

作用:切换用户
格式:su [-] 目标用户    #带“-”表示使用目标用户的登录shell环境,不加环境变量不变。
可登录的用户一般分两种种,超级用户root、普通用户。
当root切换到任意的用户时,不需要密码。
但当普通用户切换其他用户的时候,需要输入目标用户的密码进行验证。

Insert picture description here

2) Restrict users who use the su command
Step 1: Add users who are allowed to use the su command to the wheel group

gpasswd -a 用户 wheel    #添加用户到wheel组中
grep wheel /etc/group    #确定wheel组成员

Insert picture description here
Step 2: Modify /etc/pam.d/su authentication configuration to enable pam_wheel authentication

vim /etc/pam.d/su     #编辑/etc/pam.d/su文件
auth sufficient pam_rootok.so  
#pam_rootok.so模块的主要作用是使uid为0的用户root能够直接通过认证而不用输入密码
...      #省略部分
auth required pam_wheel.so use_uid 
 #pam_wheel.so作用是让wheel组内的用户使用su命令,其他人(包括root)无法使用su命令

每种状态的解释:
两行都注释:所有用户都能使用su命令,切换时root和普通用户都需要密码验证
开启第二行,注释第六行:(默认状态)允许所有用户间使用su命令进行切换的,切换时,root不需要密码,其他用户需要密码。
注释第二行,开启第六行:只有wheel组内的用户才能使用su命令,root用户也无法切换。
两行都开启:只有root用户和wheel组内的用户才可以使用su命令。

Insert picture description here
Example: Modify the document to delete the comment "#" in front of the command and save it with "wq"
3) View the record of su operation
/var/log/secure is the security log of su, and the operation of switching users using the su command will be recorded. So you can check this file to see the record.

例:cat /var/log/secure  

View /var/log/secure file
Insert picture description here

2.2 PAM security certification

  • Linux-PAM is a linux pluggable authentication module, a set of customizable and dynamically loadable shared libraries, so that the local system administrator can choose the authentication method of the program at will.
    By default, any user is allowed to use the su command and has the opportunity to repeatedly try the login password of other users (such as root), which brings security risks
  • In order to strengthen the control of the use of the su command, the PAM authentication module can be used to allow only a very few users to use the su command to switch

1) PAM and its role

PAM is a linux pluggable authentication module, a set of customizable and dynamically loadable shared libraries. The system administrator can choose the authentication method of the program at will through the PAM configuration file.
The PAM configuration file is located in the /etc/pam.d directory, and the local authentication module of CentOS7 is located in /lib64/security. If you want to know what they are, you can use ls to view.

2) PAM authentication principle

  • Generally follow the order
    Service (service) —> PAM (configuration file) —> pam_*.so
  • PAM first determines which service, then loads the corresponding PAM configuration file, and finally calls the PAM authentication module for security authentication
  • When a user accesses the server, a certain service program of the server sends the user's request to the PAM module for authentication
  • The PAM modules corresponding to the same application are also different
如果想查看某个程序是否支持 PAM 认证,可以用 ls 命令进行查看/etc/pam.d/。
示例:查看su是否支持PAM模块认证
ls /etc/pam.d | grep su

Insert picture description here

3) The composition of PAM certification

  • Each line is an independent authentication and process, which are called by the PAM module in order from top to bottom
  • Each line has three partitions: authentication type, control type, PAM module, PAM module parameters. To
    view a login configuration file, first cd /etc/pam.d/, ls to see which ones are available, and cat selects one.
    Insert picture description here
    Explanation of each partition
    First column: PAM has the following four module types, representing four different tasks
Authentication module type effect
auth Identify the user's identity, if prompted to enter a password, determine whether it is root.
account Check the various attributes of the account, such as whether it is allowed to log in to the system, whether the account has expired, whether the maximum number of users has been reached, etc.
password Use user information to update data, such as changing user passwords.
session Define the session operation management to be performed before login and after logout, such as login connection information, opening and closing of user data, and mounting the file system.

The second column: PAM uses the control type to process and judge the return value of each module

Control type effect
required A success value needs to be returned. If it fails, the failure result will not be returned immediately, but the next verification of the same type will continue. After all modules of this type are executed, the failure will be returned. The success of the line and the modules involved is a necessary condition for the user to pass the authentication
requisite Similar to required, but if this module returns a failure, it will return immediately and indicate that this type has failed.
sufficient If this module returns success, regardless of the subsequent verification, it returns success directly to the program, indicating that the verification passed. If the return fails, it can be regarded as optional. (Use with caution)
optional It does not return whether it is successful or not. It is generally not used for verification, but only displays information (usually used for session types). Regardless of success or failure, continue to verify the next module, and the services of this module can also be enjoyed.
include Indicates that other PAM configuration files are called during the verification process. For example, many applications implement authentication by completely calling /etc/pam.d/system-auth (mainly responsible for the authentication of the user's login system) without the need to rewrite configuration items one by one.

The third column represents the PAM module:

  • The default is in the /lib64/security/ directory, if it is not in the default path, fill in the absolute path

  • The same module can appear in different module types, and it performs different operations in different types. This is because each module has different execution functions for different module types. The
    fourth column represents the PAM module. The parameters:

  • Add according to the module used

  • The parameters passed to the module, there can be multiple parameters, separated by spaces

4) Supplementary description of control mark

  • required: Indicates that the success of the line and the module involved is a [necessary condition] for the user to pass the authentication. In other words, only when all required modules corresponding to the application program have all succeeded, the program can pass the authentication. At the same time, if any module with the required mark has an error, PAM does not immediately return the error message to the application program, but returns the error message to the program that called it after all modules of this type have been called.
    To put it bluntly anyway, all modules of this type must be executed once. If any one of the modules fails to verify, the verification will continue, and the error message will be returned after the execution is complete. The purpose of this is to prevent users from knowing which module they are rejected, and to protect system services in a hidden way. Just like when setting up firewall rules, the deny rules are set to drop, so that users cannot accurately determine whether they are denied or the target network is unreachable when accessing the network is unsuccessful.
  • requisite: similar to required, only after the module with this mark returns successfully, the user can pass the authentication. The difference is that once it fails, it no longer executes the other modules behind in the heap, and the authentication process ends here, and the error message is returned immediately. Compared with the above required, it seems to be more open and fair.
  • Sufficient: Indicates that the successful verification of the line and the module involved is a [sufficient condition] for the user to pass the authentication. That is to say, as long as the module marked as sufficient is verified successfully, PAM will immediately return a successful result to the application without having to try any other modules. It is the same even if the requisite or required control flags are used in the subsequent cascading modules. When the module marked as sufficient fails, the sufficient module will be treated as an optional. Therefore, the configuration item with the sufficient flag bit is unfair when the verification is performed incorrectly, which causes the entire verification to fail, but when the verification is successful, the door is opened. Therefore, the use of this control bit must be cautious.
  • optional: It means that the user can still pass the authentication even if the verification of the module involved in the row fails. In the PAM system, the module with this mark will continue to process the next module after it fails. That is to say, even if the verification of the module specified by the bank fails, the user is allowed to enjoy the services provided by the application. Using this flag, the PAM framework will ignore the verification error generated by this module and continue to execute the next cascaded module in sequence.

5) PAM security certification process

Insert picture description here
1, required to verify continued failure, but returned Fail
2, requisite verification fails an immediate end to the entire verification process, return to Fail
3, Sufficient validation is successful then immediately returns, no longer continue, otherwise ignore the results and continue to
4, optional not be used to verify , Only display information (usually used for session type)

3. Switch machine safety

3.1 Adjust BIOS boot settings

(1) Set the first boot device to the hard disk where the current system is located.
(2) It is forbidden to boot the system from other devices (CD-ROM, U-disk, network), and set the corresponding item to "disabled".
(3) Set the security level to setup and set the administrator password.

3.2 GRUB restrictions

grub2-mkpasswd-pbkdf2       #使用grub2-mkpasswd-pbkdf2生成密钥

cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak
cp /etc/grub.d/00_header /etc/grub.d/00_header.bak

vim /etc/grub.d/00_header       #修改/etc/grub.d/00_header文件,添加密码记录
cat << EOF
set superusers="root"					#设置用户名为root
password_pbkdf2 root grub.pbkdf2……		#设置密码,省略部分内容为经过加密生成的密码字符串
EOF

grub2-mkconfig -o /boot/grub2/grub.cfg	#生成新的 grub.cfg 文件
1
2
3
4
5
6
7
8
9
10
11
12
在linux系统重启时,看最下面有一行,按“e”可以进入grub菜单。

Insert picture description here
After entering the grub menu, everyone can modify the grub boot parameters. This is a great hidden danger, so we need a grup to add a restriction. A password can be set for the GRUB menu, and only the correct password is allowed to modify the boot parameters.
Insert picture description here
(1) Use grub2-mkpasswd-pbkdf2 to generate a key

grub2-mkpasswd-pbkdf2

You need to enter the password twice, and generate the key based on the entered password.
Insert picture description here
2) Modify the /etc/grub.d/00_header file and add a password record.
Back up the file before modifying the file to prevent problems and restore it. Here the grup.cfg of the third step is backed up together.
Insert picture description here
Insert picture description here
3) Generate a new grub.cfg configuration file
Insert picture description here
4) Restart the system init 6, press "e" on the corresponding interface, and the following interface will pop up. Enter the user name and password as prompted to enter the grub menu.
Insert picture description here

4. Terminal login security control

1. Restrict root to log in only on secure terminals

  • Secure terminal configuration: /etc/securetty
[root@localhost ~]# vim /etc/securetty
#tty5        #禁止root用户从终端tty5,tty6登录
#tty6

2. Forbid ordinary users to log in

Create the /etc/nologin file,
delete the nologin file or restart it, it will return to normal

touch /etc/nologin			#禁止普通用户登录
rm -rf /etc/nologin			#取消登录限制

Guess you like

Origin blog.csdn.net/zhangyuebk/article/details/113781091
Recommended