Наилучшие практики для безопасной установки Zabbix

Обзор

В этом разделе содержатся рекомендации, которые следует соблюдать для того, чтобы настроить Zabbix безопасным образом.

Практики, описанные здесь, не требуются для работы Zabbix. Они рекомендуются для повышения безопасности системы.

Access control

Principle of least privilege

The principle of least privilege should be used at all times for Zabbix. This principle means that user accounts (in Zabbix frontend) or process user (for Zabbix server/proxy or agent) have only those privileges that are essential to perform intended functions. In other words, user accounts at all times should run with as few privileges as possible.

Giving extra permissions to 'zabbix' user will allow it to access configuration files and execute operations that can compromise the overall security of the infrastructure.

When implementing the least privilege principle for user accounts, Zabbix frontend user types should be taken into account. It is important to understand that while a "Admin" user type has less privileges than "Super Admin" user type, it has administrative permissions that allow managing configuration and execute custom scripts.

Some information is available even for non-privileged users. For example, while AdministrationScripts is not available for non-Super Admins, scripts themselves are available for retrieval by using Zabbix API. Limiting script permissions and not adding sensitive information (like access credentials, etc) should be used to avoid exposure of sensitive information available in global scripts.

Защищённый пользователь для Zabbix агента

В конфигурации по умолчанию процессы Zabbix сервера и Zabbix агента делят одного 'zabbix' пользователя. Если вы хотите убедиться, что агент не сможет получить доступ к конфиденциальной информации из конфигурации сервера (например, данные подключения в базе данных), агента необходимо запускать из под другого пользователя:

  1. Создайте защищённого пользователя
  2. Укажите этого пользователя в файле конфигурации агента (параметр 'User')
  3. Перезапустите агента с правами администратора. Привилегии администратора сбросятся на указанного пользователя.

UTF-8 кодировка

UTF-8 является единственной кодировкой, которая поддерживается Zabbix. Она, как известно, работает без каких-либо проблем с безопасностью. Пользователи должны знать, что существуют известные проблемы с безопасностью при использовании некоторых других кодировок.

Zabbix Security Advisories and CVE database

See Zabbix Security Advisories and CVE database.

Настройка SSL для Zabbix веб-интерфейса

На RHEL/Centos, установите пакет mod_ssl:

yum install mod_ssl

Создайте папку для SSL ключей:

mkdir -p /etc/httpd/ssl/private
       chmod 700 /etc/httpd/ssl/private

Создайте SSL сертификат:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/httpd/ssl/private/apache-selfsigned.key -out /etc/httpd/ssl/apache-selfsigned.crt

Заполните подсказки соответствующим образом. Самая важная строка здесь, которая запрашивает Common Name. Вам необходимо указать имя домена, которое вы хотите связать с вашим сервером. Вместо него вы можете указать публичный IP адрес, если у вас отсутствует имя домена. В этой статье мы будем использовать example.com.

Country Name (2 letter code) [XX]:
       State or Province Name (full name) []:
       Locality Name (eg, city) [Default City]:
       Organization Name (eg, company) [Default Company Ltd]:
       Organizational Unit Name (eg, section) []:
       Common Name (eg, your name or your server's hostname) []:example.com
       Email Address []:

Измените конфигурацию Apache SSL:

/etc/httpd/conf.d/ssl.conf
       
       DocumentRoot "/usr/share/zabbix"
       ServerName example.com:443
       SSLCertificateFile /etc/httpd/ssl/apache-selfsigned.crt
       SSLCertificateKeyFile /etc/httpd/ssl/private/apache-selfsigned.key

Перезапустите сервис Apache, чтобы применить изменения:

systemctl restart httpd.service

Web server hardening

Включение Zabbix в корневом каталоге URL

Добавьте виртуальный хост в конфигурацию Apache и задайте постоянную переадресацию для корневого каналога на Zabbix SSL URL. Не забудьте заменить example.com на актуальное имя сервера.

/etc/httpd/conf/httpd.conf
       
       #Добавьте строки
       
       <VirtualHost *:*>
           ServerName example.com
           Redirect permanent / http://example.com
       </VirtualHost>

Перезапустите сервис Apache, чтобы применить изменения:

systemctl restart httpd.service

Enabling HTTP Strict Transport Security (HSTS) on the web server

HSTS is enforced by Zabbix frontend in versions 4.0.0 - 4.0.2.

Starting with 4.0.3 to protect Zabbix frontend against protocol downgrade attacks, we recommend to enable HSTS policy on the web server.

For example, to enable HSTS policy for your Zabbix frontend in Apache configuration:

/etc/httpd/conf/httpd.conf

add the following directive to your virtual host's configuration:

<VirtualHost *:443>
          Header set Strict-Transport-Security "max-age=31536000"
       </VirtualHost>

Restart the Apache service to apply the changes:

systemctl restart httpd.service

Отключение отображения информации о веб-сервере

Рекомендуется отключить все подписи веб-сервера, как часть процесса по улучшению защищенности веб-сервера. По умолчанию веб-сервер раскрывает подпись программного обеспечения:

Эту подпись можно отключить, добавив две строки в файл конфигурации Apache (используется как пример):

ServerSignature Off
       ServerTokens Prod

Подпись PHP (Заголовок X-Powered-By HTTP) можно отключить, изменив файл конфигурации php.ini (подпись отключена по умолчанию):

expose_php = Off

Чтобы изменения файлов конфигурации вступили в силу, необходимо перезапустить веб-сервер.

Дополнительный уровень безопасности можно достичь, используя mod_security (пакет libapache2-mod-security2) с Apache. mod_security позволяет совсем удалить подпись сервера вместо удаления лишь версии из подписи сервера. Подпись можно изменить на любое значение, исправив "SecServerSignature" на любое желаемое значение, после установки mod_security.

Пожалуйста, обратитесь к документации по вашему веб-серверу для того, чтобы узнать как удалять/изменять подписи к программному обеспечанию.

Отключение страниц ошибок по умолчанию веб-сервера

Рекомендуется отключить страницы ошибок по умолчанию, чтобы избежать раскрытия информации. По умолчанию веб-сервер использует встроенные страницы ошибок:

Страницы ошибок по умолчанию необходимо заменить/удалить, как часть процесса по улучшению защищенности веб-сервера. Можно использовать директиву "ErrorDocument", чтобы задать пользовательскую страницу/текст веб-серверу Apache (используется как пример).

Пожалуйста, обратитесь к документации по вашему веб-серверу для того, чтобы узнать как заменять/удалять страницы ошибок по умолчанию.

Удаление тестовой страницы с веб-сервера

Рекомендуется удалить тестовую страницу веб-сервера, чтобы избежать раскрытия информации. По умолчанию, корневой каталог веб-сервера содержит тестовую страницу с именем index.html (Apache2 на Ubuntu используется как пример):

Тестовую страницу необходимо удалить или сделать недоступной, как часть процесса по улучшению защищенности веб-сервера.

Set X-Frame-Options HTTP response header

By default, Zabbix is configured with X-Frame-Options HTTP response header set to SAMEORIGIN, meaning that content can only be loaded in a frame that has the same origin as the page itself.

Zabbix frontend elements that pull content from external URLs (namely, the URL dashboard widget) display retrieved content in a sandbox with all sandboxing restrictions enabled.

These settings enhance the security of the Zabbix frontend and provide protection against XSS and clickjacking attacks. Super Admins can modify iframe sandboxing and X-Frame-Options HTTP response header parameters as needed. Please carefully weigh the risks and benefits before changing default settings. Turning sandboxing or X-Frame-Options off completely is not recommended.

Hiding the file with list of common passwords

To increase the complexity of password brute force attacks, it is suggested to limit access to the file ui/data/top_passwords.txt by modifying web server configuration. This file contains a list of the most common and context-specific passwords, and is used to prevent users from setting such passwords if Avoid easy-to-guess passwords parameter is enabled in the password policy.

For example, on NGINX file access can be limited by using the location directive:

location = /data/top_passwords.txt {​​​​​​​
           deny all;
           return 404;
       }​​​​​​​

On Apache - by using .htacess file:

<Files "top_passwords.txt">  
         Order Allow,Deny
         Deny from all
       </Files>

Displaying URL content in the sandbox

Since version 4.0.22, some Zabbix frontend elements (for example, the URL widget) are preconfigured to sandbox content retrieved from the URL. It is recommended to keep all sandboxing restrictions enabled to ensure protection against XSS attacks.

Zabbix Windows agent with OpenSSL

Zabbix Windows agent compiled with OpenSSL will try to reach the SSL configuration file in c:\openssl-64bit. The "openssl-64bit" directory on disk C: can be created by non-privileged users.

So for security hardening, it is required to create this directory manually and revoke write access from non-admin users.

Please note that the directory names will be different on 32-bit and 64-bit versions of Windows.

Cryptography