How To Secure Your Linux Server

0
1173

At the annual LinuxCon conference in 2015, Linux kernel creator Linus Torvalds shared his opinion on the security of the system. He stressed the need to mitigate the effect of the presence of certain bugs with competent protection, so that if one component is broken, the next layer would cover the problem.

In this article we will try to open this topic from a practical point of view:

  • start with the preliminary configuration and recommendations for the selection and installation of Linux distributions;
  • then tell you about a simple and effective point of protection – security update;
  • Next, we’ll look at how to set limits for programs and users;
  • How to secure a connection to the server via SSH;
  • Here are examples of configuring a firewall and limiting unwanted traffic;
  • In the final part, we’ll explain how to disable unnecessary programs and services, how to further protect servers from intruders.

 

1. Configure the preload environment before installing Linux

You need to take care of the security of the system before installing Linux. Here is a set of recommendations for setting up a computer that you should consider and perform before installing the operating system:

  • Loading in UEFI mode (not legacy BIOS)
  • Set the password for setting UEFI
  • Enable SecureBoot mode
  • Set a password at the UEFI level to boot the system

 

2. Select the appropriate Linux distribution

Most likely, you will choose popular distributions – Fedora, Ubuntu, Arch, Debian, or other close forks. In any case, you need to consider the mandatory presence of these functions:

  • Support for forced (MAC) and role-based access control (RBAC): SELinux / AppArmor / GrSecurity
  • Publication of security bulletins
  • Regular release of security updates
  • Cryptographic verification of packages
  • Support for UEFI and SecureBoot
  • Support for full native disk encryption

Recommendations for installing distributions

All distributions are different, but there are some points that you should pay attention to and do:

  • Use the full disk encryption (LUKS) with a reliable passphrase
  • The paging process should be encrypted
  • Set the password for editing the boot loader
  • A strong password for root access
  • Use an account without privileges that belongs to the Administrators group
  • Set a strong password for the user, different from the root password

 

3. Configure automatic security updates

One of the main ways to ensure the security of the operating system is to update the software. Updates often fix found bugs and critical vulnerabilities.

In the case of server systems, there is a risk of failures during the update, but in our opinion, problems can be minimized by automatically installing only the security update .

Auto-update works only for those installed from the repositories, rather than compiled packages themselves:

  • Debian / Ubuntu uses the unattended upgrades package for updates
  • CentOS uses auto-update for auto-update
  • In Fedora for these purposes there is dnf-automatic

To update, use any of the available package managers with the commands:

#yum update
#apt-get update
#apt-get upgrade

Linux can be configured to send notifications of new updates by email.

Also, to maintain security in the Linux kernel, there are security extensions , such as SELinux. Such an extension will help to save the system from misconfigured or dangerous programs.

SELinux is a flexible system of compulsory access control, which can work simultaneously with the selective access control system. Running programs get access to files, sockets and other processes, and SELinux sets limits so that harmful applications can not break the system.

4. Restrict access to external systems

The next protection method after the upgrade is to restrict access to external services. To do this, you need to edit the files /etc/hosts.allow and /etc/hosts.deny.

Here is an example of how to restrict access to telnet and ftp:
In the /etc/hosts.allow file:

hosts.allow 
in.telnetd: 123.12.41., 126.27.18., .mydomain.name, .another.name 
in.ftpd: 123.12.41., 126.27.18., .mydomain.name, .another.name

The example above will allow telnet and ftp connections to any host in IP classes 123.12.41. * And 126.27.18. *, As well as to the host with the domains mydomain.name and another.name.

Further in the file /etc/hosts.deny ‘:

hosts.deny
in.telnetd: ALL
in.ftpd: ALL

Adding a user with limited rights

We do not recommend connecting to the server as root, it has the rights to execute any commands, even critical for the system. Therefore, it is better to create a user with limited rights and work through it. Administration can be performed through sudo (substitute user and do) – this is a temporary elevation of privileges to the administrator level.

How to create a new user:

In Debian and Ubuntu:

Create a user by replacing the administrator with the desired name and specify the password in response to the request. The entered password symbols are not displayed on the command line:

adduser administrator

Add a user to the sudo group:

adduser administrator sudo

Now you can use the sudo prefix when executing commands that require administrator rights, for example:

sudo apt-get install htop 

In CentOS and Fedora:

Create a user by replacing the administrator with the desired name, and create a password for his account:

useradd adminstrator ; passwd administrator

Add a user to the wheel group to pass sudo rights to it:

usermod –aG wheel administrator

Use only strong passwords – at least 8 letters of a different register, numbers and other special characters. To search for weak passwords among users of your server, use utilities like “John the ripper”, change the settings in the pam_cracklib.so file to force passwords.

Use the chage command to set the password expiration period:

chage -M 60 -m 7 -W 7 UserName

You can disable password obsolescence with the command:

chage -M 99999 UserName

Find out when a user’s password is out of date:

 chage -l UserName

Also, you can edit the fields in the / etc / shadow file:

 {UserName}:{password}:{lastpasswdchanged}:{Minimum_days}:{Maximum_days}:{Warn}:{Inactive}:{Expire}:

Where,

  • Minimum_days: The minimum number of days before the password expires.
  • Maximum_days: The maximum number of days before the password expires.
  • Warn: The number of days before the expiration, when the user is warned about the approaching shift day.
  • Expire: The exact expiration date of the login.

Also, you should limit the reuse of old passwords in the pam_unix.so module and set the maximum number of unsuccessful user login attempts.

To see the number of failed login attempts:

faillog

Unblock account after unsuccessful login:

 faillog -r -u UserName

To lock and unlock accounts, you can use the passwd command:

 lock account
passwd -l UserName

 

unlocak account
passwd -u UserName

Make sure that all users have passwords, you can use the command:

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

Block users without passwords:

passwd -l  ИмяПользователя

Make sure that the UID parameter is set to 0 only for the root account. Enter this command to view all users with an equal 0 UID.

>awk -F: '($3 == "0") {print}' /etc/passwd

You should see only:

root:x:0:0:root:/root:/bin/bash

If there are other lines, check if you set the UID for them to 0, delete the unnecessary rows.

5. Configure access rights for users

After setting the passwords, it’s worth making sure that all users have access that matches their rank and responsibility. In Linux, you can set permissions on files and directories. This makes it possible to create and control different levels of access for different users.

The

Linux access category is based on working with multiple users, so each file belongs to one particular user. Even if the server is administered by one person, several accounts are created for different programs.

To view users in the system, you can use the command:

 cat /etc/passwd

The / etc / passwd file contains a string for each user of the operating system. For services and applications, individual users can be created, which will also be present in this file.

In addition to individual accounts, there is an access category for groups. Each file belongs to the same group. One user can belong to several groups.

To view the groups to which your account belongs, you can use the command:

groups

Display a list of all groups in the system, where the first field indicates the name of the group:

cat /etc/group

There is a “other” access category if the user does not have access to the file and does not belong to the group.

Access types

For user categories, it is possible to set access types. Usually this is the right to start, read, and modify the file. In Linux, access types are marked with two types of notation: alphabetic and octal.

In alphabetical notation, the permissions are marked with the letters:

r = read
w = change
x = start

In octal notation, the level of access to files is determined by numbers from 0 to 7, where 0 means no access, and 7 means full access to change, read and execute:

4 = read
2 = change
1 = start

 

6. Use keys for SSH connection

Usually password authentication is used to connect to the host via SSH. We recommend a more secure way, an input on a pair of cryptographic keys. In this case, the private key is used instead of the password, which seriously complicates the brute force selection.

For example, create a pair of keys. Actions must be performed on the local computer, not on the remote server. During the creation of keys, you can specify a password for accessing them. If you leave this field blank, you will not be able to use the generated keys before saving them to the keychain manager of the computer.

If you have already created RSA keys earlier, skip the generation command. To test existing keys, run:

ls ~/.ssh/id_rsa*

To generate new keys:

ssh-keygen –b 4096

Downloading the public key to the server

Replace the administrator with the name of the key owner, and 1.1.1.1 with the ip address of your server. From the local computer, type:

ssh-copy-id administrator@1.1.1.1

To check the connection, disconnect and reconnect to the server – the input must occur on the generated keys.

Configuring SSH

You can prevent SSH from connecting as root, and to get administrator rights, use sudo at the beginning of the command. On the server in the file / etc / ssh / sshd_config you need to find the PermitRootLogin parameter and set its value to no.

You can also disable the SSH connection by entering a password so that all users use the keys. In the / etc / ssh / sshd_config file, set the PasswordAuthentification parameter to no. If this line is missing or commented out, then add or uncomment it accordingly.

In Debian or Ubuntu, you can enter:

 class="">nano /etc/ssh/sshd_config

...
PasswordAuthentication no

Connection can also be further secured with two-factor authentication.

7. Install firewalls

A new vulnerability has recently been discovered that allows you to conduct DDoS attacks on servers running Linux. The bug in the kernel of the system appeared from version 3.6 at the end of 2012. Vulnerability allows hackers to inject viruses into download files, web pages and open Tor-connections, and for hacking it does not need to exert much effort – the IP-spoofing method will work.

Maximum harm for encrypted HTTPS or SSH connections is interruption of connection, but in unprotected traffic an attacker can place new content, including malicious programs. To protect against such attacks, firewall is suitable.

Blocking access using the Firewall

Firewall is one of the most important tools for blocking unwanted incoming traffic. We recommend to skip only the really necessary traffic and completely prohibit the rest.

To filter packets, most Linux distributions have an iptables controller. Usually it is used by experienced users, and for simplified configuration, you can use UFW utilities in Debian / Ubuntu or FirewallD in Fedora.

8. Disable unnecessary services

Specialists from the University of Virginia recommend that you disable all services that you do not use. Some background processes are set to autoload and work until the system is shut down. To configure these programs, you need to test the initialization scripts. The services can be started through inetd or xinetd.

If your system is configured via inetd, then in /etc/inetd.conf you can edit the list of background programs of “daemons”, to disable the loading of the service it is enough to put the “#” sign at the beginning of the line, turning it from an executable into a comment.

If the system uses xinetd, its configuration will be in the /etc/xinetd.d directory. Each directory file defines a service that can be disabled by specifying the item disable = yes, as in this example:

 class="">service finger
{
 type           = stream
  wait            = no
  user            = nobody
  server          = /usr/sbin/in.fingerd
  disable         = yes
}

It is also worth checking the persistent processes that are not controlled by inetd or xinetd. You can configure startup scripts in the directories /etc/init.d or / etc / inittab. After the changes made, run the command under the root account.

 class="">/etc/rc.d/init.d/inet restart

 

9. Protect the server physically

It is impossible to completely defend yourself from attacks by an attacker with physical access to the server. Therefore, you need to secure the room where your system is located. Data centers seriously monitor security, restrict access to servers, install security cameras and assign permanent security.

To enter the data center, all visitors must undergo certain stages of authentication. It is also highly recommended to use motion sensors in all rooms of the center.

10. Protect the server from unauthorized access

An unauthorized access system collects system configuration data and files and then compares these data with new changes to determine if they are harmful to the system.

For example, the Tripwire and Aide tools collect a database of system files and protect them with a set of keys. Psad is used to track suspicious activity using firewall reports.

Bro is designed to monitor the network, monitor suspicious activity schemes, collect statistics, execute system commands, and generate alerts. RKHunter can be used to protect against viruses, most often rootkits. This utility checks your system based on known vulnerabilities and can detect unsafe settings in applications.

Conclusion

The tools and settings listed above will help you partially protect the system, but security depends on your behavior and understanding of the situation. Without care, caution and constant self-study, all protective measures may not work.

LEAVE A REPLY

Please enter your comment!
Please enter your name here