25 Hardening Security Tips for Linux Servers

Everybody says that Linux is secure by default and agreed to some extend (It’s debatable topics). However, Linux has in-built security model in place by default. Need to tune it up and customize as per your need which may help to make more secure system. Linux is harder to manage but offers more flexibility and configuration options.

Linux Security and Hardening Tips
25 Linux Security and Hardening Tips

Securing a system in a production from the hands of hackers and crackers is a challenging task for a System Administrator. This is our first article related to “How to Secure Linux box” or “Hardening a Linux Box“. In this post We’ll explain 25 useful tips & tricks to secure your Linux system. Hope, below tips & tricks will help you some extend to secure your system.

1. Physical System Security

Configure the BIOS to disable booting from CD/DVD, External Devices, Floppy Drive in BIOS. Next, enable BIOS password & also protect GRUB with password to restrict physical access of your system.

  1. Set GRUB Password to Protect Linux Servers

2. Disk Partitions

It’s important to have different partitions to obtain higher data security in case if any disaster happens. By creating different partitions, data can be separated and grouped. When an unexpected accident occurs, only data of that partition will be damaged, while the data on other partitions survived. Make sure you must have following separate partitions and sure that third party applications should be installed on separate file systems under /opt.

/
/boot
/usr
/var
/home
/tmp
/opt

3. Minimize Packages to Minimize Vulnerability

Do you really want all sort of services installed?. It’s recommended to avoid installing useless packages to avoid vulnerabilities in packages. This may minimize risk that compromise of one service may lead to compromise of other services. Find and remove or disable unwanted services from the server to minimize vulnerability. Use the ‘chkconfig‘ command to find out services which are running on runlevel 3.

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

Once you’ve find out any unwanted service are running, disable them using the following command.

# chkconfig serviceName off

Use the RPM package manager such as “yum” or “apt-get” tools to list all installed packages on a system and remove them using the following command.

# yum -y remove package-name
# sudo apt-get remove package-name
  1. 5 chkconfig Command Examples
  2. 20 Practical Examples of RPM Commands
  3. 20 Linux YUM Commands for Linux Package Management
  4. 25 APT-GET and APT-CACHE Commands to Manage Package Management

4. Check Listening Network Ports

With the help of ‘netstat‘ networking command you can view all open ports and associated programs. As I said above use ‘chkconfig‘ command to disable all unwanted network services from the system.

# netstat -tulpn
  1. 20 Netstat Commands for Network Management in Linux

5. Use Secure Shell(SSH)

Telnet and rlogin protocols uses plain text, not encrypted format which is the security breaches. SSH is a secure protocol that use encryption technology during communication with server.

Never login directly as root unless necessary. Use “sudo” to execute commands. sudo are specified in /etc/sudoers file also can be edited with the “visudo” utility which opens in VI editor.

It’s also recommended to change default SSH 22 port number with some other higher level port number. Open the main SSH configuration file and make some following parameters to restrict users to access.

# vi /etc/ssh/sshd_config
Disable root Login
PermitRootLogin no
Only allow Specific Users
AllowUsers username
Use SSH Protocol 2 Version
Protocol 2
  1. 5 Best Practices to Secure and Protect SSH Server

6. Keep System updated

Always keep system updated with latest releases patches, security fixes and kernel when it’s available.

# yum updates
# yum check-update

7. Lockdown Cronjobs

Cron has it’s own built in feature, where it allows to specify who may, and who may not want 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 user names in cron.deny and to allow a user to run cron add in cron.allow file. If you would like to disable all users from using cron, add the ‘ALL‘ line to cron.deny file.

# echo ALL >>/etc/cron.deny
  1. 11 Cron Scheduling Examples in Linux

8. Disable USB stick to Detect

Many times it happens that we want to restrict users from using USB stick in systems to protect and secure data from stealing. Create a file ‘/etc/modprobe.d/no-usb‘ and adding below line will not detect USB storage.

install usb-storage /bin/true

9. Turn on SELinux

Security-Enhanced Linux (SELinux) is a compulsory access control security mechanism provided in the kernel. Disabling SELinux means removing security mechanism from the system. Think twice carefully before removing, if your system is attached to internet and accessed by the public, then think some more on it.

SELinux provides three basic modes of operation and they are.

  1. Enforcing: This is default mode which enable and enforce the SELinux security policy on the machine.
  2. Permissive: In this mode, SELinux will not enforce the security policy on the system, only warn and log actions. This mode is very useful in term of troubleshooting SELinux related issues.
  3. Disabled: SELinux is turned off.

You can view current status of SELinux mode from the command line using ‘system-config-selinux‘, ‘getenforce‘ or ‘sestatus‘ commands.

# sestatus

If it is disabled, enable SELinux using the following command.

# setenforce enforcing

It also can be managed from ‘/etc/selinux/config‘ file, where you can enable or disable it.

10. Remove KDE/GNOME Desktops

There is no need to run X Window desktops like KDE or GNOME on your dedicated LAMP server. You can remove or disable them to increase security of server and performance. To disable simple open the file ‘/etc/inittab‘ and set run level to 3. If you wish to remove it completely from the system use the below command.

# yum groupremove "X Window System"

11. Turn Off IPv6

If you’re not using a IPv6 protocol, then you should disable it because most of the applications or policies not required IPv6 protocol and currently it doesn’t required on the server. Go to network configuration file and add followings lines to disable it.

# vi /etc/sysconfig/network
NETWORKING_IPV6=no
IPV6INIT=no

12. Restrict Users to Use Old Passwords

This is very useful if you want to disallow users to use same old passwords. The old password file is located at /etc/security/opasswd. This can be achieved by using PAM module.

Open ‘/etc/pam.d/system-auth‘ file under RHEL / CentOS / Fedora.

# vi /etc/pam.d/system-auth

Open ‘/etc/pam.d/common-password‘ file under Ubuntu/Debian/Linux Mint.

# vi /etc/pam.d/common-password

Add the following line to ‘auth‘ section.

auth        sufficient    pam_unix.so likeauth nullok

Add the following line to ‘password‘ section to disallow a user from re-using last 5 password of his or her.

password   sufficient    pam_unix.so nullok use_authtok md5 shadow remember=5

Only last 5 passwords are remember by server. If you tried to use any of last 5 old passwords, you will get an error like.

Password has been already used. Choose another.

13. How to Check Password Expiration of User

In Linux, user’s passwords are stored in ‘/etc/shadow‘ file in encrypted format. To check password expiration of user’s, you need to use ‘chage‘ command. It displays information of password expiration details along with last password change date. These details are used by system to decide when a user must change his/her password.

To view any existing user’s aging information such as expiry date and time, use the following command.

#chage -l username

To change password aging of any user, use the following command.

#chage -M 60 username
#chage -M 60 -m 7 -W 7 userName
Parameters
  1. -M Set maximum number of days
  2. -m Set minimum number of days
  3. -W Set the number of days of warning

14. Lock and Unlock Account Manually

The lock and unlock features are very useful, instead of removing an account from the system, you can lock it for an week or a month. To lock a specific user, you can use the follow command.

# passwd -l accountName

Note : The locked user is still available for root user only. The locking is performed by replacing encrypted password with an (!) string. If someone trying to access the system using this account, he will get an error similar to below.

# su - accountName
This account is currently not available.

To unlock or enable access to an locked account, use the command as. This will remove (!) string with encrypted password.

# passwd -u accountName

15. Enforcing Stronger Passwords

A number of users use soft or weak passwords and their password might be hacked with a dictionary based or brute-force attacks. The ‘pam_cracklib‘ module is available in PAM (Pluggable Authentication Modules) module stack which will force user to set strong passwords. Open the following file with an editor.

Read Also:

# vi /etc/pam.d/system-auth

And add line using credit parameters as (lcredit, ucredit, dcredit and/or ocredit respectively lower-case, upper-case, digit and other)

/lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 lcredit=-1 ucredit=-2 dcredit=-2 ocredit=-1

16. Enable Iptables (Firewall)

It’s highly recommended to enable Linux firewall to secure unauthorised access of your servers. Apply rules in iptables to filters incoming, outgoing and forwarding packets. We can specify the source and destination address to allow and deny in specific udp/tcp port number.

  1. Basic IPTables Guide and Tips

17. Disable Ctrl+Alt+Delete in Inittab

In most Linux distributions, pressing ‘CTRL-ALT-DELETE’ will takes your system to reboot process. So, it’s not a good idea to have this option enabled at least on production servers, if someone by mistakenly does this.

This is defined in ‘/etc/inittab‘ file, if you look closely in that file you will see a line similar to below. By default line is not commented out. We have to comment it out. This particular key sequence signalling will shut-down a system.

# Trap CTRL-ALT-DELETE
#ca::ctrlaltdel:/sbin/shutdown -t3 -r now

18. Checking Accounts for Empty Passwords

Any account having an empty password means its opened for unauthorized access to anyone on the web and it’s a part of security within a Linux server. So, you must make sure all accounts have strong passwords and no one has any authorized access. Empty password accounts are security risks and that can be easily hackable. To check if there were any accounts with empty password, use the following command.

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

19. Display SSH Banner Before Login

It’s always a better idea to have an legal banner or security banners with some security warnings before SSH authentication. To set such banners read the following article.

  1. Display SSH Warning Message to Users

20. Monitor User Activities

If you are dealing with lots of users, then its important to collect the information of each user activities and processes consumed by them and analyse them at a later time or in case if any kind of performance, security issues. But how we can monitor and collect user activities information.

There are two useful tools called ‘psacct‘ and ‘acct‘ are used for monitoring user activities and processes on a system. These tools runs in a system background and continuously tracks each user activity on a system and resources consumed by services such as Apache, MySQL, SSH, FTP, etc. For more information about installation, configuration and usage, visit the below url.

  1. Monitor User Activity with psacct or acct Commands

21. Review Logs Regularly

Move logs in dedicated log server, this may prevents intruders to easily modify local logs. Below are the Common Linux default log files name and their usage:

  1. /var/log/message – Where whole system logs or current activity logs are available.
  2. /var/log/auth.log – Authentication logs.
  3. /var/log/kern.log – Kernel logs.
  4. /var/log/cron.log – Crond logs (cron job).
  5. /var/log/maillog – Mail server logs.
  6. /var/log/boot.log – System boot log.
  7. /var/log/mysqld.log – MySQL database server log file.
  8. /var/log/secure – Authentication log.
  9. /var/log/utmp or /var/log/wtmp : Login records file.
  10. /var/log/yum.log: Yum log files.

22. Important file Backup

In a production system, it is necessary to take important files backup and keep them in safety vault, remote site or offsite for Disasters recovery.

23. NIC Bonding

There are two types of mode in NIC bonding, need to mention in bonding interface.

  1. mode=0 – Round Robin
  2. mode=1 – Active and Backup

NIC Bonding helps us to avoid single point of failure. In NIC bonding, we bond two or more Network Ethernet Cards together and make one single virtual Interface where we can assign IP address to talk with other servers. Our network will be available in case of one NIC Card is down or unavailable due to any reason.

Read Also : Create NIC Channel Bonding in Linux

24. 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. To do this, open “/etc/fstab” file.

# vi /etc/fstab

Add the following line at the bottom, save and close it.

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

Please note that you need to reset the change to read-write if you need to upgrade the kernel in future.

25. Ignore ICMP or Broadcast Request

Add following line in “/etc/sysctl.conf” file to ignore ping or broadcast request.

Ignore ICMP request:
net.ipv4.icmp_echo_ignore_all = 1

Ignore Broadcast request:
net.ipv4.icmp_echo_ignore_broadcasts = 1

Load new settings or changes, by running following command

#sysctl -p

If you’ve missed any important security or hardening tip in the above list, or you’ve any other tip that needs to be included in the list. Please drop your comments in our comment box. TecMint is always interested in receiving comments, suggestions as well as discussion for improvement.

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

75 thoughts on “25 Hardening Security Tips for Linux Servers”

  1. Thanks for the tips. I just rented a VServer, the first time that a Linux server of mine hangs freely on the Internet. Of course, you have to pay more attention to the security.

    Reply
  2. I am also administrating Linux servers for my client websites and facing too many security threats.

    Sometimes server got down after website update.

    I will also use above tips to secure my servers.

    Thanks for the tips.

    Reply
  3. kindly correct the english grammer mistakes and recheck for other errors. Otherwise a very good article for linux security. Recommended!

    Reply
  4. Hi,

    Kindly help me understand tip number 15.
    lcredit=-1 ucredit=-2 dcredit=-2 ocredit=-1 why these parameters have -1/-2 value.

    Thanks in advance
    Gaurav

    Reply
  5. Hello, For me SElinux do not work at all. Don’t know where to get help. Tried everything. My Linux say all the time, after sestatus, disabled, even if I edit etc /selinux/config.

    Reply
  6. Liked the efforts to write such a very useful article. Thanks.

    I’ve a situation where I want to ensure that a particular group of IT staff is not able to perform any execute or write on production servers. Is there a quick way to do so by adding them to “deny” files etc?

    Reply
  7. Hi Ravi,

    Any server-hardening-security-tips article then suggested me…because this article is very basic times. We need more security in servers…..also Suggested me any PAM article

    Reply
  8. I stopped reading at number 2. Different partitions do nothing for security or protection. If anything it can cause problems by having a partition that can become too small and fill. With current systems you can use raid 1 or do a rsync of the entire disk daily. The only real disk that needs to protected is /home.

    Reply
  9. One caveat on the way the SELinux tip was worded: just enabling it on its own does not instantly and magically give you any extra security, but it will slow your system down. If you’re not making explicit use of the features that it offers then disabling it will not reduce your security.

    SELinux is a module that provides more fine-grained access control over security policies. Before enabling it find out what it is and whether you will use that extra level of control, and balance that need against the fact that it does come with some amount of negative performance impact.

    But don’t just treat “Enable SELinux” as a checklist item to get out of the way and quickly move on, every installation.

    Reply
  10. Awesome…Appreciate your efforts…Looks like you can help me with my dilemma..I have installed RHEL 7.1 & 6.5 on VM in VMware work station. But I am not able to create repository..In fact, rpm also does not work. Any comments please? I am not able to move forward with setting up my server.

    Reply
  11. Hi,

    I want to block all user for cp and scp from our remote server to my local machine. please suggest me ..

    Thanks

    Reply
    • @Mohd,

      In sshd_config file, just comment out the following line to disable scp connections.

      ## override default of no subsystems
      #Subsystem       sftp    /usr/libexec/openssh/sftp-server
      
      Reply
    • @Mike,

      Thanks for the tip and we are well aware of it, in fact we’re in process to update this article to match the newest technologies..

      Reply
  12. This indeed is very well versed documented article for linux server hardening and shows to harden your core operating system. Thanks for sharing this nice information.

    Reply
  13. Great article – very useful. I would go as far as to say force users to use key based authentication if possible as SSH brute force attacks are relentless these days. Also it is worth considering using a real time security monitoring tool to identify malicious activity. Tools like siemless are easy to set up and operate a freemium operating model so home users and SME’s can be covered by 24/7 security monitoring for no fee.

    Reply
  14. @Hextreme – Really using ICMP for diagnostics??? Have you heard of LEM and SNMP? Or actively monitoring your servers?? Good article for people like Hextreme that has a lot to learn.

    Reply
  15. At least half the things in this list are completely bogus and certainly don’t increase security. Password protecting GRUB or the BIOS? If they have physical access to the machine, that’s trivial to get around. Disabling ICMP and broadcasts? That just breaks network diagnostics and doesn’t increase security at all. Empty passwords? That means NO LOGIN, which is certainly more secure than setting a password! NIC bonding isn’t security, it’s reliability…

    CTRL-ALT-DEL is a great shortcut for rebooting the system properly, turning it off doesn’t increase security in any way. If you can touch the keyboard you can just as easily pull the power cord.

    Reply
  16. very usefull thanks
    I use public private key authentication where ever possible. Especially on SSH and suppress password login. So I can allow SSH root login and have root as the only user on servers. Additionally I send a login notification automatically with the .bash_profile to my mailbox. So I can see if there is a unauthorized login by a forign IP address. So I also have to surveille only one user

    Reply
  17. Hi,

    Thanks for sharing information. i have one query, while adding below lines in /etc/pam.d/system-auth file. Is there any problem in system booting.

    password sufficient pam_unix.so nullok use_authtok md5 shadow remember=5
    /lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 lcredit=-1 ucredit=-2 dcredit=-2 ocredit=-1

    Reply
  18. “Minimize Packages to Minimize Vulnerability”
    in this which which package/services i have to remove/stop can you please tell me

    Reply
  19. Ravi, your article does not even touch the surface of linux hardening. Even distros where syslinux is not available can be maintained in many ways not mentioned in article. Starting from file system encryption and ending on warnings about specific services (i.e. mail servers should be tested for open relay, web servers should be kept in chrooted environment etc. etc.)

    Reply
  20. I would like to shift over from Windows to Linux, i have gone through ur valuable tips… can i get any links or suggestion for achieving the Certification in Linux….. kindly help… preparing for RHCSA…

    Reply
  21. I want to but linux whm server so let me know which port open in configserver firewall and ad which to be block

    Can you explain me the steps

    Regards
    Mayur

    Reply
  22. Please remove the part that says to disable ipv6. This does not harden a server and is grossly untrue as to say it is not needed.
    Some isp’s use ipv6.
    It has its place.
    When an isp has ipv6, and it is setup correctly on the pc’s, it doesn’t slow things down, cause stalls, etc etc.
    That happens when the isp in use doesnt support the potocol and the pc’s are searching for it.

    Reply
  23. Hi Ravi,

    This is an excellent article for someone new to Linux, I have a question with regard to No 3 how do I know what is needed and what is not, as I have quite few services running. Playing around with owncloud as a practical introduction to Linux.

    Reply
  24. Use tcp wrappers to allow and deny connections and have an email notification when someone is trying to access from not allowed locations.

    Reply
  25. Great article, one note though. ‘chkconfig’ is a Red Hat tool, that command won’t work on Ubuntu, you would need to follow a different process to stop/remove services for other distros.

    Reply
  26. Thanks for the tips,
    but .., beware tip #24, as it sent me in maintenance mode, and i’m running CentOS 6.4, the ext2 filesystem type should have rung a bell but didn’t and before i know it, i lost control of my system, although i learned something valuable outta this:

    If you’re stuck in maintenance mode (during bootstrap) and you get a root shell but everything’s read-only, and you can’t edit the file that sent you here, use the following command

    mount -o remount,rw /

    Many people go automatically fetch their livecd for that matter but i don’t think it’s adequate, this way, you don’t even to mount sysimage using your install cd. Hope it helps

    Reply
  27. Comment on 5. Never log in as root and use sudo, sudo encourages a weak passwords and hence weaker security (For example a 30+ password on root would be tedious, but this is what I have on my servers)

    Better to log in to root and do complex work that running multiple sudo commands. While you do get a sudo log, in my opinion working in this way on non trivial tasks is ridiculous.

    Reply
    • Why does sudo encourage weak passwords? If you find yourself constantly being timed out in sudo, and having to constantly enter your password, you can increase the timeout value.

      It’s safer to prevent root SSH login. SSH in as a different user, and su to root if you need to.

      Reply
  28. Thanks Ravi for sharing such an important doc.
    Here we are missing on
    1.ftp service :- Disabling the ftp services eg.vsftpd if it is not required..
    2.WWW files:- Secondly monitor the WWW files /folders, if possiable pls set strong umask . We should not have any system config files with WWW permissions,
    3.Enable audit and seconday login logs if you are using SUDO access,
    4.Stop sharing the users id’s, every end users should have his named id instead of using the genric user id’s..eg. on database servers normally we are having oracle / db2 / sybase user id’s used for binary installation purpose. We should disable the direct logins post the installation gets over and enable db team to have sudo su – , this will help us to segrate ownership.

    Reply

Got something to say? Join the discussion.

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.