What is linux hardening

Linux hardening steps for starters

Most systems have confidential data that needs to be protected. To safeguard this data, we need to secure our Linux system. But how to properly harden a Linux system? In this article, we will cover this step by step. We start by with physical security measures to prevent unauthorized people from access the system in the first place. Next is doing the installation the right way, so we have a solid foundation. Finally, we will apply a set of common security measures. After we are finished, your server or desktop system should be better protected. Are you ready? Let’s proceed with the first steps!

Table of Contents

Linux is already secure by default, right?

One of the myths about Linux is that it is secure, as it is not susceptible to viruses or other forms of malware. This is partially true, as Linux uses the foundations of the original UNIX operating system. Processes are separated and a normal user is restricted in what he or she can do on the system. Still, Linux is not perfectly secure by default. One of the reasons is the Linux distributions that package the GNU/Linux kernel and the related software. They have to choose between usability, performance, and security.

With the difficult choices that Linux distributions have to make, you can be sure of compromises. These compromises typically result in a lowered level of security. What about malware for Linux? That is a definitely a myth. The Linux platform also has its fair share of backdoors, rootkits, works, and even ransomware. That is one of the reasons why it is important to do system hardening, security auditing, and checking for compliance with technical guidelines.

There are many aspects to Linux security, including Linux system hardening, auditing, and compliance.

What is system hardening?

To improve the security level of a system, we take different types of measures. This could be the removal of an existing system service or uninstall some software components.

System hardening is the process of doing the ‘right’ things. The goal is to enhance the security level of the system. There are many aspects to securing a system properly. Yet, the basics are similar for most operating systems. So the system hardening process for Linux desktop and servers is that that special.

Core principles of system hardening

If we would put a microscope on system hardening, we could split the process into a few core principles. These include the principle of least privilege, segmentation, and reduction.

Principe of least privilege

The principle of least privileges means that you give users and processes the bare minimum of permission to do their job. It is similar to granting a visitor access to a building. You could give full access to the building, including all sensitive areas. The other option is to only allow your guest to access a single floor where they need to be. The choice is easy, right?

  • When read-only access is enough, don’t give write permissions
  • Don’t allow executable code in memory areas that are flagged as data segments
  • Don’t run applications as the root user, instead use a non-privileged user account
Читайте также:  Новейшая операционная система microsoft windows

Segmentation

The next principle is that you split bigger areas into smaller ones. If we look at that building again, we have split it into multiple floors. Each floor can be further divided into different zones. Maybe you visitor is only allowed on floor 4, in the blue zone. If we translate this to Linux security, this principle would apply to memory usage. Each process can only access their own memory segments.

Reduction

This principle aims to remove something that is not strictly needed for the system to work. It looks like the principle of least privilege, yet focuses on preventing something in the first place. A process that does not have to run, should be stopped. Similar for unneeded user accounts or sensitive data that is no longer being used.

System hardening steps

Overview of hardening steps

  1. Install security updates and patches
  2. Use strong passwords
  3. Bind processes to localhost
  4. Implement a firewall
  5. Keep things clean
  6. Security configurations
  7. Limit access
  8. Monitor your systems
  9. Create backups (and test!)
  10. Perform system auditing

1. Install security updates and patches

Most weaknesses in systems are caused by flaws in software. These flaws we call vulnerabilities. Proper care for software patch management help with reducing a lot of the related risks. The activity of installing updates often has a low risk, especially when starting with the security patches first. Most Linux distributions have the option to limit what packages you want to upgrade (all, security only, per package). Make sure that your security updates are installed as soon as they come available. It goes without saying, before you implementing something, test it first on a (virtual) test system.

Depending on your Linux distribution there might be a way to implement security patches automatically, like unattended upgrades on Debian and Ubuntu. This makes software patch management a lot easier!

2. Use strong passwords

The main gateway to a system is by logging in as a valid user with the related password of that account. Strong passwords make it more difficult for tools to guess the password and let malicious people walk in via the front door. A strong password consists of a variety of characters (alphanumeric, numbers, special like percent, space, or even Unicode characters).

3. Bind processes to localhost

Not all services have to be available via the network. For example, when running a local instance of MySQL on your web server, let it only listen on a local socket or bind to localhost (127.0.0.1). Then configure your application to connect via this local address, which is typically already the default.

4. Implement a firewall

Only allowed traffic should in an ideal situation reach your system. To achieve this, implement a firewall solution like iptables, or the newer nftables.

When creating a policy for your firewall, consider using a “deny all, allow some” policy. So you deny all traffic by default, then define what kind of traffic you want to allow. This is especially useful for incoming traffic, to prevent sharing services you didn’t intend to share.

5. Keep things clean

Everything installed on a system which doesn’t belong there can only negatively impact your machine. It will also increase your backups (and restore times). Or they might contain vulnerabilities. A clean system is often a more healthy and secure system. Therefore minimalization is a great method in the process of Linux hardening.

Actionable tasks include:

  • Delete unused package
  • Clean up old home directories and remove the users

6. Secure configurations

Most applications have one or more security measures available to protect against some forms of threats to the software or system. Look at the man page for any options and test these options carefully.

7. Limit access

Only allow access to the machine for authorized users. Does someone really need access or are alternative methods possible to give the user what he or she wants?

Читайте также:  Windows tightvnc config file

8. Monitor your systems

Most intrusions are undetected, due to lack of monitoring. Implement normal system monitoring and implement monitoring on security events. For example, the use of the Linux audit framework increased detection rates of suspected events.

9. Create backups (and test!)

Regularly make a backup of system data. This can prevent data loss. Even more important, test your backups. Having a backup is nice, but it is the restore that really counts!

Backups can be done with existing system tools like tar and scp . Another option to spare bandwidth is synchronizing data with tools like rsync. If you rather want to use a backup program, consider Amanda or Bacula.

10. Perform system auditing

Screenshot of a Linux server security audit performed with Lynis.

You can’t properly protect a system if you don’t measure it.

Use a security tool like Lynis to perform a regular audit of your system. Any findings are showed on the screen and also stored in a data file for further analysis. With an extensive log file, it allows to use all available data and plan next actions for further system hardening.

Lynis runs on almost all Linux systems or Unix flavors. It only requires a normal shell. Root permissions are preferred, yet not needed. The security tool is free to use and open source software (FOSS).

Additional hardening resources

Ready for more system hardening? Read then the extended version of the Linux security guide.

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Continue reading

How to secure a Linux system

Ubuntu system hardening guide for desktops and servers

Linux security guide: the extended version

How much system hardening should you do?

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Linux Audit

This blog is part of our mission: help individuals and companies, to scan and secure their systems. We simply love Linux security, system hardening, and questions regarding compliance.

Besides the blog, we have our security auditing tool Lynis. Open source, GPL, and free to use.

For those with enterprise needs, or want to audit multiple systems, there is an Enterprise version.

«One security solution to audit, harden, and secure your Linux/UNIX systems.»

Benefits:

  • Perform audits within a few minutes
  • Central management
  • Powerful reporting
  • Compliance checks (e.g. PCI DSS)
  • Additional plugins and more tests

Enjoy the articles!

Linux and UNIX security automation

Lynis is a free and open source security scanner. It helps with testing the defenses of your Linux, macOS, and Unix systems. Typical use-cases for this software include system hardening, vulnerability scanning, and checking compliance with security standards (PCI-DSS, ISO27001, etc).

Recent Posts

Contact

This blog is part of our mission to share valuable tips about Linux security. We are reachable via @linuxaudit

Company details

CISOfy
De Klok 28,
5251 DN, Vlijmen, The Netherlands
+31-20-2260055

Источник

Linux. Как работает hardening

Статья расскажет о том, как с помощью kconfig hardened check можно проверить настройку механизмов защиты ядра ОС Linux, которые используются для противодействия эксплойтам. На сегодняшний день данный инструмент, пожалуй, является одним из самых опасных инструментов нарушения разграничения доступа и функционирования ОС. Рассмотрим, какие основные параметры компиляции ядра и модули безопасности есть в официальном репозитории, а также попробуем выяснить, какие наборы механизмов применяются в различных дистрибутивах.

Инструменты и источники для проведения исследования

Исследование ОС Linux будем традиционно проводить на базе исходного кода, который доступен в официальном репозитории. В качестве инструментов исследования будем использовать:

Visual Studio Code;

Python в этом случае необходим для построение иерархии директорий, которые содержат исходный код. Именно этот метод верхнеуровневого представления будет использован как основной для исследования.

Читайте также:  Windows store apps application data

Подсистемы защиты

Головная боль любой ОС — разграничение доступа и уязвимости, которые приводят к повреждению памяти. Исторически сложилось так, что для создания ОС используются языки программирования, которые имеют определенные проблемы при неверной обработке памяти.

В ОС Linux с точки зрения защиты от различных атак на разграничение доступа и эксплуатацию уязвимостей используют следующие механизмы:

LSM фреймворк — механизм перехвата системных функций для обработки расширениями ядра Linux;

KASLR — рандомизация адресного пространства ядра;

HW-Vuln — митигации и патчи, которые используются против Hardware уязвимостей (Meltdown, Spectre, и т.д.);

Параметризация сборки и запуска ядра. Большое количество работающих алгоритмов в ядре — это потенциальный вектор для атаки, поэтому здесь исходят из минимально необходимого функционала, который можно оставить и при этом максимально уменьшить возможности проведения атак.

Большая часть механизмов противодействия атакам на разграничение доступа и эксплуатации уязвимостей находится в разделе linux/security :

Здесь в явном виде представлены модули ядра, которые можно использовать для улучшения механизмов защиты. Есть только маленькая неприятность — некоторые модули из этой директории не могут быть совместимы. На сегодняшний день, к сожалению, нет метода использования сразу несколько модулей LSM. Поэтому предполагается, что тот, кто хочет собрать себе ядро для своей ОС, должен самостоятельно решить, что за модуль ему подойдет больше. Всего их 11 штук:

Например, модуль tomoyo нельзя использовать с другими модулями.

В директории «security» есть описания для защит от различных техник, которые позволяют проводить эксплуатацию уязвимостей. Например — min_addr . Этот механизм защиты, который резервирует адреса в оперативной памяти, которые находятся рядом с нулевым адресом. Сделано это для того, чтобы нельзя было использовать начальные страницы в оперативной памяти для хранения данных эксплойта. Часть остальных «противодействий» в ядре запускается только с использованием дополнительных опций запуска ядра и компиляции. Обнаружить эти данные можно в hardening конфиге. Вся информация предоставляется только как описание отдельных параметров.

Выходит, что механизмы есть, но на выбор нужно собирать себе обойму самостоятельно. Это не удивительно, так как ядро Linux предоставляется для большого количества дистрибутивов, и поэтому разработчики отдельных дистрибутивов должны заниматься более тонкой настройкой. Давайте попытаемся выяснить, а что работает в конкретных дистрибутивах.

Ubuntu и его механизмы защиты

Популярный дистрибутив, который используется и как сервер, и для десктопов. Проверять будем с помощью вот этого инструмента — kconfig hardened check . Инструмент проверяет текущую настройку ядра с точки зрения безопасности и демонстрирует, какие параметры были установлены при установке системы. Репозиторий постоянно обновляется, поэтому список подсистем защит и параметров компиляции ядра намного больше того, что мы смогли обнаружить при исследовании исходного кода. Репозиторий предоставляет скрипт на Python для проверки опций в уже собранном дистрибутиве. Стоит отметить, что без использования эталонного конфига, инструмент показывает информацию по дистрибутиву, не указывая, что есть. Он показывает, что желательно бы иметь в качестве установленных параметров. Запускать проверку можно так:

kconfig-hardened-check -p X86_64 -c kspp-recommendations-x86-64.config

Вообще в репозитории есть 2 вида конфигов — обычный, который создан для конкретного дистрибутива, и рекомендуемый с точки зрения наибольшего количества безопасных опций. Ресурс kernsec характеризует KSSP конфиг как наиболее параноидальный с точки зрения количества применяемых параметоров. Результат для Ubuntu Server 20.04:

29 опций, которые не используются или не найдены из 111. Не такой уж плохой результат. Особенно если учесть, что конфиг эталона — параноидальный.

Debian и его механизмы защиты

Для исследования Debian был выбран неофициальный дистрибутив Debian, а его модификация — Kali Linux. Этот дистрибутив, который используют для тестирования на проникновение, посмотрим что у него у самого с параметрами безопасности:

Дистрибутив несмотря на то, что используется для узкого спектра задач все же содержит в себе достаточное количество опций и параметров ядра для противодействия атакам.

Таким образом можно выяснять, как настроен тот дистрибутив, которым вы пользуетесь на базе ядра ОС Linux.

Прямо сейчас в OTUS открыт набор на новый поток курса «Administrator Linux. Basic», Приглашаем всех желающих на бесплатный вебинар, в рамках которого наши эксперты подробно расскажут о курсе, процессе обучения, а также карьерных перспективах в данной сфере.

Источник

Оцените статью