15 Linux Hardening Steps to Keep Your Server Protected

Server hardening is the process of enhancing server security through various methods. We have a lot of steps to secure a server. Keep yourself and your company out by protecting your Linux systems from hackers, crackers, and attackers! You can turn a vulnerable box into a hardened server via the following steps. It will help you to prevent outside attacks. Here I’m  describing the server hardening of CentOS.

What to know

This guide walks you through the steps required to security harden CentOS 7. Hardening a system will make it more restrictive and you may run into issues. I recommend creating a duplicate virtual machine you can use for troubleshooting. Below you will find a list of basic steps you can and should take to harden your servers immediately after provisioning.

1. Secure remote access

Sometimes we access our server by remote methods and if it's not more secure, we can expose our server. OpenSSH options are controlled through the /etc/ssh/sshd_config file.

a. Disable SSH password authentication method and enable public key authentication method

It is important to disable password remote login method and enable authentication public key

Change ChallengeResponseAuthentication and PasswordAuthentication to no to deactivate password method

PasswordAuthentication no
ChallengeResponseAuthentication no

Authorize public key authentification

RSAAuthentication yes
PubkeyAuthentication yes

now you can generate new key pair

# ssh-keygen -t rsa

b. Disable direct root login

It is a risk security to allow root to login directly to the server. Instead, you should login to the system as your account and then do su - to login as root. So you need to change PermitRootLogin yes to PermitRootLogin no 

PermitRootLogin no

c. Change default SSH listening port (eg : 8500)

Sometimes it is not recommended to use the default port because it is known by all the world and it is a security risk. It is good to personalize the port to use

port 8500

2. Securing the Boot Loader with grub password

By securing the boot loader we can prevent access to single user mode which logs in automatically as root. This is done with GRUB by setting a password which is stored in plain text by default.

For Debian system

# grub-mkpasswd-pbkdf2

For Centos

# grub2-mkpasswd-pbkdf2

3. Listening Network Ports

After configuring network services, it is important to pay attention to which ports are actually listening on the system's network interfaces. Any open ports can be evidence of an intrusion.

# nmap -sT -O localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2017-06-07 23:13 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000061s latency).
Other addresses for localhost (not scanned): 127.0.0.1
rDNS record for 127.0.0.1: centos-01
Not shown: 995 closed ports
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
80/tcp open http
111/tcp open rpcbind
2049/tcp open nfs

To list all open ports and associated programs use the command below

# netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           
tcp        0      0 0.0.0.0:20048           0.0.0.0:*               LISTEN   

4. Narrow Down Permissions

Narrow down permissions for system files and folders to limit the risks.

# chmod 700 /root
# chmod 700 /var/log/audit
# chmod 740 /etc/rc.d/init.d/iptables
# chmod 740 /sbin/iptables
# chmod -R 700 /etc/skel
# chmod 600 /etc/rsyslog.conf
# chmod 640 /etc/security/access.conf
# chmod 600 /etc/sysctl.conf

5. Checking Accounts for Empty Passwords

Any account having an empty password means it's opened for unauthorized access to anyone on the web and it’s a part of security within a Linux server. To check accounts with empty password, use the command below

# cat /etc/shadow | awk -F: '($2==""){print $1}'
paul

For security, it is good to lock all empty password accounts:

# passwd -l paul
Locking password for user paul.
passwd: Success

6. Tune kernel parameters

Sysctl is an interface for examining and dynamically changing parameters in the Linux operating system. Edit /etc/sysctl.conf  file  to optimize  kernel parameters

Sysctl is the command used to modify kernel parameters at run time.

# sysctl -a
# sysctl -A
# sysctl net.ipv4.conf.all.rp_filter
To load settings, enter: 
# sysctl -p

Copy-Paste the following content into /etc/sysctl.conf

sysctl.conf

# Turn on execshield
kernel.exec-shield=1
kernel.randomize_va_space=1

# Enable IP spoofing protection
net.ipv4.conf.all.rp_filter=1

# Disable IP source routing
net.ipv4.conf.all.accept_source_route=0

# Ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.icmp_ignore_bogus_error_messages=1

# Make sure spoofed packets get logged
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# Disable ICMP routing redirects
sysctl -w net.ipv4.conf.all.accept_redirects=0
sysctl -w net.ipv6.conf.all.accept_redirects=0
sysctl -w net.ipv4.conf.all.send_redirects=0
sysctl -w net.ipv6.conf.all.send_redirects=0

# Disables the magic-sysrq key
kernel.sysrq = 0

# Turn off the tcp_sack
net.ipv4.tcp_sack = 0

# Turn off the tcp_timestamps
net.ipv4.tcp_timestamps = 0

# Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1

# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1

7. Disable Unwanted Services

You need to remove all unwanted services and daemons (services that runs in the background) from the system start-up which are started at boot time in run level 3.

# chkconfig --list | grep '3:on'

To disable service, enter:

# service serviceName stop
# chkconfig serviceName off

8. Require Authentication for Single User Mode

It is reommended to require root password when entering single user mode. Open /etc/sysconfig/init file and add the line:

SINGLE=/sbin/sulogin

9. Security Enhanced Linux (SELinux)

SELinux is a set of security rules that determine which process can access which file, directories, ports, etc. Every file, process, directory and port has a special security label called SELinux contexts. A context is simply a name that is used by the SELinux policy to determine whether or not a process can access a file, directory or port. By default, the policy does not allow any interaction, so explicit rules grant access. If there is no allow rule, no access is allowed.

getenforce command tells us what mode SELinux is in.

We  can change SELinux mode into enforcing by changing SELINUX=enforcing in /etc/sysconfig/selinux

SELinux

There are three directives in this file as explained below.

  • Enforcing: SELinux security policy is enforced.
  • Permissive: SELinux prints warnings instead of enforcing.
  • Disabled: SELinux is fully disabled.

You can check the status of SELinux with the command

# sestatus
SELinux status: disabled

You see that it is disabled. To enable it, you can use

# setenforce enforcing

10. Setup firewall with iptables

iptables is a user space application program that allows a system administrator to configure the tables provided by the Linux Kernel Firewall and the chains and rules it stores.

a. Close all the Unwanted ports

iptables -A INPUT -p tcp --dport PORT_NUMBER -j DROP

b. Block bad IP's

iptables -A INPUT -s IP_ADDRESS -j DROP

c. Block Connections to a Network Interface

To block connections from a specific IP address to a specific network interface, use the command

# iptables -A INPUT -i ens0 -s 6.6.6.6 -j DROP

d. List iptables rules

You can see all iptables rules by the command

iptables -L -n -v

iptables -L -n -v

11. Verifying File system

All SUID/SGID bits enabled file can be used for malicious activities, when the SUID/SGID executable has a security problem.All local or remote user can use such file.

a. Identify unwanted SUID and SGID binaries

find / \( -perm -4000 -o -perm -2000 \) -print
find / -path -prune -o -type f -perm +6000 -ls

b. Identify world writable files

find /dir -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print

c. Identify Orphaned files and folders

find /dir -xdev \( -nouser -o -nogroup \) -print

12. Keep /boot as read-only

Linux kernel and its related files are in /boot directory which is by default as read-write. Changing it to read-only reduces the risk of unauthorized modification of critical boot files. We need to edit /etc/fstab file and insert the line below<

LABEL=/boot     /boot     ext2     defaults,ro     1 2

13. Deny All TCP Wrappers

TCP wrappers can provide a quick and easy method for controlling access to applications linked to them. So it is recommended to block all the unused application and then authorized only the applications which will be used.

For example, we will block all applications but authorized ssh only

echo "ALL:ALL" >> /etc/hosts.deny 
echo "sshd:ALL" >> /etc/hosts.allow

14. Lock cronjobs for unauthorized users

Cron is used for automating jobs at a certain time. It is possible to specify who may and may not be able to run jobs. This is controlled by the use of files called /etc/cron.allow and /etc/cron.deny. To lock a user using cron, simply add usernames in cron.deny and to allow a user to run cron add in cron.allow file.

# echo ALL >>/etc/cron.deny

15. Secure the server against buffer overflow

A buffer overflow occurs when a program or process attempts to write more data to a fixed length block of memory, or buffer, than the buffer is allocated to hold.  It is important to protect your server again this attack

a. Enable ExecShield

It helps to prevent stack smashing. Typically, a buffer overflow exploit overwrites a return address so that a function will return to an attacker-chosen address. You need to enable on current kernel

sysctl -w kernel.exec-shield=1

You can also add the line below to /etc/sysctl.conf

kernel.exec-shield = 1

b. Check / Enable ASLR

Address Space Layout Randomization is a defense feature to make buffer overflows more difficult. ASLR makes difficult for the attacker to find an address to jump to. You need to enable randomized Virtual Memory Region Placement by setting runtime for kernel.randomize_va_space

sysctl -q -n -w kernel.randomize_va_space=2

Add the line below to /etc/sysctl.conf if it does not already exist

kernel.randomize_va_space = 2

Conclusion

These are some of the basic considerations for new users trying to run their own servers. Keep in mind that crackers are always a step ahead; they keep looking for any holes to hack into your server. It is important to recognize that, while it's better late than never, security measures decrease in their effectiveness the longer you wait to implement them

About Bobbin Zachariah

Founder of LinOxide, passionate lover of Linux and technology writer. Started his career in Linux / Opensource from 2000. Love traveling, blogging and listening music. Reach Bobbin Zachariah about me page and google plus page.

Author Archive Page

Have anything to say?

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.

2 Comments