Linux security operating systems

Системы защиты Linux

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

Предыстория Linux Security Modules и SELinux

Security Enhanced Linux представляет собой набор правил и механизмов доступа, основанный на моделях мандатного и ролевого доступа, для защиты систем Linux от потенциальных угроз и исправления недостатков Discretionary Access Control (DAC) — традиционной системы безопасности Unix. Проект зародился в недрах Агентства Национальной Безопасности США, непосредственно разработкой занимались, в основном, подрядчики Secure Computing Corporation и MITRE, а также ряд исследовательских лабораторий.

Linux Security Modules

Линус Торвальдс внес ряд замечаний о новых разработках АНБ, с тем, чтобы их можно было включить в основную ветку ядра Linux. Он описал общую среду, с набором перехватчиков для управления операциями с объектами и набором неких защитных полей в структурах данных ядра для хранения соответствующих атрибутов. Затем эта среда может использоваться загружаемыми модулями ядра для реализации любой желаемой модели безопасности. LSM полноценно вошел в ядро Linux v2.6 в 2003 году.

Фреймворк LSM включает защитные поля в структурах данных и вызовы функций перехвата в критических точках кода ядра для управления ими и выполнения контроля доступа. Он также добавляет функции для регистрации модулей безопасности. Интерфейс /sys/kernel/security/lsm содержит список активных модулей в системе. Хуки LSM хранятся в списках, которые вызываются в порядке, указанном в CONFIG_LSM. Подробная документация по хукам включена в заголовочный файл include/linux/lsm_hooks.h.

Подсистема LSM позволила завершить полноценную интеграцию SELinux той же версии стабильного ядра Linux v2.6. Буквально сразу же SELinux стал стандартом де-факто защищенной среды Linux и вошел в состав наиболее популярных дистрибутивов: RedHat Enterprise Linux, Fedora, Debian, Ubuntu.

Глоссарий SELinux

LSM и архитектура SELinux

Несмотря на название LSM в общем-то не являются загружаемыми модулями Linux. Однако также, как и SELinux, он непосредственно интегрирован в ядро. Любое изменение исходного кода LSM требует новой компиляции ядра. Соответствующая опция должна быть включена в настройках ядра, иначе код LSM не будет активирован после загрузки. Но даже в этом случае его можно включить опцией загрузчика ОС.

Стек проверок LSM

LSM оснащен хуками в основных функций ядра, которые могут быть релевантными для проверок. Одна из основных особенностей LSM состоит в том, что они устроены по принципу стека. Таким образом, стандартные проверки по-прежнему выполняются, и каждый слой LSM лишь добавляет дополнительные элементы управления и контроля. Это означает, что запрет невозможно откатить назад. Это показано на рисунке, если результатом рутинных DAC проверок станет отказ, то дело даже не дойдет до хуков LSM.

SELinux перенял архитектуру безопасности Flask исследовательской операционной системы Fluke, в частности принцип наименьших привилегий. Суть этой концепции, как следует из их названия, в предоставлении пользователю или процессу лишь тех прав, которые необходимы для осуществления предполагаемых действий. Данный принцип реализован с помощью принудительной типизации доступа, таким образом контроль допусков в SELinux базируется на модели домен => тип.

Благодаря принудительной типизации доступа SELinux имеет гораздо более значительные возможности по разграничению доступа, нежели традиционная модель DAC, используемая в ОС Unix/Linux. К примеру, можно ограничить номер сетевого порта, который будет случать ftp сервер, разрешить запись и изменения файлов в определенной папке, но не их удаление.

Основные компоненты SELinux таковы:

  • Policy Enforcement Server — Основной механизм организации контроля доступа.
  • БД политик безопасности системы.
  • Взаимодействие с перехватчиком событий LSM.
  • Selinuxfs — Псевдо-ФС, такая же, как /proc и примонтированная в /sys/fs/selinux. Динамически заполняется ядром Linux во время выполнения и содержит файлы, содержащие сведения о статусе SELinux.
  • Access Vector Cache — Вспомогательный механизм повышения производительности.


Схема работы SELinux

Все это работает следующим образом.

  1. Некий субъект, в терминах SELinux, выполняет над объектом разрешенное действие после DAC проверки, как показано не верхней картинке. Этот запрос на выполнение операции попадает к перехватчику событий LSM.
  2. Оттуда запрос вместе с контекстом безопасности субъекта и объекта передается на модуль SELinux Abstraction and Hook Logic, ответственный за взаимодействие с LSM.
  3. Инстанцией принятия решения о доступе субъекта к объекту является Policy Enforcement Server и к нему поступают данные от SELinux AnHL.
  4. Для принятия решения о доступе, или запрете Policy Enforcement Server обращается к подсистеме кэширования наиболее используемых правил Access Vector Cache (AVC).
  5. Если решение для соответствующего правила не найден в кэше, то запрос передается дальше в БД политик безопасности.
  6. Результат поиска из БД и AVC возвращается в Policy Enforcement Server.
  7. Если найденная политика согласуется с запрашиваемым действием, то операция разрешается. В противном случае операция запрещается.

Управление настройками SELinux

SELinux работает в одном из трех режимов:

  • Enforcing — Строгое соблюдение политик безопасности.
  • Permissive — Допускается нарушение ограничений, в журнале делается соответствующая пометка.
  • Disabled — Политики безопасности не действуют.

Посмотреть в каком режиме находится SELinux можно следующей командой.

Читайте также:  Visual basic окно поверх всех окон windows

Изменение режима до перезагрузки, например выставить на enforcing, или 1. Параметру permissive соответствует числовой код 0.

Также изменить режим можно правкой файла:

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing — SELinux security policy is enforced.
# permissive — SELinux prints warnings instead of enforcing.
# disabled — No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of three values:
# targeted — Targeted processes are protected,
# minimum — Modification of targeted policy. Only selected processes are protected.
# mls — Multi Level Security protection.

Разница с setenfoce в том, что при загрузке операционный системы режим SELinux будет выставлен в соответствии со значением параметра SELINUX конфигурационного файла. Помимо того, изменения enforcing disabled вступают в силу только через правку файла /etc/selinux/config и после перезагрузки.

Просмотреть краткий статусный отчет:

SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: permissive
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 31
Для просмотра атрибутов SELinux некоторые штатные утилиты используют параметр -Z.

По сравнению с обычным выводом ls -l тут есть несколько дополнительных полей следующего формата:

Последнее поле обозначает нечто вроде грифа секретности и состоит из комбинации двух элементов:

  • s0 — значимость, также записывают интервалом lowlevel-highlevel
  • c0, c1… c1023 — категория.

Изменение конфигурации доступов

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

Первая команда semanage login связывает пользователя SELinux с пользователем операционной системы, вторая выводит список. Наконец последняя команда с ключом -r удаляет связку отображение пользователей SELinux на учетные записи ОС. Объяснение синтаксиса значений MLS/MCS Range находится в предыдущем разделе.

Login Name SELinux User MLS/MCS Range Service
__default__ unconfined_u s0-s0:c0.c1023 *
root unconfined_u s0-s0:c0.c1023 *
system_u system_u s0-s0:c0.c1023 *
[admin@server

]$ semanage login -d karol

Команда semanage user используется для управления отображений между пользователями и ролями SELinux.

  • -a добавить пользовательскую запись соответствия ролей;
  • -l список соответствия пользователей и ролей;
  • -d удалить пользовательскую запись соответствия ролей;
  • -R список ролей, прикрепленных к пользователю;

Файлы, порты и булевы значения

Каждый модуль SELinux предоставляет набор правил маркировки файлов, но также можно добавить собственные правила для в случае необходимости. Например мы желаем дать веб серверу права доступа к папке /srv/www.

Первая команда регистрирует новые правила маркировки, а вторая сбрасывает, вернее выставляет, типы файлов в соответствии с текущими правилами.

Аналогично, TCP/UDP порты отмечены таким образом, что лишь соответствующие сервисы могут их прослушивать. Например, для того, чтобы веб-сервер мог прослушивать порт 8080, нужно выполнить команду.

Значительное число модулей SELinux имеют параметры, которые могут принимать булевы значения. Весь список таких параметров можно увидеть с помощью getsebool -a. Изменять булевы значения можно с помощью setsebool.

Практикум, получить доступ к интерфейсу Pgadmin-web

Рассмотрим пример из практики, мы установили на RHEL 7.6 pgadmin4-web для администрирования БД PostgreSQL. Мы прошли небольшой квест с настройкой pg_hba.conf, postgresql.conf и config_local.py, выставили права на папки, установили из pip недостающие модули Python. Все готово, запускаем и получаем 500 Internal Server error.

Начинаем с типичных подозреваемых, проверяем /var/log/httpd/error_log. Там есть некоторые интересные записи.

[timestamp] [core:notice] [pid 23689] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0
.
[timestamp] [wsgi:error] [pid 23690] [Errno 13] Permission denied: ‘/var/lib/pgadmin’
[timestamp] [wsgi:error] [pid 23690]
[timestamp] [wsgi:error] [pid 23690] HINT : You may need to manually set the permissions on
[timestamp] [wsgi:error] [pid 23690] /var/lib/pgadmin to allow apache to write to it.

На этом месте у большинства администраторов Linux возникнет стойкое искушение запустить setenforce 0, да и дело с концом. Признаться, в первый раз я так и сделал. Это конечно тоже выход, но далеко не самый лучший.

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

]$ yum install setroubleshoot
[admin@server

]$ journalctl -b -0
[admin@server

]$ service restart auditd

Обратите внимание на то, что сервис auditd необходимо перезапускать именно так, а не с помощью systemctl, несмотря на наличие systemd в ОС. В системном журнале будет указан не только факт блокировки, но также причина и способ преодоления запрета.

Выполняем эти команды:

]$ setsebool -P httpd_can_network_connect 1
[admin@server

]$ setsebool -P httpd_can_network_connect_db 1

Проверяем доступ на веб страницу pgadmin4-web, всё работает.

Источник

Top 10 Most Secure Linux Distros for Personal Use

Several different kinds of secure Linux distros exist, and each is developed for unique usages, including spy-level security, personal use, organizational usage, and more. So, if you want standard security and privacy, you can use the Linux distros that are best for personal use. This article will help you to choose the best Linux distro for your personal usage needs. The following sections include complete information about the top 10 most secure Linux distros available for personal use.

Linux Kodachi

Linux Kodachi is a lightweight Linux distro based on Xubuntu 18.04 and developed for running from a USB or DVD. Kodachi is one of the most secure Linux distros available for personal use, offering an anonymous, anti-forensic, and secure system to users. For even tighter security, Linux Kodachi filters all network traffic by VPN, or Virtual Proxy Network, and a Tor network to obscure your location. This Linux distro also works to remove all activity traces after you use it. Kodachi is based on the stable distribution Linux Debian, with customized features from Xfce for higher stability, security, and singularity.

Kodachi also has a support system for a protocol, DNScrypt, and utility for encrypting a request for the OpenDNS server through elliptical cryptography. As mentioned previously, Kodachi also has a browser-based system on the Tor Browser, in which you can eliminate any uncertain Tor modules.

Читайте также:  Enum all windows c

Pros and cons of Linux Kodachi

Pros Cons
Contains various pre-installed programs. Many users complain about the narrow service, as Kodachi is based on Xubuntu.
Offers a powerful security system.
Provides speedy network access.
Is highly stable.

2. Qubes OS

Qubes OS is one of the most secure Linux distros available. Many users recommend this distro for a high-level privacy system. Qubes is a security-oriented operating system (OS) that offers the compatibility to run other programs on a computer/laptop. This Linux distro works for isolating the user’s files from malicious activities and malware without affecting the data. Qubes OS provides top-notch security through compartmentalization, through which you can compartmentalize different tasks in the securely isolated compartment known as Qubes.

The Qubes operating system uses the RPM package manager to work on any desktop environment without consuming an excessive amount of resources. Most importantly, Qubes is an open-source operating system, so the source codes are easily available online. We recommend that you use Qube OS if you need advanced security, but it is a bit of an advanced operating system for new users.

Pros and Cons of Qubes OS

Pros Cons
Users can perform application separation with a sandboxed virtual machine, assuring that any malicious script or apps cannot be passed to system applications. Only recommended for advanced users.
Offers a higher level of separation through the Internet by forcing all Internet traffic via the Whonix Tor gateway. It is difficult to test Qubes OS because it does not work well in a virtual machine.

3. Whonix

Whonix is based on the Debian GNU/Linux to offer outstanding security and advanced level privacy. This distro is one of the most secure Linux distros if you want something different in your system’s security. Whonix is different because it does not have a live system rather than running on a virtual machine, particularly where it is isolated from the primary operating system to eliminate the DNS leakage risk.

There are two specific parts to Whonix. The first part is Whonix Gateway, which works as the Tor gateway. The second part is Whonix Workstation, an isolated network that works to route all connections via the Tor gateway. This Linux distro will work well if you need a private IP address for your system. As mentioned earlier, Whonix is based on Debian, so it utilizes two different VMs (virtual machines) that make it a little bit resource hungry.

Pros and Cons of Whonix

Pros Cons
Uses VirtualBox technology to ensure that many people can use this distro easily. Is somewhat resource hungry because it requires a high-end system for proper use.
Is easy to set up and use because it does not require special knowledge. Anonymity in Whonix is offered in the workstation virtual machine only, and users can forget it easily.

4. Tails (The Amnesic Incognito Live System)

Tails, or The Amnesic Incognito Live System, is a security-centric system based on Debian. It is one of the most secure Linux distros available for personal use because it was designed for protecting your identity by keeping your activities anonymous. Tails forces incoming or outgoing traffic through a Tor network and block all traceable connections. Tails was first released in 2009 for personal computers.

Tails is one of the most secure Linux distros available for personal use. It does not require any space in your hard disk, as Tails only needs space in the RAM, but it will be erased once a user shuts down the system. Hence, the default desktop environment of Tails is Gnome, and it can be used via a pen drive to save all the RAM data.

Pros and Cons of Tails

Pros Cons
Is an easy-to-use Linux distro. Must be used as the live boot OS.
You can quickly start browsing anonymously. Sometimes, users misplace the flash drive, which can create major issues.
Is packaged with a TOR Browser. TOR is a bit problematic, as it is compressed for Tails.
Offers a secured space to save passwords.

5. Kali Linux

Kali Linux is based on Debian and was created to offer an amazing penetration Linux distro for ethical hacking, security experts, digital forensics, and network security assessments. This distribution is one of the best and most secure Linux distros for personal, providing users with packages of tools like Foremost, Wireshark, Maltigo as-Aircrack-ng, Kismet, and more. These packages offer various benefits to users, such as exploiting a victim application, checking the targeted IP address, and performing a network discovery.

You can use Kali Linux via a USB stick or DVD, so this distro is quite easy to use, like the Tails distro mentioned earlier in the list. Kali Linux is compatible with both 32- and 64-bit systems. Apart from that, the basic requirements of Kali Linux are 512 MB of RAM and 10 GB of hard disk space. According to multiple surveys, developers consider Kali Linux to be one of the top-ranked and most secure Linux distros available.

Pros and Cons Kali Linux

Pros Cons
An open-source distribution that can be accessed easily. Can make the system a bit slower than usual.
Inxluswa multi-language support. Users face software-related issues.
Allows users to locate different binaries easily. Sometimes, Kali Linux corrupts the system.

6. Parrot Security OS

Parrot Security OS was developed by FrozenBox and is based on a Debian distribution. Released in 2013, this Linux distro was created for ethical hacking, working anonymously, and penetration testing. This Linux distro was specifically designed to test authorized simulated attacks on the computer system, which can be beneficial for assessing system vulnerabilities. As mentioned earlier, Parrot Security OS is an open-source and free GNU distribution made for security researchers, developers, penetration testers, privacy enthusiasts, and forensic investigators.

Читайте также:  Что такое windows multipoint mouse sdk

Parrot Security OS comes with a portable laboratory that works to protect your system from security-related issues while using the Internet, gaming, or browsing. This Linux distro is distributed as a rolling release (frequently providing updates and applications), so it offers some core applications, including Parrot Terminal, MATE, Tor Browser, and OnionShare, as its default desktop environment.

Pros and Cons Parrot Security OS

Pros Cons
Offers a large number of tools. It is not minimalistic.
The widgets are very easy to use. It has shortcut-related issues.
Does not require the GPU to run correctly.
Has a sleek UI, and things are easy to navigate.

7. BlackArch Linux

BlackArch is based on Arch Linux, and it is a lightweight Linux distro designed for penetration tester, security researchers, and computer experts. This Linux distro provides multiple features, combined with 2,000+ cybersecurity tools that users can install according to their requirements. BlackArch can be used on any hardware, as it is a lightweight Linux distro and also a new project, so many developers prefer to use this distro nowadays.

According to the reviews, this Linux distro can compete against many reliable OS due to the variety of features and tools for experts that it offers. Users can choose between different desktop environments, including Awesome, spectrwm, Fluxbox, and Blackbox. BlackArch is available in the DVD image, and you can also easily run it from a pen drive.

Pros and Cons of BlackArch Linux

Pros Cons
Offers a large repository. It is not recommended for beginners.
It is a suitable choice for professionals. Sometimes, the system becomes slower while using BlackArch.
It is better than ArchStrike.
It is based on Arch Linux.

8. IprediaOS

IprediaOS is a privacy-centered Linux distro based on Fedora. If you are looking for a platform to browse, email, and share files anonymously, then IprediaOS is a good choice for you. Along with privacy and anonymity, IprediaOS also provides stability, computing ability, and amazing speed. Compared to other Linux distros, IprediaOS is much faster, and you can run this distro smoothly even on older systems.

The Ipredia operating system is security-conscious, and it is designed with the minimalist ideology of shipping with vital applications. IprediaOS seeks to transparently encrypt and anonymize all traffic by sending it through an I2P anonymizing network. The basic features of IprediaOS include I2P Router, Anonymous BitTorrent client, Anonymous email client, Anonymous IRC client, and more.

Pros and Cons of IprediaOS

Pros Cons
Can be used on an older system. Sometimes, users face performance-related issues.
Provides anonymous email client services.
Provides anonymous email client services.

9. Discreete

Discreete Linux is based on Debian, and it was developed to offer protection from trojan-based surveillance by isolating working from a location with secured data. Discreete was formerly known as UPR (Ubuntu Privacy Remix), so it is a trusted and secure Linux distro that will protect your data. You can use this OS via CD, DVD, or USB drive, as it cannot be installed on the hard drive, and all networks are deliberately disabled when Discreete runs in the system.

Discreete is one of the unique Linux distros in terms of security, and it was developed for everyday computer activities, such as gaming or word processing. As we have mentioned above, Discreete disables the Internet connection while working to separate the data and cryptographic keys to remain protected from non-trusted networks.

Pros and Cons of Discreete

Pros Cons
It is best for everyday work. Disables the network when a user works on it.
You can use it via DVD, CD, or USB drive.

10. TENS

The full form of TENS is Trusted End Node Security. TENS was developed by the United States Department of Defense’s Air Force Research Laboratory. This Linux distro does not need administrator privileges for running without installation and storing it in the hard drive. TENS consists of an Xfce desktop, and it is customized to look like a Windows XP desktop. Everything about the appearance of TENS is similar to Windows, including the application names and placements.

This Linux distro is available in two editions. The first edition of TENS is a Deluxe edition that includes various applications, like LibreOffice, Evince PDF reader, Totem Movie Player, Thunderbird, and so on. The other edition of TENS is the regular edition that includes an encryption app and some other useful apps.

Pros and Cons of TENS

Pros Cons
Offers great security and privacy. The look of TENS
Provides two different editions for users. Exhibits performance-related issues.

Conclusion

This article provided a list of the top ten most secure Linux distros for personal use. All the distros discussed in this article offer amazing features and anonymity to the user. We have included these Linux distros according to user reviews and features, but the list position of each distribution is completely random. Privacy, security, and anonymity are important for performing specific computer-related tasks, and any of these Linux distros would be a great choice for keeping your information safe from malicious threats.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

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