Security Hardening of Linux Systems

Security Hardening of Linux Systems

Linux is a free and open-source Unix-like operating system. As an open-source operating system, Linux servers are widely used due to their significant advantages in security, efficiency, and stability. However, if permissions are not properly allocated, the security of the Linux system cannot be adequately guaranteed. Below, we will primarily use the RHEL7 system to optimize the security of Linux systems from aspects such as account security, login control, and SeLinux configuration.

Linux is a free and open-source Unix-like operating system. As an open-source operating system, Linux servers are widely used due to their significant advantages in security, efficiency, and stability. However, if permissions are not properly allocated, the security of the Linux system cannot be adequately guaranteed. Below, we will primarily use the RHEL7 system to optimize the security of Linux systems from aspects such as account security, login control, and SeLinux configuration.

As early as 1985, the U.S. Department of Defense proposed the Trusted Computer System Evaluation Criteria (TCSEC), which categorizes systems into four classes (A, B, C, D) with seven security levels. Level D is the lowest security level, Class C is for discretionary protection; Class B is for mandatory protection; Class A is for verified protection.

  • • Level D, lowest security
  • • Level C1, basic access control
  • • Level C2, improved discretionary access control (DAC), auditing
  • • Level B1, mandatory access control (MAC)
  • • Level B2, good structured design, formal security model
  • • Level B3, comprehensive access control, trusted recovery
  • • Level A1, formal certification

Current mainstream operating systems’ security is far from sufficient; for example, Windows NT can only reach level C2, indicating that security needs improvement. However, a hardened Linux system can achieve a B1 security level.

Control System Accounts: System accounts are stored by default in <span>cat /etc/passwd</span>. You can manually query user information. We will set all accounts, except for the Root account that needs to log in, to be prohibited from logging in.

Use <span>passwd -l username</span> to lock user logins. Below, we will write a <span>BASH</span> script to complete this process in bulk.

#!/bin/bash

for temp in `cut -d ":" -f 1 /etc/passwd | grep -v "root"`
do
        passwd -l $temp
done

Modify Password Lifetime: The password lifetime refers to the expiration time of user passwords, which is stored by default in <span>cat /etc/login.defs | grep "PASS"</span>. We need to reduce this time, as shown in the configuration below.

[root@localhost ~]# vim /etc/login.defs

# 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   90      # Maximum days a new user password can be used
PASS_MIN_DAYS   0       # Minimum days a new user password can be used
PASS_MIN_LEN    7       # Minimum password length
PASS_WARN_AGE   10      # Days before password expiration warning

Set Password Complexity: Set the complexity of the password entered when creating a new user. This configuration is stored by default in <span>cat /etc/pam.d/system-auth</span>.

[root@localhost ~]# vim /etc/pam.d/system-auth

#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.

password    required pam_cracklib.so try_first_pass retry=3 dcredit=-1 lcredit=-1 ucredit=-1 ocredit=-1 minlen=10

Add the following line to the above file, which means the password must contain at least one number, one lowercase letter, one uppercase letter, one special character, and the password length must be >=10.

Limit Login Timeout: Limit the waiting time after a user successfully logs in. If there is no operation on the user’s terminal, the connection will be disconnected by default.

[root@localhost ~]# vim /etc/profile

TMOUT=300
export TMOUT

Limit TTY Attempt Count: This configuration can effectively prevent brute-force login attempts. The configuration file is in <span>cat /etc/pam.d/login</span>. Add the following configuration; this method only limits user logins from TTY terminals and does not restrict remote logins.

[root@localhost ~]# vim /etc/pam.d/login

#%PAM-1.0
auth required  pam_tally2.so deny=3 lock_time=300 even_deny_root root_unlock_time=10

[root@localhost ~]# pam_tally2 --user lyshark    # Check remote login attempts

Modify SSH Remote Port: Change the SSH login port. Here, it can be changed to a high port like 65534, as the Nmap scanner only detects ports 0-1024 by default, which can effectively avoid scanning.

[root@localhost ~]# vim /etc/ssh/sshd_config

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
Port 65534               # Change login port to 65534
MaxAuthTries=3           # Maximum password attempts 3

[root@localhost ~]# systemctl restart sshd
[C:\Users]$ ssh [email protected] 6553

Disable Root User Login: First, create a normal user lyshark, then configure Sudo authorization. Use Sudo to execute commands when needed, and prohibit the Root user from logging into the host.

# --------------------------------------------------------------------------------------------
# Create normal user lyshark
[root@localhost ~]# useradd lyshark
[root@localhost ~]# passwd lyshark

# --------------------------------------------------------------------------------------------
# Add Sudo authorization to the normal user
[root@localhost ~]# vim /etc/sudoers

## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere 
root    ALL=(ALL)       ALL
lyshark ALL=(ALL)       ALL
# --------------------------------------------------------------------------------------------
# Modify ROOT user to prohibit login to the system
[root@localhost ~]# vim /etc/ssh/sshd_config
PermitRootLogin no

[root@localhost ~]# systemctl restart sshd

In addition, you can specify which usernames are allowed to use SSH, making the SSH service more secure.

[root@localhost ~]# vim /etc/ssh/sshd_config

AllowUsers lyshark admin          # Specify allowed login users
AllowGroup lyshark admin         # Specify allowed login user groups

Login Warning Prompt: Implement a pop-up warning prompt by modifying <span>/etc/motd</span> and <span>/etc/issue.net</span>. After a user logs in remotely, the following two lines of text will be prompted.

[root@localhost ~]# vim /etc/motd
[root@localhost ~]# vim /etc/issue.net

-----------------------------------------------------------------------------------------------
Warning! If unauthorized, illegal login system, please exit immediately!!
Your system fingerprint has been recorded!!
-----------------------------------------------------------------------------------------------

Limit Umask Value: The umask value is used to set the default attributes of files. The system’s default Umask value is 0022, meaning U permissions remain unchanged, G permissions are reduced by 2, and O permissions are reduced by 2. To prevent the upload of a web shell, we will change the system’s Umask value to <span>0777</span>, meaning that when a user creates any file, it will not have (read, write, execute) permissions, even if uploaded successfully.

[root@localhost ~]# echo "umask 0777" >> /etc/bashrc
[root@localhost ~]# touch test1
[root@localhost ~]# mkdir test2
[root@localhost ~]# 
[root@localhost ~]# ls -lh
total 0
----------. 1 root root 0 Aug 25 05:46 test1
d---------. 2 root root 6 Aug 25 05:46 test2

Lock System Files: Locking files is one of the most powerful security features in Linux systems. No user (even root) can write, delete, or perform other operations on immutable files. We will set some binary files to read-only mode to better prevent the system from being illegally tampered with or injected with malicious code. Generally, the contents of the /sbin and /usr/lib directories can be set to unchangeable.

[root@localhost sbin]# chattr +i /sbin/
[root@localhost sbin]# chattr +i /usr/sbin/
[root@localhost sbin]# chattr +i /bin/
[root@localhost sbin]# chattr +i /sbin/
[root@localhost sbin]# chattr +i /usr/lib
[root@localhost sbin]# chattr +i /usr/lib64
[root@localhost sbin]# chattr +i /usr/libexec

Limit GCC Compiler: If the system has been hacked, the next target for hackers should be to compile some POC files to escalate privileges and become root users within seconds. Therefore, we need to impose certain restrictions on the compilers in the system.

First, you need to check the single data packet to determine which binary files it contains. Then set all these files to 000 with no permissions.

[root@localhost ~]# rpm -q --filesbypkg gcc | grep "bin"

[root@localhost ~]# chmod 000 /usr/bin/c89 
[root@localhost ~]# chmod 000 /usr/bin/c99 
[root@localhost ~]# chmod 000 /usr/bin/cc
[root@localhost ~]# chmod 000 /usr/bin/gcc
[root@localhost ~]# chmod 000 /usr/bin/gcc-*
[root@localhost ~]# chmod 000 /usr/bin/gcc-*

Then, create a group that can access the binary files of the compiler and grant it the corresponding permissions.

[root@localhost ~]# groupadd compilerGroup
[root@localhost ~]# chown root:compilerGroup /usr/bin/gcc
[root@localhost ~]# chmod 0750 /usr/bin/gcc

At this point, any user attempting to use gcc will see a permission denied message.

[lyshark@localhost ~]$ gcc -c test.c 
-bash: /usr/bin/gcc: Permission denied

Limit Log Files: Next, we need to impose certain restrictions on log files because generally, if the system is compromised, log files will help us gather evidence. Once compromised, hackers will first try to clear these traces, so we need to set log files to be append-only, preventing them from being deleted.

[root@localhost ~]# cd /var/log/
[root@localhost log]# chattr +a dmesg cron lastlog messages secure wtmp 

[root@localhost log]# lsattr secure 
-----a---------- secure

[root@localhost log]# rm -fr secure 
rm: cannot remove ‘secure’: Operation not permitted

Minimize Firewall Rules: Configure the firewall to deny all ports, only allowing the necessary SSH and HTTP ports.

[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -p INPUT DROP

[root@localhost ~]# iptables -I INPUT -p tcp --dport 6553 -j ACCEPT
[root@localhost ~]# iptables -I OUTPUT -p tcp --dport 6553 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
[root@localhost ~]# iptables -A INPUT -p tcp --dport 443 -j ACCEPT
[root@localhost ~]# iptables-save

Enable SELinux: Since system administrators often disable it, you need to manually enable it.

[root@localhost ~]# vim /etc/selinux/config

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing

[root@localhost ~]# setenforce 1

After enabling SeLinux, you will find that the sshd service cannot start normally because the SELinux policy has taken effect. We need to modify the configuration below.

Allow SSH Port in SELinux: Use the Semanage management tool to allow port 6553.

[root@localhost ~]# yum install -y policycoreutils-python-2.5-29.el7.x86_64

[root@localhost ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      22

[root@localhost ~]# semanage port -a -t ssh_port_t -p tcp 6553

[root@localhost ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      6553, 22

Set Web Directory Permissions: Set web directory permissions using the semanage command.

[root@localhost html]# semanage fcontext -a -t httpd_sys_content_t /var/www/html/index.html

[root@localhost html]# ls -Z
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html

Link: https://www.cnblogs.com/LyShark/p/11407373.html

(Copyright belongs to the original author, please delete if infringed)

WeChat group

WeChat group

Security Hardening of Linux Systems

To facilitate better communication on operation and maintenance and related technical issues, a WeChat group has been created. Friends who need to join the group can scan the QR code below to add me as a friend (note: join the group).

Security Hardening of Linux Systems

Blog

Blog

Security Hardening of Linux Systems

CSDN Blog: https://blog.csdn.net/qq_25599925

Security Hardening of Linux Systems

Juejin Blog: https://juejin.cn/user/4262187909781751

Security Hardening of Linux Systems

Knowledge Planet: https://wx.zsxq.com/group/15555885545422

Security Hardening of Linux Systems

Long press to recognize the QR code to visit the blog website and see more high-quality original content.

Leave a Comment