Necessary Measures to Ensure Security of Linux System

As an open source operating system, Linux servers are widely used because of their significant advantages of security, efficiency and stability. Then comes the security problem of Linux system.

This blog focuses on the security of Linux system:
1. Account security control;
2. System boot and login control;
3. Weak password detection and port scanning.

I. Account Security Control

User account is the identity certificate or identification of computer users. Every person who wants to access system resources must rely on his user account to enter the computer. In Linux system, there are many mechanisms to ensure the proper and safe use of user accounts.

1. Basic (necessary) safety measures

(1) Cleaning up System Accounts

In Linux system, in addition to the various accounts created manually by users, there are also a large number of other system accounts generated with the installation process of the system or program. In addition to superuser root, a large number of other accounts are only used to maintain the system running service process. Generally speaking, the system is never allowed to log in, so they are also called non-logged user accounts.

A common login shell for a non-logged-in user's account is usually / sbin/nologin, which means that terminal login is prohibited and that it should be ensured that it is not considered a change, such as:

[root@localhost ~]# grep "/sbin/nologin" /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
                 ..................                     //Omit part of content

Among all kinds of non-logged-in user accounts, a considerable number are seldom used, such as games. These user accounts are referred to as redundant accounts. In addition, there are some user accounts installed with the application. If the application can not be automatically deleted after uninstalling, the administrator will need to delete them manually.

For long-term unused user accounts on Linux servers, if you can't determine whether they should be deleted, you can temporarily lock them down. For example:

[root@localhost ~]# Usermod-L q1//Lock Account
[root@localhost ~]# Passwd-S q1//View account status
q1 LK 2019-08-27 0 99999 7 -1 (The password has been locked.)
[root@localhost ~]# Usermod-U q1//unlock account
[root@localhost ~]# passwd -S q1
q1 PS 2019-08-27 0 99999 7 -1 (Password is set. Use SHA512 Algorithms.)

If the user account in the server is fixed and no modification is made, the method of locking the account configuration file can be adopted to further guarantee the security of the account. For example:

[root@localhost ~]# Chattr +i/etc/passwd/etc/shadow//lock file
[root@localhost ~]# Lsattr/etc/passwd/etc/shadow// View Locked State
----i----------- /etc/passwd
----i----------- /etc/shadow
[root@localhost ~]# Chattr-i/etc/passwd/etc/shadow//unlock file
[root@localhost ~]# Lsattr/etc/passwd/etc/shadow// View the status as unlocked
---------------- /etc/passwd
---------------- /etc/shadow

If the account document is locked, its content will not be allowed to be modified. Therefore, it is impossible to add or delete accounts, and to change user's password, login shell, host directory and other attribute information.

[root@localhost ~]# chattr +i /etc/passwd /etc/shadow
[root@localhost ~]# lsattr /etc/passwd /etc/shadow
----i----------- /etc/passwd
----i----------- /etc/shadow
[root@localhost ~]# useradd a1
useradd: Unable to open /etc/passwd

(2) Password Security Control

In an unsafe network environment, in order to reduce the risk of password being guessed or violently cracked, users should develop the habit of modifying passwords regularly to avoid long-term use of the same password. Administrators can limit the maximum number of valid days of user passwords on the server side. For users whose passwords have expired, they are required to reset their passwords when they log in, otherwise they will refuse to log in.

The following actions can set the password's validity to 30 days:

[root@localhost ~]# vim /etc/login.defs // / for new users after modifying files
                    ..................                               //Omit part of content
PASS_MAX_DAYS   30                                   //Default exists, modification is enough.
[root@localhost ~]# Chage-M 30 q1//For existing Q1 users

In some special cases, if batch creation is required, the user must set his own password when he first logs in. For example:

[root@localhost ~]# Chage-d 0 q1//New users, existing users are applicable
Localhost login: q1
password: 
You are required to change your password immediately (root enforced)
WARNING: Your password has expired.
You must change your password now and login again!
//Change the password of user q1.
//Change STRESS password for q1.
(Current) UNIX Password:

(3) Order History and Automatic Log-off

The command history mechanism of Shell environment provides great convenience for users, but on the other hand, it also brings potential risks to users. As long as the user's command history file is obtained, the user's command operation process will be exhaustive. If the password in plaintext has been input on the command line, it will bring huge benefits to the server. Risk.

In Bash terminal environment, the record entries of historical commands are controlled by variable HISTSIZE. By default, 1000 entries can affect all users in the system by modifying their configuration files. For example:

[root@localhost ~]# Vim/etc/profile//For new logged-in users
                     ............                                   //Omit some content and add the following
HISTSIZE=200
[root@localhost ~]# export HISTSIZE=200  
//For current users, the role of export: Setting a variable to a global variable

In addition, you can modify the ~/.bash_logout file in the user host directory and add the operation statement of the situation history command:

[root@localhost ~]# vim ~/.bash_logout// / Open the configuration file and add the following
history -c                                                                  //Empty historical orders
clear                                                                        //Clean screen

In this way, when the user exits the logged-in Bash environment, the recorded historical commands are automatically cleared.

In Bash terminal environment, an idle timeout time can also be set. When there is no input beyond the specified time, the terminal can be automatically logged off. This can effectively avoid the risk of misoperation of the server by other personnel when the administrator is absent. The idle timeout is controlled by the variable TMOUT. The default unit is seconds (s).

[root@localhost ~]# Vim/etc/profile//For new logged-in users
                     ............                                   //Omit some content and add the following
export TMOUT=600
[root@localhost ~]# ExpoTMOUT = 600 // / For Current Users

Note: When compiling program code, modifying system configuration and other time-consuming operations should avoid setting TMOUT variables. If necessary, you can use the "unset TMOUT" command to cancel the TMOUT variable settings.

2. User switching and rights raising

Most Linux servers do not recommend that users log in directly as root users. On the one hand, it can greatly reduce the damage caused by misoperation; on the other hand, it also reduces the risk of privileged passwords being leaked in insecure networks. For these reasons, it is necessary to provide an identity or privilege promotion mechanism for ordinary users to perform administrative tasks when necessary.

Linux system provides us with su and sudo commands, in which su command is mainly used to switch users, while sudo command is used to enhance execution authority.

(1) su command - switching users

With the su command, you can switch to another specified user, thus having all the rights of that user. Of course, the password of the target user needs to be verified when switching (except when switching from root to other users). For example:

[root@localhost ~]# su - xiaoli
[xiaoli@localhost ~]$ su - root
//Password: //Enter User root Password
[root@localhost ~]#                                     // Get root privileges after verification

In the above command, the option "-" is equivalent to "- login" or "- l", which means that after switching the user, it enters the login shell environment of the target user. If the "-" option is not added, it means only switching identity, not switching the user environment. In the case of switching to root, root can be omitted.

By default, any user is allowed to use the su command. This gives you the opportunity to repeatedly try the login passwords of other users, such as root. This brings a great security risk. In order to strengthen the use control of su command, we can use pam_wheel authentication module to allow only very few users to switch using su command. Implementation process:

[root@localhost ~]# gpasswd -a xiaoli wheel
//User xiaoli is being added to the wheel group
[root@localhost ~]# grep "wheel"  /etc/group
wheel:x:10:xiaoli
[root@localhost ~]# vim /etc/pam.d/su
auth            sufficient      pam_rootok.so                              //Default exists
                 ............                                                             //Omit part of content
auth            required        pam_wheel.so use_uid               //Default exists, just remove the "#" number!
                 ............                                                             //Omit part of content

When pam_wheel authentication is enabled, other users who do not join the wheel group will not be able to use the su command. When they attempt to switch, they will be prompted to "deny permission" so as to limit the permissions of the switched users to a minimum.

[xiaozhang@localhost ~]$ su - root
 Password: // Whether the password is correct or not, the denial of privileges will be prompted
 su: Deny permission

Any user actions (add, delete, switch) will be recorded in the / var / log / security file, and can be viewed as needed.

(2) sudo command - enhance Execution Authority

It is very convenient to switch to another user by su command, but the prerequisite is to know the login password of the target user (except when switching from root user to other users), and the password of root user must be known when switching from any user to root user. For Linux servers in production environments, the fewer people the root user knows, the better, otherwise there will be a huge risk.

There is a way that ordinary users can have some administrative rights without knowing the password of root users. That is to use the sudo command.

Execution privileges can be increased by using sudo commands. However, administrators need to pre-execute authorization to specify which users will execute which commands as superusers (or other users).

1) Add authorization to configuration file / etc/sudoers

The configuration file of sudo mechanism is / etc/sudoers. The default permission of the file is 400. It needs to be written by special visudo tool. Although it can be edited by "vim", the command "w!" must be executed when saving, otherwise the system will prompt read-only files and refuse to save them.

In the configuration file/etc/sudoers, the basic configuration format of authorization records is:

User Host Name List = Command Program List

Authorization configuration mainly includes three parts: user, host and command, that is, who is authorized to execute which commands on which host. Specific meaning of each part:

User: directly authorize the specified user name, or use "% group name" (authorize all users of a group);
Host: The name of the host that uses this profile. This part is mainly to facilitate sharing a sudoers file among multiple hosts, usually set to local host or the actual host name.
Commands: Allow authorized users to make privileged commands through sudo mode, need to fill in the complete path of the command program, multiple commands are executed with commas "," separated;

In a typical sudo configuration record, each row corresponds to a sudo authorization configuration for a user or group. For example:

[root@localhost ~]# visudo
                              ..................             //Omit part of content
xiaozhang       localhost=/sbin/ifconfig    //Allow user xiaozhang to use the ifconfig command locally
%wheel  ALL=NOPASSWD:ALL            //Allow members of the wheel group to execute arbitrary commands on any host without using a password

Centrally defined aliases can be used when there are more users using the same authorization or when there are more authorized commands. Users, hosts, and commands can be defined as aliases (which must be capitalized) set by keywords User_Alias, Host_Alias, and Cmnd_Alias, respectively. For example:

[root@localhost ~]# visudo
                              ..................             //Omit part of content
User_Alias      OPERATORS=user1,user2,user3                 //Define a list of usernames
Host_Alias      MAILSVRS=smtp,pop                                   //Define host list
Cmnd_Alias      PKGTOOLS=/bin/rpm,/usr/bin/yum            //Define a list of commands
OPERATORS       MAILSVRS=PKGTOOLS                       //Associate all defined lists

The command part of sudo configuration record allows wildcards "*" and anti-symbols "!" It is especially useful when you need to authorize all commands in a directory or cancel individual commands. For example:

[root@localhost ~]# visudo
                              ..................             //Omit part of content
xiaowang        localhost=/bin/*,!/bin/passwd root  
//Allow xiaowang users to use all commands in the / bin path locally, but do not allow root users to change passwords

Usually, operations performed by sudo are not recorded. To enable sudo logging for viewing, you should do this:

[root@localhost ~]# visudo
                              ..................             //Omit part of content
Defaults logfile="/var/log/sudo"
2) Executing privileged commands through sudo

For authorized users, when executing privileged commands through sudo mode, just add "sudo" before normal commands.

[xiaosun@localhost ~]$ sudo ifconfig ens33 192.168.1.1/24

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for xiaosun: 
xiaosun Be not in sudoers Document. This matter will be reported.
//Because xiaosun was not authorized by the privileged command
[xiaozhang@localhost ~]$ ifconfig ens33 192.168.1.1/24
SIOCSIFADDR: Operations not allowed
SIOCSIFFLAGS: Operations not allowed
SIOCSIFNETMASK: Operations not allowed
[xiaozhang@localhost ~]$ sudo ifconfig ens33 192.168.1.1/24

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for xiaozhang:                 
//When executing a command, you need to enter your own password for validation (if you do not want to enter a password, you should add "NOPASSWD" before the command)
//xiaozhang can use privileged commands (already authorized)

In the current session, when executing a command through sudo for the first time, the user's own password (not root's password) must be known to verify it. When using sudo command after that, as long as the interval between the previous sudo operation and the previous sudo operation does not exceed 5 minutes, there is no need to repeat the validation.

If you want to see which privileged commands and environment variables the user obtains, you can execute the "sudo-l" command.

[xiaozhang@localhost ~]$ sudo -l
[sudo] password for xiaozhang: 
//Match the default entry for xiaozhang on this host:
    !visiblepw, always_set_home, env_reset, env_keep="COLORS DISPLAY HOSTNAME
    HISTSIZE KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG
    LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION
    LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC
    LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS
    _XKB_CHARSET XAUTHORITY", secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin,
    logfile=/var/log/sudo

//User xiaozhang can run the following commands on the host:
    (root) /sbin/ifconfig
//View authorized users
[root@localhost ~]# su - xiaosun
//Last logon: 27 August 21:41:40 CST 2019pts/0
[xiaosun@localhost ~]$ sudo -l
[sudo] password for xiaosun: 
//Sorry, user xiaosun can't run sudo on localhost.
//View as an authorized user

If sudo logs are enabled, you can view user sudo's operating records.

[root@localhost ~]# tail /var/log/sudo
Aug 27 21:41:07 : xiaoli : TTY=pts/0 ; PWD=/home/xiaoli ; USER=root ;
    COMMAND=/sbin/ifconfig ens33 192.168.1.1/24
Aug 27 21:42:53 : xiaozhang : TTY=pts/0 ; PWD=/home/xiaozhang ; USER=root ;
    COMMAND=/sbin/ifconfig ens33 192.168.1.1/24

II. System boot and login control

In the Internet environment, most servers are managed by remote login, while local boot and terminal login are often ignored, leaving security risks. Especially when the server's room environment is anti-strict and safe management system, how to prevent the illegal intervention of other users has become a problem that must be paid attention to.

1. Switch Safety Control

For server hosts, in addition to physical security. In the safety control of switchgear, besides physical safety protection, some safety measures of the system itself should be done well.

(1) Adjusting BIOS boot settings

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

(2) Prohibit ctrl+Alt+Del shortcut key restart

Shortcut key restart function provides convenience for server local maintenance, but for multi-terminal login Linux server, it is a safe choice to disable this function. The operation is as follows:

[root@localhost ~]# Cat/etc/inittab//View the file that provides ctrl+Alt+Del shortcuts
                                ..................                 //Omit part of content
# Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target
[root@localhost ~]# ll /usr/lib/systemd/system/ctrl-alt-del.target 
lrwxrwxrwx. 1 root root 13 7 April 1418:54 /usr/lib/systemd/system/ctrl-alt-del.target -> reboot.target
//Check to see that it's a soft connection to the reboot.target file

Without affecting the reboot.target file, you can disable the ctrl+Alt+Del shortcut by executing the following commands

[root@localhost ~]# System CTL mask ctrl-alt-del.target//cancel ctrl+Alt+Del service
Created symlink from /etc/systemd/system/ctrl-alt-del.target to /dev/null.
[root@localhost ~]# System CTL daemon-reload//reload system D configuration
[root@localhost ~]# System CTL unmask ctrl-alt-del.target//Re-open ctrl+Alt+Del service
Removed symlink /etc/systemd/system/ctrl-alt-del.target.
[root@localhost ~]# System CTL daemon-reload//reload system D configuration  

(3) Restrict the change of GRUB boot parameters

From the point of view of system security, if people can modify GRUB boot parameters, it is obviously a great security risk to the server itself. In order to strengthen the security control of boot process, a password can be set for GRUB menu. Only the correct password can be provided to modify boot parameters.
The password set for GRUB menu is recommended to be generated by the command "grub2-mkpasswd-pbkdf2".
The password set for GRUB menu is recommended to be generated by the command "grub2-mkpasswd-pbkdf2".

[root@localhost ~]# grub2-mkpasswd-pbkdf2//Enter password as prompted
//Enter password:
Reenter password: 
PBKDF2 hash of your password is 
//"Is" is followed by an encrypted password string character (not publishable due to restrictions)
[root@localhost ~]# cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak
[root@localhost ~]# cp /etc/grub.d/00_header /etc/grub.d/00_header.bak
//It's recommended to make a backup (experimental environment, it doesn't matter)
[root@localhost ~]# Vim/etc/grub.d/00_header// This is a configuration file that generates passwords through key tools
                   ........................                         //Omit part of content
cat << EOF
set superusers="root"                                      //Username
password_pbkdf2 root                                    
//Fill in the key file just generated through the key tool (that is, after the key file "is" just generated, because of restrictions can not be released)
//Set the password for the username 
EOF
[root@localhost ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
//Rebuild configuration file

When you re-test the computer and press the "e" button to enter the GRUB menu, you will be prompted:

Enter the correct username and password before you can enter (the experiment uses root, which has nothing to do with root in the system)!

2. Terminal and login control

(1) Restrict the login of root users

In Linux, the login program reads the / etc / security file to determine which terminals the root user logs in from.

[root@localhost ~]# vim /etc/securetty 
                   ........................                  //Omit part of content
#tty5
#tty6
//Prohibit root users to log in from tty5 and tty6

(2) Prohibit ordinary users from logging in

When the server is doing maintenance work such as backup or debugging, it may not want to have new users to log on to the system. At this time, it is only necessary to establish / etc/nologin empty file; otherwise, it allows ordinary users to log on.

[root@localhost ~]# Touch/etc/nologin//Disallow Ordinary User Logon
[root@localhost ~]# Rm-rf/etc/nologin//Allow ordinary users to log in

Note: Only recommended during server maintenance and testing!

3. Weak Password Detection and Port Scanning

The security tools used in this experiment are John the Ripper and NMAP.
John the Ripper Tool Disk Link: https://pan.baidu.com/s/1HQNCPFnKNBQWmjSNSEZ7_Q
Extraction code: q1b0
NMAP tools can be installed using yum!

1. Weak Password Detection Tool - John the Ripper

For any administrator who is responsible for security, it is necessary to find out these weak passwords in time so as to take further security measures (modifying passwords).

John the Ripper is an open source password cracking tool that can quickly analyze plaintext password strings with known ciphertext, support DES, MD5 and other encryption algorithms, and allow the use of dictionaries to crack.

(1) Install John the Ripper

[root@localhost ~]# tar zxf john-1.8.0.tar.gz -C /usr/src
[root@localhost ~]# cd /usr/src/john-1.8.0/
[root@localhost john-1.8.0]# ls
doc  README  run  src
//The doc directory is a manual document, README is a link description file, run is a running program, and src is a source file.
[root@localhost john-1.8.0]# cd src
[root@localhost src]# make clean linux-x86-64
//Compiling in this way
[root@localhost src]# cd ../run
[root@localhost run]# ls
ascii.chr   john       lm_ascii.chr  makechr       relbench  unique
digits.chr  john.conf  mailer        password.lst  unafs     unshadow
//Confirm that john executable program is generated

(2) Detecting weak password accounts

Take Linux system as an example (if other ciphertext files are detected, a copy can be made locally):

[root@localhost run]# ./john /etc/shadow
Loaded 6 password hashes with 6 different salts (crypt, generic crypt(3) [?/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
123456           (user1)
123456           (xiaowang)
123456           (xiaosun)
123456           (xiaoli)
123456           (xiaozhang)
..................              Press Ctrl+C Combination key terminates subsequent process
//Password deciphering takes time and patience

(3) Use password dictionary to crack

[root@localhost run]# :>john.opt
//A list of accounts that have been cracked for reanalysis and cracking
[root@localhost run]# ./john --wordlist=./password.lst /etc/shadow
//Use the password dictionary that comes with the tool itself to crack
Loaded 6 password hashes with 6 different salts (crypt, generic crypt(3) [?/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
123456           (user1)
123456           (xiaowang)
123456           (xiaosun)
123456           (xiaoli)
123456           (xiaozhang)
..................              Press Ctrl+C Combination key terminates subsequent process

2. Network Scanning Tool - NMAP

(1) Installing NMAP package

[root@localhost ~]# yum -y install nmap

(2) Scanning Grammar and Types

nmap [Scan Type] [Option] <Scan Target...>

Common options are:
"-p" is used to specify port information for scanning;
"-n" means disabling reverse DNS parsing (speeding up scanning);

Several commonly used scanning types, such as:

(3) Examples of scanning operations

[root@localhost ~]# nmap 127.0.0.1
//Scanning native open TCP ports
[root@localhost ~]# nmap -sU 127.0.0.1
//Scanning UDP ports opened locally
[root@localhost ~]# nmap -p 21 192.168.1.0/24
//Scan 192.168.1.0 which hosts provide FTP services
[root@localhost ~]# nmap -n -sP 192.168.1.0/24
//Scan 192.168.1.0 segment surviving hosts (can ping through)
[root@localhost ~]# nmap -p 139,445 192.168.1.0/24
//Scan 192.168.1.0 segment for hosts that open shared services

Different options can be changed according to actual needs!

Tags: Linux sudo vim shell

Posted on Tue, 27 Aug 2019 04:16:33 -0700 by j4ymf