Secure your Linux system
Reading Sun Tzu is just the first step in tackling those who seek to harm your Linux machines. Shashank Sharma reveals what you need to do next.
There’s an entire thread on Reddit discussing whether Professor Alastor ‘Mad-Eye’ Moody, from the Harry Potter books, ever uttered the catchphrase, “Constant vigilance!” Regardless of who to attribute the statement to, if you’re concerned about securing your Linux installation, whether as a home user or a system administrator, it’s good advice to adopt this mantra.
The entire gamut of operations that you can employ to defend yourself from threats are spread over the next few pages. We will walk you through creating a digital moat around your machines to stop the marching invaders in their tracks. This involves using password managers such as Keepass2, using secure login, working with ClamAV to detect trojans, viruses and malware, and more. We’ll also show you how you can make life easier for yourself by automating a number of essential tasks, such as monitoring the ports for scanners using tools like Nmap and implementing tools such as logcheck and logrotate to make sense of all the logs that are generated by various apps and services. Along the way, we’ll help you deploy a rootkit checker, discuss various passwordstrengthening measures and lots more. Finally, we’ll discuss the projects that are working towards making Linux even more secure for servers and networks and the efforts being made to make the kernel robust.
While we’re using Linux Mint for this feature (which is on the cover disc), all the tools discussed here can just as readily be used on any popular distro such as CentOS, Fedora, Mageia, Ubuntu, Debian and so on.
But first, baby steps. These are the tricks that you can and must adopt to secure your machines. If you’re interested in protecting a relative’s desktop which they use to browse the internet for their daily dose of entertainment or world politics, even these changes should be enough to set your mind at peace.
The first step is to choose the right distro. Sounds rather silly, but there’s a reason why you should give serious thought before settling on any Linux distro. You must consider whether the distro has a dedicated team working on pushing regular bug fixes and security updates. This is important, because in recent years, many security weaknesses in popular Linux apps and services such as Samba have been found and unless you plug these your system is at risk. As a further precaution, you can also disable or uninstall services that you don’t need. For instance, if you only have a single machine at home and haven’t configured it for printing, you don’t need CUPS or the Samba services.
Another trick to employ is to opt for encryption. Most Linux distros nowadays allow you to encrypt your home folder during installation itself. You can also optionally use apps such as zuluCrypt to configure encryption on your current installation.
It’s imperative to not use dictionary words nor keywords such as ‘qwerty’ or ‘god111’ as your passwords. The safest option is to ensure that passwords are reset regularly, and you can program your system to reject passwords that users have used previously.
Throughout the next few pages, you’ll find helpful hints and sometimes detailed instructions on how to adopt many of these principles into your Linux installation, apart from all the other advanced tools and tricks which you can use to thwart attackers.
To secure your machines, you must adopt a two-pronged strategy against potential attacks. The first involves preparing against intruders by installing a firewall and adopting better password policies. But this alone isn’t enough. It’s one thing to lock all the windows in your house, but you must still make sure no one got in before you closed them.
Trusting passwords to hold all your data is foolhardy. To prevent unauthorised access to your machine, you can add an extra layer of authentication. One of the easiest methods is by using the Google Authenticator service, which issues a time-based authentication token to supplement the existing password challenge.
You can configure the utility for all configured users on your Linux machine, and each will receive the OTP on their configured Android devices. Unless a user enters the token that quickly expires, they can’t log in. If you’ve configured your machine to allow remote logins, you can also configure Google Authenticator to work with SSH.
To implement this multi-factor authentication with Google Authenticator, you’ll need the Google Authenticator PAM module. PAM stands for ‘pluggable authentication modules’ — a mechanism for plugging different forms of authentication into a Linux computer.
The libpam-pwquality tool is another such module that you can use to improve your passwords. Open the /etc/pam.d/common-password file in your favourite text editor and identify the line that reads password [success=1 default=ignore] pam_ unix.so obscure sha512 . Add the minlen parameter to the end of the line if you want users to choose passwords with a minimum-length password [success=1 default=ignore] pam_ unix.so obscure sha512 minlen=8 .
If you similarly want to ensure that users choose passwords with a mix of upper/lower-case letters and special characters, throw in parameters such as lcredit=-3 ucredit=-2 dcredit=-2 , which forces users to respectively use three lower-case letter, two upper-case letters and two digits. You can install it using the sudo apt install libpampwquality command from the terminal.
CHECK FOR ROOTKITS
The password tricks discussed here, coupled with using a firewall and regular system updates, are a good start to protecting your system, but hackers often employ other means to do you harm. A common attack strategy used by attackers is privilege escalation, wherein after gaining access to the machine by compromising your password or installation of malicious script, an attempt is made to gain root access such that more harmful operations can be carried out. A rootkit is a script or program designed to gain unlawful root access for nefarious purposes.
One of the most popular rootkit scanners is chkrootkit. You can easily install it from the terminal with the sudo apt install chkrootkit command. Once installed, you can invoke it with the sudo chkrootkit command. The tool is designed to scan your machine for a host of known rootkits and malware. Run the
chkrootkit -l command for a list of all the tests the utility runs by default. Keep in mind that the process can take some time, depending on your system configuration and available resources.
A common trick adopted by rootkits is opening ports, which would allow an attacker entry into your system. You can scan your system for open ports using the Nmap utility. You can scan for ports by specifying a range or scan all of them with nmap -p 1-65535 localhost . The full range of Nmap’s capabilities are too vast for us to list here. Refer to the manual (use man nmap ) for details on getting the most out of it.
As a further precaution, you must also install the ClamAV app, which can detect trojans and viruses. If your setup involves Windows and Linux machines, it’s also recommended to install Linux Malware Detect, a malware scanner for Linux which even allows users to submit suspected malware for review.
“It’s one thing to lock all the windows in your house, but you must still make sure no one got in before you closed them.”
The security of a Linux machine involves more than mere installation of software. It requires active participation to monitor the log files and other reports generated by the host of tools and apps deployed. You must also interpret the reports and, where necessary, take further steps to deter attackers. Unless you’re willing to do all this, you’ll quickly end up with a machine that’s host to all manner of suspect activity.
But don’t panic. You can help yourself by automating a number of these tasks.
AUTOMATE SYSTEM MONITORING
A network analyser, often referred to as a sniffer, is a program that collects and gathers all network traffic. You can use it to determine if a malicious entity is attacking or has attacked your network. When your machine is set in promiscuous mode, the network interface will collect all network traffic passing through that interface.
You can use the ‘ngrep’ tool to watch your network in real time. It even enables you to separate packets based on specific parameters. The simplest way to use it is to run the ngrep command in the terminal to watch all traffic passing through the network. If you’ve never used the tool before, it’s best to study the output of ngrep, initially. Later on, you can begin playing around with different filters, which allow you to focus on packets based on host, type, protocol or direction (of traffic). You can use: ngrep port number > /tmp/ ngrep-logile to dump the traffic details to a log file and study it later.
CREATE CRON JOBS
Cron is a time-based scheduler which you can use to run defined operations at a specific time and date. It is commonly used to perform routine tasks such as backups. Every scheduled operation is referred to as a cron job. You can create such cron jobs to ensure your system isn’t compromised by scheduling lynis and chkrootkit to be run daily. You can create cron jobs using: crontab -e . This opens a the crontab file in a text editor and you can then add tasks. The syntax of a cron job is: minutes hours day month day_of_ week. That is, you can define the minute, hour, day, month, day of the week when each task should be run.
It’s best to schedule chkrootkit to run daily. You can configure it to run at 1am everyday by adding the following to the crontab file: 0 1 * * * /usr/sbin/ chkrootkit 2>&1 >chrootkit_log
WORK WITH LOG FILES
Your Linux system, the myriad applications and tools, and many everyday operations such as software management all generate log files. These are useful for three main reasons. They can help you troubleshoot system problems, such as the reason why a software installation failed. Next, logs can serve as an early warning system for security events. From a security point of view, if you are convinced your system has been compromised, logs can help you with performing forensic investigation.
You can only rely on the logs to determine something is wrong if you’re familiar with what the log reads like during normal system operation. It is imperative to be able to distinguish normal activity as opposed to someone trying to attack the system. You can only do this if you don’t just collect logs, but regularly study them too!
When dealing with logs, you must also have a thorough policy in place with regards to various factors such as frequency of logging. You should also routinely back up log files,
as comparing current logs with the archive can help you detect nefarious activity. At the same time, you can’t retain log files indefinitely, as they can take a large amount of space over a period of time.
MANAGE LOG FILES
You can use logrotate for easy management of log files. It supports automatic rotation, compression and mailing of log files and can be configured by editing the /etc/logrotate.conf file. The logrorate utility enables you to define the frequency of rotation, whether weekly or monthly, and the number of log files to be used for each log. You can also set different parameters for different log files and define whether a log is to be rotated based on its size, and the period for which a rotated log file is to be stored.
For example, if the rotation is set to 10 for the output.log file, the logrotate utility will automatically create output1.log, output2.log and so on until output10.log, while the latest logs will be stored in output.log. The man page has more details and you can find detailed instructions and examples easily on the internet as the utility has been around for ages.
Another popular tool is logcheck. It is designed to periodically scan all the logs — it starts the scan where it left off last time, saving crucial time. The highly configurable tool lets you define the frequency of checks, the log files to be checked, what is considered normal and not, and where to email the alerts. You must define the normal behaviour which the tool can ignore, otherwise you’ll be inundated with alerts.
SEARCH LOG FILES
Another important tool in the arsenal of log watchers is swatch. It works by looking for the specified regular expressions and promptly informs you when a match is found.
The user invoking swatch must create a ~/.swatchrc file which describes the ignore and ‘watchfor’ directives as well as the notification email address. The watchfor entry is a list of keywords that you want to be alerted about as soon as a match is found. You must be familiar with regular expressions to get the most out of swatch. Also your system must be configured to send mails to local users, as well as to an internet domain, if you want emails sent to external services such as Gmail.
Once configured, you can use swatch to monitor a number of logs for essential keywords.
So far, we have discussed a number of tools and practices that you can adopt to secure your system and prevent attacks, but there’s still plenty more that you can do, depending on whether you’re interested in protecting your server or your network, or even a home workstation.
The entire gamut of available solutions can very well lead to a troubling case of paralysis from analysis, which is why we listed some of the best protective tools. But there’s still more that various other projects and entities are working on to protect your machine from harm.
The Linux Security Modules (LSM) framework allows the Linux kernel to support a variety of security models to implement mandatory access control (MAC). SELinux and AppArmor are two of the most popular LSMs on Linux. While the former allows you to define the activities which can be performed by each user, process or daemon, AppArmor can be used to restrict each installed program using applicationspecific profiles. Container vendor Docker is also working on another LSM called Landlock, although it’s still at the nascent stage.
Apart from these, there are a large number of updates that ship with each new Linux kernel which fix many identified issues to keep you safe. On top of that, the Kernel Self Protection Project was started to provide additional layers of security to the Linux kernel.
You can also tweak a number of parameters on your kernel to bolster the security. Run sysctl -a for a list of current kernel settings. You can save these to a file with: sysctl -a > ~/sysctl.settings , which will enable you to use the file for reference or comparisons if you make any changes.
You can change these settings on your running kernel by editing the /etc/sysctl.conf file. On Linux Mint, the file already exists and contains a number of these settings, but they are disabled by default.
One of the biggest risks to system security is from untested and unknown applications and you must take precautions to protect your system from such programs. One way to do that is through sandboxing. This involves providing a compartmentalised environment to a script or app, so that the larger part of your installation remains protected.
SANDBOX WITH CHROOT
The oldest sandboxing tool in Linux, chroot can be used to change the root directory for a process. This prevents apps inside a chroot jail from accessing other directories or files. Containers such as Docker can similarly be used to run isolated application instances. If you’re spooked by the prospect of performing too many tasks to feel secure while connecting to the internet, consider using Subgraph OS. Based on Debian, the distro has been designed from the ground up, with a focus on security and privacy. It ships with a hardened Linux kernel, along with out-of-the-box sandboxing for applications, firewall and proxy.
Despite all these tools, you must understand that attaining a completely secure system is an unachievable goal. This is because the process would require you to, in the words of Linus Torvalds: “Unplug the network cable and instantiate draconian measures for physical security.” There’s no golden rule for security that applies in every case, and even if there were, it would have been cracked already. Security is something that needs to be worked on and personalised. With the combined weight of all the tools discussed, you’ll get the three essential ingredients for good system security — prevention, protection and detection — and that’s the best anyone can hope for.
Your system log files can be classified into four broad categories: application logs, event logs, system logs and service logs.
After completing the scans, lynis will provide a number of suggestions that you can incorporate to improve system security.
Nmap Front End (NmapFE) is a well designed and stable GUI that allows you to control almost every aspect of Nmap.