Linux Server Security Tips and Best Practices

checklist for SysAdmins

This article includes a collection of commands and best practices that you can use to improve the security of your Linux servers (RHEL/CentOS)

1. Remove insecure tools (FTP, telnet, rlogin, rsh, etc.) and use only secure alternatives (SCP, SSH, sftp, rsync, etc.)

When choosing data communication tools, use only the secure and encrypted tools and remove the rest of the tools from the server.

$ yum erase xinetd ypserv tftp-server telnet-server rsh-server

2. Enable firewall/Iptables

Iptables allows you to configure the IP packet filter rules of the Linux kernel firewall. To get the maximum advantage, you may need some advanced knowledge on setting up these rules. The following are few examples that you can try.

$ service iptables start// Force SYN packets check
$ iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP// Drop XMAS packets
$ iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP// Drop null packets
$ iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP// Drop incoming packets with fragments
$ iptables -A INPUT -f -j DROP

3. Disable unwanted services and daemons

You may not need services like AutoFS, NFS, FTP, HTTP, NIS, telnetd, sendmail most of the time. You can remove/disable them.

$ chkconfig –list | grep ‘3:on’
$ service serviceName stop
$ chkconfig serviceName off$ yum remove packageName

4. Audit installed packages and remove unwanted ones regularly

A smaller number of packages always results in a smaller security threat surface, which means fewer potential threats at the end of the day. Therefore, keep only the necessary packages and clean up the rest.

$ yum list installed
$ yum list packageName
$ yum remove packageName

5. Audit listening network ports and block unwanted ones regularly

From time to time, you might open ports for different services and leave them out later. This is very risky, so you must always be conscious of your open ports at any given time and make sure that unwanted ones are blocked.

// List open ports of own server
$ netstat -tulpn
$ ss -tulpn// List open ports of any server in network
$ nmap -sT -O localhost
$ nmap -sT -O server.example.com// Use chkconfig to disable corresponding services
$ chkconfig –list | grep ‘3:on’
$ service serviceName stop
$ chkconfig serviceName off

6. Audit user accounts and disable the unwanted ones regularly

Only add the minimum number of user accounts needed and disable the rest.

// Lock password (add ! in the second field of the file /etc/passwd, password authentication will fail because of this, but other authentication methods like SSH keys will still work)
$ usermod -L userName
$ passwd -l userName// Unlock password (i.e. revert the effect of above command)
$ passwd -u userName// Expire account
$ chage -E0 userName// Change default shell to non-interactive, so user won't get any login shell
$ usermod -s /sbin/nologin userName// Verify locked user account (*LK* flag in the output indicates that the account is locked)
$ passwd --status userName
userName *LK* 2021-04-05 0 45 7 -1 (Password set, SHA512 crypt.)// Verify password and account expiration
$ chage -l userName
Last password change: Jan 19, 2021
Password expires: Jan 02, 2022
Password inactive: never
Account expires: Jan 02, 2022
Minimum number of days between password change: 0
Maximum number of days between password change: 45
Number of days of warning before password expires: 7// Verify non-interactive shell
$ grep ^userName /etc/passwd
userName:x:1000:1000:,,,:/home/userName:/sbin/nologin

7. Enable SELinux

Security-enhanced Linux (SELinux) is provided by the kernel as an access control security mechanism.

// View current status
$ sestatus
$ system-config-selinux
$ getenforce// Enable SELinux (using command)
$ setenforce enforcing
$ setenforce 1// Enable SELinux (by editing config file)
$ vi /etc/selinux/config

8. Turn off IPv6

Unless you use IPv6 for a specific reason, you can disable it.

$ vi /etc/sysconfig/networkNETWORKING_IPV6=no
IPV6INIT=no

9. Make /boot directory a read-only

By default, the /boot directory allows both read and write access. Since it includes the Linux kernel and its related files, you must protect them from unauthorized and unintended modifications.

$ vi /etc/fstabLABEL=/boot     /boot     ext2     defaults,ro     1 2

As a result, you may not be able to upgrade the kernel in the future. In such a scenario, you can temporarily revert this change.

10. Disable ICMP broadcast requests and harden /etc/sysctl.conf

Ping is the most fundamental way of checking whether a server is reachable over a network. Ping operates by sending ICMP (Internet Control Message Protocol) echo request packets to the target host and waiting for an ICMP echo reply. It’s used for testing and troubleshooting only. So when there’s no such need, you must keep it disabled. Also, it is best to harden /etc/sysctl.conf with the below configurations.

$ vi /etc/sysctl.conf# Ignore ICMP request
net.ipv4.icmp_echo_ignore_all = 1# Ignore Broadcast request
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_messages=1# Turn on execshield
kernel.exec-shield=1
kernel.randomize_va_space=1# Enable IP spoofing protection
net.ipv4.conf.all.rp_filter=1# Make sure spoofed packets get logged
net.ipv4.conf.all.log_martians = 1# Disable IP source routing
net.ipv4.conf.all.accept_source_route=0// Load new changes
$ sysctl -p

11. Strengthen password policy

Never allow user accounts with empty passwords.

// Check for empty password accounts
$ cat /etc/shadow | awk -F: ‘($2==””){print $1}’

Also, force strong passwords using tools like pam_cracklib (PAM = pluggable authentication modules).

$ vi /etc/pam.d/system-authpassword requisite pam_cracklib.so retry=3 minlen=8 lcredit=1 ucredit=2 dcredit=2 ocredit=1// Notation
retry = retry attempts for a user to pick a good password before the passwd program aborts
lcredit = lower-case
ucredit = upper-case
dcredit = numeric (digit)
ocredit = non-alphanumeric (other)
minlen = minimum length

12. Monitor suspicious user activities

If you notice suspicious user activities or have to deal with difficult users with different trust levels, you can collect information about their activities and processes for post audits using psacct or acct tools.

$ yum install psacct// Enable
$ chkconfig psacct on
$ /etc/init.d/psacct start
$ /etc/init.d/psacct status// Find day-wise login info for a user
$ ac -d userName// Find last executed commands by a user
$ lastcomm userName// Find unsuccessful login attempts
$ faillog -u userName

13. Disable root login and password authentication for SSH

Root user is available in most Linux servers by default and hackers often try to get a login as root by guessing its password. Therefore, it’s recommended to disable the root account. First, ensure that you have an admin user account so that you can execute root-level commands later with the sudo special privileges access command. Then you can safely disable the root login.

$ vi /etc/ssh/sshd_configPermitRootLogin no

Also, you can disable password authentication in favour of a secure method, like SSH public-private key authentication.

$ vi /etc/ssh/sshd_configPasswordAuthentication no

14. Disable shutdown/restart on three-finger salute (Ctrl+Alt +Del)

You can define how a Linux system must react to a three-finger salute, but since someone can mistakenly also run it, it is better to disable it on always running servers.

$ vi /etc/inttab// Comment-out the line starting with `ca::ctrlaltdel:`
# ca::ctrlaltdel:/sbin/shutdown -t3 -r now

15. Remove desktops

You really don’t need to run desktops on a dedicated server. Disabling them increases not only performance but also security (fewer bloatware/packages = fewer security troubles).

$ yum groupremove "X Window System"
$ yum groupremove "GNOME Desktop"
$ yum groupremove "KDE Plasma Workspaces"
$ yum groupremove "Server with GUI"
$ yum groupremove "MATE Desktop"

16. Fix permissions on world-writable files and no-owner files

Find files with loose permissions and set correct user and group permissions.

// Find all world writable and sticky bits set files
$ find /dir -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print// Find all files not owned by any user or group
$ find /dir -xdev \( -nouser -o -nogroup \) -prin

17. Remove unwanted files/scripts/directories regularly and keep the server clean

If you create a temporary file/script/folder, make sure you remove it soon. Do not stack a huge load of old file data in a server because there can be a threat hidden somewhere.

18. Keep servers up to date

Always apply the latest security updates, releases, patches, etc. to your servers.

// Update all packages
$ yum updates// Update security-related packages
$ yum update --security// Check available updates
$ yum check-update

19. Collect Syslog regularly

Syslog helps you understand most suspicious behaviours and errors in services and packages. Collect syslog information proactively for potential investigation of security incidents in the future.

20. Set up periodic backups and secure offsite mount points for important files/directories

In the event of an intrusion or ransomware attacks, to ensure that critical data remains accessible, various backup strategies can be used. As a rule of thumb, backups are maintained at least as three copies, with at least two of them stored at separate locations, and with one location being offsite (the 3–2–1 backup rule).

Tools like rsync can help with backing up data in Linux and with many data-copying and backup-related features.

$ yum install rsync

21. Configure intrusion prevention tools at the network level

Tools like Fail2Ban can alter firewall rules to ban any address that has attempted to log in a specific number of times. Also, it can be used to spot and address authentication failure patterns, with support for email alerts too.

$ yum install fail2ban

22. Perform security audits regularly

Tools like auditd can help to collect basic system audit information and keep a record on the disk, for instance, of predefined rules in /etc/audit.rules.

However, it is always industry best practice to run security audits using specialized commercial tools too, especially when it’s an enterprise environment. With these audits, misconfiguration, expired policies, pending updates, and rare threats can be revealed.