Linux system security

1, Basic measures for account security

1.1. System account cleaning

  • Set the Shell of the non logged in user to / sbin/nologin
    usermod-s/sbin/nologin username
  • Lock accounts that have not been used for a long time
[root@localhost ~]# usermod -L user name lock user account
[root@localhost ~]# passwd -l user name lock user account
[root@localhost ~]# usermod -U user name unlock user account
[root@localhost ~]# passwd -u user name unlock user account
[root@localhost ~]# passwd -S username to view user status
  • Delete useless account
    [ root@localhost ~]#Userdel - R username
  • Lock account files passwd and shadow
[root@localhost ~]# Chatr + I / etc / passwd / etc / shadow lock file
[root@localhost ~]# chattr -i /etc/passwd /etc/shadow unlock file
[root@localhost ~]# lsattr /etc/passwd /etc/shadow view file status

[root@localhost ~]# lsattr /etc/passwd /etc/shadow
---------------- /etc/passwd
---------------- /etc/shadow
[root@localhost ~]# useradd lisi
[root@localhost ~]# passwd lisi
 Change user lisi Your password.
New password:
Invalid password: password is less than 8 characters
 Re enter the new password:
passwd: All authentication tokens have been successfully updated.
[root@localhost ~]# id lisi
uid=1001(lisi) gid=1001(lisi) group=1001(lisi)
[root@localhost ~]# chattr +i /etc/passwd /etc/shadow
[root@localhost ~]# lsattr /etc/passwd /etc/shadow
----i----------- /etc/passwd
----i----------- /etc/shadow
[root@localhost ~]# useradd qiaozhi
useradd: Cannot open /etc/passwd
[root@localhost ~]# passwd lisi
 Change user lisi Your password.
New password:
Invalid password: password is less than 8 characters
 Re enter the new password:
123passwd: Authentication token operation error
[root@localhost ~]# chattr -i /etc/passwd /etc/shadow
[root@localhost ~]# lsattr /etc/passwd /etc/shadow
---------------- /etc/passwd
---------------- /etc/shadow
[root@localhost ~]# useradd qiaozhi
[root@localhost ~]# passwd qiaozhi
 Change user qiaozhi Your password.
New password:
Invalid password: password is less than 8 characters
 Re enter the new password:
passwd: All authentication tokens have been successfully updated.

1.2 password security control

  • Set password validity
    [ root@localhost ~]#Chage - M 30 user name is applicable to existing users
    18885:0:99999:7::: becomes 18885:0:30:7:::
​`[root@localhost ~]# cat /etc/shadow|grep lisi
lisi:$6$lI.TDhRs$lqTvhvybf2njN7/7eKS3ff56hEQDzbp0mxKk0yM/OSX6qj97j4lS4P2t44mT2Gf7IoVEA2GXkSv88/btLtkaf1:18885:0:99999:7:::
[root@localhost ~]# chage -M 30 lisi
[root@localhost ~]# cat /etc/shadow|grep lisi
lisi:$6$lI.TDhRs$lqTvhvybf2njN7/7eKS3ff56hEQDzbp0mxKk0yM/OSX6qj97j4lS4P2t44mT2Gf7IoVEA2GXkSv88/btLtkaf1:18885:0:30:7:::`

[ root@localhost ~]#VIM / etc / login.defs is applicable to existing users
PASS_MAX_DAYS 30
cat /etc/shadow | grep user name to check whether the password effective date is configured successfully

The validity period here becomes 30 days

  • Force password change at next login
    [ root@localhost ~]#Chage - d 0 user name forces the user to change the password when logging in next time

1.3 command history restrictions

  • Reduce the number of recording commands
Reduce the number of recording commands:
[root@localhost ~]# vim /etc/profile edit global variable configuration file    
export HISTSIZE=10                 Default 1000 entries=10
:wq
[root@localhost ~]# source /etc/profile is equivalent to overloading the commands in / etc/profile
[root@promote ~]#history

history -c temporarily cleared

  • Automatic case command history on logoff
[root@localhost ~]# vim ~/.bashrc
echo " " > ~/.bash_history       
:wq
reboot
history

[root@localhost ~]# vim ~/.bashrc 
[root@localhost ~]# source .bashrc
[root@localhost ~]# reboot 
Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(haoyang1) at 20:26:45.

Type `help' to learn how to use Xshell prompt.
[C:\~]$ 
[C:\~]$ 
[C:\~]$ 

Connecting to 192.168.32.99:22...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.

Last login: Wed Sep 15 20:27:12 2021
[root@localhost ~]# history 
    1  history 

1.4 automatic logoff of terminal

Automatically log off after 600 seconds of inactivity:
[root@localhost ~]#vim .bash_profile edit global variable profile
    export TMOUT=60  output timeout=60
[root@localhost ~]# source .bash_profile refresh
[root@localhost ~]# echo $TMOUT view logout time

[root@localhost ~]# vim .bash_profile 
[root@localhost ~]# source .bash_profile
[root@localhost ~]# echo $TMOUT
60

2, Use the su command to switch users

2.1 purpose and usage of su command

Purpose: Substitute User to switch users
Format: su - target user

[root@localhost ~]# su - lisi 
Last login: September 15-20:52:09 CST 2021pts/0 upper
[lisi@localhost ~]$ pwd
/home/lisi
[lisi@localhost ~]$ echo $PATH 
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/lisi/.local/bin:/home/lisi/bin

2.2. Password verification

  • root - any user without verifying the password
  • Normal user - other users, verifying the password of the target user
  • The su - root with - option indicates that the login Shell environment of the target user will be used

2.3. Restrict users using su command

  • Add users who are allowed to use the su command to the wheel group
  • Enable pam_wheel authentication module
gpasswd -a user name wheel     Add user name to wheel Group
vim /etc/pam.d/su 

auth    sufficient   pam_rootok.so
............
#auth   required     pam_wheel.so use_uid
#%PAM-1.0
auth            sufficient      pam_rootok.so
# Uncomment the following line to implicitly trust users in the "wheel" group.
#auth           sufficient      pam_wheel.so trust use_uid
# Uncomment the following line to require a user to be in the "wheel" group.
auth            required        pam_wheel.so use_uid
auth            substack        system-auth
auth            include         postlogin
account         sufficient      pam_succeed_if.so uid = 0 use_uid quiet
account         include         system-auth
password        include         system-auth
session         include         system-auth
session         include         postlogin
session         optional        pam_xauth.so

3, PAM security authentication in Linux

1. Potential safety hazards of Su command
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 use control of the su command, only a few users are allowed to use the su command for switching with the help of the PAM authentication module

2.PAM(Pluggable Authentication Modules) pluggable authentication module
It is an efficient, flexible and convenient user level authentication method
It is also a widely used authentication method for Linux servers

3.PAM certification principle
Generally follow the order
Service - > PAM * so
First, determine which service, then load the corresponding PAM configuration file (located under /etc/pam.d), and finally call the authentication file (located under /lib64/security) for security authentication.
When a user accesses the server, a service program of the server sends the user's request to the PAM module for authentication
Different applications have different PAM modules

4. Composition of PAM certification
To check whether a program supports PAM authentication, you can use the ls command
Example: check su whether PAM module authentication is supported
Is /etc/pam.d | grep su
View the PAM configuration file of Su: cat/etc/pam.d/su
Each line is an independent authentication process
Each row can be divided into three fields
Certification Type
control type
PAM module and its parameters
cat /etc/pam.d/system-auth
The first column represents the PAM authentication module type
auth; Identify the user's identity, such as prompt for password, and judge whether it is root
Account: check the attributes of the account, such as whether it is allowed to log in to the system, whether the account has expired, whether it has reached the maximum number of users, etc.
Password: use user information to update data, such as changing user password.
Session: defines the session operation management to be performed before login and after logout, such as login connection information, opening and closing user data, and mounting file system. How many terminals can be connected
The second column represents the PAM control flag
required: indicates that a success value needs to be returned. If the return fails, the failure result will not be returned immediately, but the next verification of the same type will continue. After the execution of all modules of this type is completed, the failure will be returned.
Required: similar to required, but if this module returns a failure, it immediately returns a failure and indicates that this type of failure.
sufficient: if this module returns success, it will directly return success to the program, indicating such success. If it fails, it will not affect this type of return value
optional: it does not return success or failure, nor does it affect this type of return value. Generally, it is not used for verification, but for displaying information (usually used for session type),
include: indicates that other PAM configuration files are called during validation.
For example, many applications realize authentication by calling / etc / pam.d/ayatem-auth (mainly responsible for the authentication of users logging in to the system) without writing configuration items one by one.
The third column represents the PAM module, which is in the / lib64/security / directory by default. If it is not in this default path, the absolute path should be filled in. The same module can appear in different module types, and its operations are different in different types. This is because each module has different execution functions for different module types.
The fourth column represents the parameters of PAM module, which needs to be added according to the module used.
Parameters passed to the module. There can be multiple parameters separated by spaces

5.PAM safety certification process
The control type, also known as Control Flags, is used to verify the returned results of PAM types
1.required continue when the verification fails, but return Fail
2. If the required verification fails, the whole verification process will be ended immediately and Fail will be returned
3. If the sufficient verification is successful, it will be returned immediately and will not continue. Otherwise, the result will be ignored and continue
4.optional is not used for verification, only information is displayed

4, Using sudo mechanism to raise rights

4.1 purpose and usage of sudo command

Purpose: execute authorization commands as other users (such as root)
Usage: sudo authorization command

4.2. Configuration authorization

visudo or vim /etc/sudoers
Format: user hostname list = command program list
The wildcard "*" and "!" can be used for inversion.

4.3. Alias creation

[root@localhost ~]# vim /etc/sudoers
Host_Alias MYHOST = localhost
User_Alias MYUSER = zhangsan,lisi,liwu
Cmnd_Alias MYCMD = /usr/sbin/useradd,/usr/bin/passwd

MYUSER         MYHOST = NOPASSWD : MYCMD

[lisi@localhost root]$ sudo useradd liba
[lisi@localhost root]$ id liba
uid=1005(liba) gid=1005(liba) group=1005(liba)
[lisi@localhost root]$ sudo passwd liba
 Change user liba Your password.
New password:
Invalid password: password is less than 8 characters
 Re enter the new password:
passwd: All authentication tokens have been successfully updated.

4.4. View sudo operation records

[root@localhost ~]# vim /etc/sudoers
Defaults logfile = /var/log/sudo   //Add the command to the last line: wq save and exit

5, On off safety control

5.1. Adjust BIOS boot setting principle

  • Set the first boot device as the hard disk of the current system
  • It is forbidden to boot the system from other devices (CD, U SB flash disk, network)
  • Set the security level to setup and set the administrator password

5.2 GRUB limitation and Implementation

Method 1: directly set grub2 - setpasswd set grub password

Method 2

  • Usually, when the system starts up and enters the GRUB menu, press the e key to view and modify the GRUB boot parameters, which is a great threat to the server.
  • You can set a password for GRUB menu. Only the correct password is provided can you modify the boot parameters.
[root@localhost ~]# grub2-mkpasswd-pbkdf2 
Enter password:
Reenter password: 
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.2D96787097EB717901FC663B72435E8E3A20D4C293A4977486A09E9039535711B402A5135FA758CADF5A6FCAA9E0354FFF336C44379EE7C36A2ED144178058E9.EEFD95507926800D13491280B75E30A8049C08A7EA007032F3E083B38C9A5B29530D1A2A716AF174FEA05F898D69BA2C6E26F92615511BEFECFB3EAA0D0AD05C

[ root@localhost grub.d]# vim 00_ The header copies the content viewed by grub2-mkpasswd-pbkdf2

[ root@localhost grub.d]# grub2-mkconfig -o /boot/grub2/grub.cfg generate a new grub.cfg file

[root@localhost grub.d]# grub2-mkconfig -o /boot/grub2/grub.cfg 
Generating grub configuration file ...
/etc/grub.d/00_header: line 361: warning: here-document at line 359 delimited by end-of-file (wanted `EOF')
Found linux image: /boot/vmlinuz-3.10.0-693.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-693.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-4bf736ee567f4452a7da314101d15437
Found initrd image: /boot/initramfs-0-rescue-4bf736ee567f4452a7da314101d15437.img
error: out of memory.
error: syntax error.
error: Incorrect command.
error: syntax error.
Syntax error at line 143
Syntax errors are detected in generated GRUB config file.
Ensure that there are no errors in /etc/default/grub
and /etc/grub.d/* files or please file a bug report with
/boot/grub2/grub.cfg.new file attached.

6, System weak password detection and network port scanning

6.1 system weak password


decompression
[root@localhost opt]#tar zxvf john-1.8.0.tar.gz 
​
Install software compilation tools
[root@localhost src]#yum install gcc gcc-c++ make -y
​
Compile and install
[root@localhost src]#make clean linux-x86-64
​
Prepare the password file to be cracked
[root@localhost src]#cd.. switch to parent directory
[root@localhost john-1.8.0]#cp /etc/shadow /opt/shadow.txt prepare the password file
 
Perform brute force cracking
[root@localhost john-1.8.0]#cd /opt/john-1.8.0/run/
[root@localhost run]#./john /opt/shadow.txt 
​

[root@localhost src]# yum install gcc gcc-c++ make -y
[root@localhost src]# make clean linux-x86-64

[root@localhost src]# cd ..
[root@localhost john-1.8.0]# ls
doc  README  run  src
[root@localhost john-1.8.0]# cp /etc/shadow /opt/shadow.txt
[root@localhost john-1.8.0]# ls /opt/
john-1.8.0  john-1.8.0.tar.gz  rh  shadow.txt
[root@localhost john-1.8.0]# cd /opt/john-1.8.0/run/
[root@localhost run]# ls
ascii.chr   john       lm_ascii.chr  makechr       relbench  unique
digits.chr  john.conf  mailer        password.lst  unafs     unshadow
[root@localhost run]# ./john /opt/shadow.txt 
Loaded 3 password hashes with 3 different salts (crypt, generic crypt(3) [?/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
123123           (liba)
123123           (root)
123123           (kehuailunnade)
3g 0:00:00:46 100% 2/3 0.06478g/s 200.4p/s 221.1c/s 221.1C/s leslie..boston
Use the "--show" option to display all of the cracked passwords reliably
Session completed

6.2 network port scanning

1, NMAP overview:
1. It is a powerful port scanning security evaluation tool, supporting ping scanning, multi port detection and other technologies
2. Official website: http://nmap.org/
3. Installation package nmap-6.40-7.el7.x86 in CentOS 7.7 CD_ 64.rpm
2, Install the NMAP package
yum install -y nmap / / and then install the nmap package
3, nmap command common options and corresponding scan types

Common optionsRole of options
-pSpecify the port to scan.
-nDisable reverse DNS resolution (to speed up scanning)
-sSTCP SYN scanning (half open scanning) only sends SYN data packets to the target. If a synck response packet is received, it is considered that the target port is listening and the connection is disconnected immediately; Otherwise, it is considered that the target port is not open.
-sTTCP connection scanning, a complete TCP scanning method (default scanning type), is used to establish a TCP connection. If it succeeds, it is considered that the target port is listening to the service, otherwise it is considered that the target port is not open.
-sFDuring TCP FIN scanning, open ports will ignore such packets, and closed ports will respond to RST packets. Many firewalls simply filter SYN packets and ignore other forms of TCP attack packets. This type of scanning can indirectly detect the robustness of the firewall.
-sUUDP scanning detects which UDP services are provided by the target host. The speed of UDP scanning will be slow.
-sPICMP scanning is similar to ping detection. It can quickly judge whether the target host is alive without other scanning.
-P0Skip ping detection. This method considers that all target hosts are alive. When the other party does not respond to ICMP requests, this method can avoid giving up scanning due to inability to ping.

[ root@localhost ~]#Nmap - St 127.0.0.1 view the local open TCP ports
[ root@localhost ~]#Nmap - Su 127.0.0.1 view the open UDP ports of this machine
[ root@localhost ~]#Nmap - N - SP 192.168.32.0/24 detects the number of surviving hosts in the 192.168.32.0/24 network segment

[root@localhost ~]# nmap -sT 127.0.0.1

Starting Nmap 6.40 ( http://nmap.org ) at 2021-09-22 21:14 CST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00063s latency).
Not shown: 996 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
25/tcp  open  smtp
111/tcp open  rpcbind
631/tcp open  ipp

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds

[root@localhost ~]# nmap -sU 127.0.0.1

Starting Nmap 6.40 ( http://nmap.org ) at 2021-09-22 21:16 CST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00012s latency).
Not shown: 998 closed ports
PORT     STATE         SERVICE
111/udp  open          rpcbind
5353/udp open|filtered zeroconf

Nmap done: 1 IP address (1 host up) scanned in 49.21 seconds


[root@localhost ~]# nmap -n -sP 192.168.32.0/24

Starting Nmap 6.40 ( http://nmap.org ) at 2021-09-22 21:18 CST
Nmap scan report for 192.168.32.1
Host is up (0.00071s latency).
MAC Address: 00:50:56:C0:00:08 (VMware)
Nmap scan report for 192.168.32.2
Host is up (0.000087s latency).
MAC Address: 00:50:56:E7:1B:08 (VMware)
Nmap scan report for 192.168.32.254
Host is up (0.00013s latency).
MAC Address: 00:50:56:EC:A5:43 (VMware)
Nmap scan report for 192.168.32.96
Host is up.
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.00 seconds

Tags: Linux Operation & Maintenance ssh

Posted on Wed, 22 Sep 2021 12:05:37 -0400 by Ell20