3.6. Настройки безопасности #
3.6.1. Настройка пользователя операционной системы #
Для работы pgpro-otel-collector достаточно прав непривилегированного пользователя. Однако в некоторых случаях для сбора журналов экземпляра СУБД может потребоваться доступ на чтение к каталогу журналов и файлам журналов со стороны операционной системы.
3.6.1.1. Настройка доступа для чтения журналов СУБД #
Для чтения журналов достаточно использовать группу, от имени которой запущен экземпляр СУБД. Для этого группе нужно выдать доступ на чтение файлов журнала и затем в эту же группу поместить пользователя, от имени которого запущен коллектор. Как правило, это группа postgres.
Добавьте права на чтение для группы (путь к каталогу может отличаться):
sudo chmod g+rx /var/log/postgresql/ sudo chmod g+r /var/log/postgresql/*
Добавьте пользователя
otelcolв группуpostgres:sudo usermod --groups=postgres otelcol
Теперь коллектор может читать существующие файлы журналов.
Дополнительно требуется настроить конфигурацию экземпляра СУБД таким образом, чтобы новые файлы журналов создавались с нужными правами доступа. Это достигается путём изменения параметра log_file_mode и перезагрузки конфигурации. Параметр можно изменить напрямую через файл конфигурации, с помощью ALTER SYSTEM или используя средства автоматизации и IaC (Infrastructure as Code, инфраструктура как код).
В примере ниже изменение выполняется через подключение к экземпляру СУБД и использование ALTER SYSTEM.
psql -U postgres -c 'ALTER SYSTEM SET log_file_mode TO "0640"' psql -U postgres -c 'SELECT pg_reload_conf()'
3.6.2. Настройка пользователя экземпляра СУБД #
Настройка пользователя СУБД включает следующие шаги:
Создание и настройка привилегий пользователя СУБД, от имени которого коллектор будет подключаться к экземпляру СУБД.
Настройка HBA-правил авторизации, которые будут разрешать коллектору подключаться к экземпляру СУБД.
Настройка дополнительных прав на запуск функций; шаг является необязательным и требуется только если вы действительно хотите включить сбор соответствующих данных.
3.6.2.1. Создание и настройка пользователя #
Задайте пароль при создании пользователя:
sudo -u postgres createuser --pwprompt otelcol
Для настройки прав подключитесь к экземпляру СУБД и выполните следующую команду:
GRANT pg_monitor TO otelcol;
3.6.2.2. Настройка правил HBA #
При использовании плагинов, требующих подключения к другим БД (сбор таблиц, индексов, раздувания), правила HBA (Host-Based Authentication, аутентификация на основе хоста) необходимо согласовать с правилами коллектора:
Базы данных, перечисленные в настройках плагина, должны быть разрешены в конфигурации HBA.
Если коллектор настроен на сбор данных со всех БД, то и правила HBA должны разрешать подключение ко всем БД.
СУБД PostgreSQL поддерживает большое количество методов аутентификации. При настройке правил HBA следует ориентироваться на метод, используемый в вашем случае.
Пример настройки доступа к БД postgres с помощью метода scram-sha-256:
vi pg_hba.conf local postgres otelcol scram-sha-256 host postgres otelcol 127.0.0.1/32 scram-sha-256
В этом примере возможности подключения ограничены только одной базой postgres. В случае, когда коллектор настроен на сбор данных с других БД, в конфигурацию HBA необходимо внести соответствующие разрешающие правила.
После внесения изменений перезагрузите конфигурацию экземпляра СУБД:
sudo -u postgres psql -c 'SELECT pg_reload_conf()'
3.6.2.3. Настройка дополнительных прав #
Различные типы собираемых данных требуют доступа к различным внутренним функциям системы. Доступ к этим функциям ограничен для обычных пользователей, так как они могут раскрывать конфиденциальную информацию. Поэтому предоставление доступа должно согласовываться с политиками безопасности компании.
За информацией о правах доступа, необходимых для бесперебойной работы, обратитесь к Подразделу 1.3.1.
3.6.3. Настройка коллектора #
3.6.3.1. Подключение к экземпляру СУБД #
Параметры подключения к экземпляру СУБД регулируются в конфигурации ресивера postgrespro файла конфигурации коллектора. Учётные данные пользователя должны быть указаны в параметрах endpoint, database, username и password (пароль можно передать через переменную окружения):
receivers:
postgrespro:
transport: tcp
endpoint: localhost:5432
database: postgres
username: otelcol
password: ${env:POSTGRESQL_PASSWORD}3.6.4. Настройка TLS #
TLS (Transport Layer Security, протокол защиты транспортного уровня) — это протокол, который преобразует данные, передаваемые между системами, обеспечивая конфиденциальность и целостность. По умолчанию TLS включён с проверкой сертификата сервера с использованием системных корневых центров сертификации (CA). Для стандартного TLS дополнительная настройка не требуется. В этом разделе описывается взаимный TLS (mTLS), при котором и клиент, и сервер предоставляют сертификаты — он является необязательным и требует дополнительной настройки.
Пример конфигурации TLS для экспортёра otlp_http:
exporters:
otlp_http:
endpoint: "https://ppem.example.org"
tls:
insecure: false
insecure_skip_verify: false
ca_file: server.crt
cert_file: client.crt
key_file: client.key
min_version: "1.3"
max_version: "1.3"Предупреждение
Параметр
insecureполностью отключает защиту транспортного уровня. По умолчанию он отключён (false), и настоятельно рекомендуется оставлять его отключённым и использовать mTLS; в противном случае метрики будут передаваться по незащищённому TCP.Параметр
insecure_skip_verifyотключает проверку сертификатов. Рекомендуется использовать этот параметр только в тестовых средах и средах разработки — не используйте его в производственной среде.insecureиinsecure_skip_verifyявляются взаимоисключающими.
ca_fileуказывает путь к TLS-сертификату, который клиент использует для проверки сертификата сервера. Если параметр опущен, используются системные корневые центры сертификации. Этот параметр обязателен для самоподписанных сертификатов.Примечание
Для ресиверов и экспортёра
prometheusиспользуйте параметрclient_ca_filecert_fileуказывает путь к TLS-сертификату. Для сервера этот параметр обязателен для работы TLS. Для клиента он требуется только при использовании mTLS. По умолчанию:$HOME/.postgresql/postgresql.crt.key_fileуказывает путь к закрытому ключу TLS. Этот параметр должен указываться вместе сcert_file. По умолчанию:$HOME/.postgresql/postgresql.key.min_versionопределяет минимальную допустимую версию TLS. По умолчанию:"1.2".max_versionуказывает максимальную допустимую версию TLS. По умолчанию:""— используется последняя поддерживаемая версия; в настоящее время это 1.3.
За полным списком параметров конфигурации TLS обратитесь к документации OpenTelemetry.
3.6.5. Настройка списков разрешений и запретов #
Списки разрешений и запретов обеспечивают гибкое управление сбором метрик из отдельных баз данных и объектов. Это особенно полезно в случаях, когда в соответствии с политиками безопасности требуется ограничить доступ к одним базам данных, а к другим разрешить.
Глобальные списки разрешений и запретов можно настроить для плагинов на уровне ресивера. Ниже приведён общий пример такой конфигурации:
receivers:
postgrespro:
acl:
databases:
allow:
- name: postgres
schemas:
- name: public
tables:
- name: table
- name: table_index
indexes:
- name: index1
- name: index2
functions:
- name: function1
deny:
- name: db
schemas:
- name: schema
tables:
- name: tableЗдесь:
Раздел
acl.allowопределяет, из каких баз данных (и вложенных объектов) плагины будут собирать данные по умолчанию.Раздел
acl.denyопределяет, из каких баз данных и объектов pgpro-otel-collector запрещается сбор метрик.
Рассмотрим конкретный пример, как сделать так, чтобы данные не собирались из базы zabbix:
receivers:
postgrespro:
max_threads: 3
collection_interval: 60s
initial_delay: 1s
transport: tcp
endpoint: localhost:5432
database: postgres
username: postgres
password: ${env:POSTGRESQL_PASSWORD}
metrics: null
acl:
databases:
allow:
- name: postgres
deny:
- name: zabbix
plugins:
activity:
enabled: true
bgwriter:
enabled: true
locks:
enabled: true
version:
enabled: true
wal:
enabled: true
cache:
enabled: trueВ этом примере метрики собираются из базы данных postgres по умолчанию, а сбор из базы данных zabbix запрещён вне зависимости от других настроек.
У отдельных плагинов может быть свой раздел настройки databases:
tables:
enabled: true
databases:
- name: demoВ этом случае игнорируется раздел acl.allow, но ограничения из раздела acl.deny действуют.
3.6.5.1. Использование регулярных выражений в ACL #
pgpro-otel-collector поддерживает регулярные выражения в конфигурации ACL (Access Control List, список контроля доступа) как для списков разрешений, так и запретов. Регулярные выражения избавляют от необходимости вручную обновлять конфигурации ACL при создании новых объектов базы данных. Вместо перечисления отдельных объектов можно задать шаблоны, которые автоматически добавляют или исключают объекты на основе их имён. Пример такого регулярного выражения приведён ниже.
receivers:
postgrespro:
transport: tcp
endpoint: &endpoint localhost:5432
database: postgres
username: postgres
password: ${env:POSTGRESQL_PASSWORD}
collection_interval: 60s
initial_delay: 1s
max_threads: 3
plugins:
databases:
allow:
- name: db1.*
schemas:
- name: sch1.*
tables:
- name: tb1.*
- name: tb2.*
indexes:
- name: idx2.*
activity:
enabled: true
tables:
enabled: true
indexes:
enabled: true
# Списки разрешений можно настраивать для отдельного плагина
# databases:
# - name: db1.*
# schemas:
# - name: sch1.*
# tables:
# - name: tb1.*
# - name: tb2.*
# indexes:
# - name: idx2.*
functions:
enabled: true
bloat_tables:
enabled: true
bloat_indexes:
enabled: true3.6.6. Базовый аутентификатор #
Расширение basicauth — компонент OpenTelemetry Collector с открытым исходным кодом, который реализует базовую HTTP-аутентификацию.
Ниже приведён пример процедуры включения базовой аутентификации для экспортёра prometheus.
Создайте файл конфигурации (например,
auth_basic.yml) со следующим содержимым:extensions: basicauth/prometheus: htpasswd: # Путь к файлу htpasswd # file: .htpasswd # # Встроенное содержимое файла htpasswd inline: | ${env:BASIC_AUTH_USERNAME}:${env:BASIC_AUTH_PASSWORD} exporters: prometheus: endpoint: :8889 send_timestamps: true # Конфигурация TLS для конечной точки HTTP Prometheus. # При настройке экспортёр будет использовать HTTPS вместо HTTP. # tls: # cert_file: /etc/pgpro-otel-collector/cert.d/server.crt # key_file: /etc/pgpro-otel-collector/cert.d/server.key # client_ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt # mTLS # min_version: "1.3" auth: authenticator: basicauth/prometheus service: extensions: [ basicauth/prometheus ]Необходимо указать либо
htpasswd.file, либоhtpasswd.inline. Если заданы оба, приоритет отдаётся учётным данным изhtpasswd.inline.За подробной информацией о параметрах конфигурации TLS обратитесь к Подразделу 3.6.4.
Запустите коллектор, указав основной файл конфигурации и файл аутентификации:
BASIC_AUTH_USERNAME=username BASIC_AUTH_PASSWORD=password build/pgpro-otel-collector/pgpro-otel-collector --config configs/basic.yml --config configs/auth_basic.yml
Проверьте, отклоняется ли запрос без аутентификации:
$ curl 127.0.0.1:8889/metrics # Должна вернуться ошибка «no basic auth provided» (базовая аутентификация не предоставлена)
Убедитесь, что при верных учётных данных запрос возвращает метрики:
$ curl -u username:password 127.0.0.1:8889/metrics # Должны возвращаться метрики в формате Prometheus
3.6. Security Setup #
3.6.1. Setting up an Operating System User #
pgpro-otel-collector can be run by an unprivileged user. In some cases, however, read access to the log directory and log files may be required on the operating system side for collecting logs from the DBMS instance.
3.6.1.1. Setting up Read Access to DBMS Logs #
To read the logs, it is sufficient to use the group under which the DBMS instance is running. To do this, the group needs to be granted read access to log files, and then the user under which the collector is running should be added to the same group. Typically, this is the postgres group.
Grant read permissions to the group (the directory path may vary):
sudo chmod g+rx /var/log/postgresql/ sudo chmod g+r /var/log/postgresql/*
Add the user
otelcolto the grouppostgres:sudo usermod --groups=postgres otelcol
Now the collector should be able to read the existing log files.
Additionally, it is necessary to adjust the DBMS instance configuration so that new log files are created with the required access permissions. This is achieved by modifying the log_file_mode parameter and reloading the configuration. The parameter can be updated either directly in the configuration file, via ALTER SYSTEM, or through automation tools and IaC (Infrastructure as Code) solutions.
In the example below, the change is made by connecting to the DBMS instance and using ALTER SYSTEM:
psql -U postgres -c 'ALTER SYSTEM SET log_file_mode TO "0640"' psql -U postgres -c 'SELECT pg_reload_conf()'
3.6.2. Setting up a DBMS Instance User #
The DBMS user setup consists of the following steps:
Creating and configuring the privileges of the DBMS user under which the collector connects to the DBMS instance.
Setting up HBA authorization rules that will allow the collector to connect to the DBMS instance.
Configuring additional privileges for function execution; this step is optional and is only required if you actually want to enable the collection of the corresponding data.
3.6.2.1. Creating and Setting up a User #
Set a password when creating a user:
sudo -u postgres createuser --pwprompt otelcol
To set up permissions, connect to the DBMS instance and run the following commands:
GRANT pg_monitor TO otelcol;
3.6.2.2. Setting up the HBA Rules #
When using plugins that require connections to other databases (such as collecting tables, indexes, or bloat), the HBA (Host-Based Authentication) rules must be aligned with the collector rules:
The databases listed in the plugin configuration must be allowed in the HBA configuration.
If the collector is configured to collect data from all databases, then HBA rules should allow connection to all of them.
PostgreSQL DBMS supports a wide variety of authentication methods. When setting up HBA rules, focus on the method that is used in your case.
The example below shows how to set up access to the database postgres using the scram-sha-256 method.
vi pg_hba.conf local postgres otelcol scram-sha-256 host postgres otelcol 127.0.0.1/32 scram-sha-256
In this example, the connection capability is limited to only the postgres database; if the collector is configured to collect data from other databases, the corresponding allowing rules must be added to the HBA configuration.
Reload the DBMS instance configuration for the changes to take effect:
sudo -u postgres psql -c 'SELECT pg_reload_conf()'
3.6.2.3. Setting up Additional Privileges #
Different types of collected data require access to various internal functions. Access to these functions is restricted for general users, as they can reveal confidential information. Therefore, granting access should be coordinated with the company's security policies.
See Section 1.3.1 for information about the access privileges required for seamless operation.
3.6.3. Setting up the Collector #
3.6.3.1. Connecting to a DBMS Instance #
The connection parameters for the DBMS instance are managed in the postgrespro receiver configuration of the collector configuration file. The user credentials should be specified in the endpoint, database, username, and password parameters (it is possible to pass the password through an environment variable):
receivers:
postgrespro:
transport: tcp
endpoint: localhost:5432
database: postgres
username: otelcol
password: ${env:POSTGRESQL_PASSWORD}
3.6.4. Configuring TLS #
TLS (Transport Layer Security) is a protocol that encrypts data transmitted between systems, ensuring confidentiality and integrity. By default, TLS is enabled with server certificate verification using the system root CAs. No additional configuration is needed for standard TLS. This section describes mutual TLS (mTLS), where both client and server present certificates — it is optional and requires additional configuration.
An example of TLS configuration for the otlp_http exporter:
exporters:
otlp_http:
endpoint: "https://ppem.example.org"
tls:
insecure: false
insecure_skip_verify: false
ca_file: server.crt
cert_file: client.crt
key_file: client.key
min_version: "1.3"
max_version: "1.3"
Warning
insecuredisables transport security entirely. It is disabled by default (false), and it is strongly recommended to keep it disabled and use mTLS instead; otherwise, metrics will be sent over plain TCP.insecure_skip_verifydisables certificate verification and should only be used in testing and development environments. Do not use it in production.insecureandinsecure_skip_verifyare mutually exclusive.
ca_filespecifies the path to the TLS certificate to use by the client to verify the server certificate. If omitted, the system root CAs are used. This parameter is required for self-signed certificates.Note
For receivers and the
prometheusexporter, use theclient_ca_fileparameter instead to specify the path to the TLS certificate used by the server to verify the client certificate.cert_filespecifies the path to the TLS certificate. For a server, this is required to serve TLS. For a client, this is only needed for mTLS. Default:$HOME/.postgresql/postgresql.crt.key_filespecifies the path to the TLS private key. Must be provided alongsidecert_file. Default:$HOME/.postgresql/postgresql.key.min_versionspecifies the minimum acceptable TLS version. Default:"1.2".max_versionspecifies the maximum acceptable TLS version. Default:""— the latest supported version is used, which is currently 1.3.
For the full list of TLS configuration parameters, refer to the OpenTelemetry documentation.
3.6.5. Setting up Allowlists and Denylists #
Allowlists and denylists provide granular control over metrics collection from specific databases and objects. This is particularly useful when security policies mandate restricting access to certain databases while allowing collection from others.
Global allowlists and denylists can be configured for plugins at the receiver level. Here is a general example of such configuration:
receivers:
postgrespro:
acl:
databases:
allow:
- name: postgres
schemas:
- name: public
tables:
- name: table
- name: table_index
indexes:
- name: index1
- name: index2
functions:
- name: function1
deny:
- name: db
schemas:
- name: schema
tables:
- name: table
Where:
The
acl.allowsection defines which databases (and their nested objects) are collected by plugins by default.The
acl.denysection specifies databases and objects from which pgpro-otel-collector is prohibited from collecting metrics.
Let's consider a specific example of excluding the zabbix database from data collection:
receivers:
postgrespro:
max_threads: 3
collection_interval: 60s
initial_delay: 1s
transport: tcp
endpoint: localhost:5432
database: postgres
username: postgres
password: ${env:POSTGRESQL_PASSWORD}
metrics: null
acl:
databases:
allow:
- name: postgres
deny:
- name: zabbix
plugins:
activity:
enabled: true
bgwriter:
enabled: true
locks:
enabled: true
version:
enabled: true
wal:
enabled: true
cache:
enabled: true
In this example, metrics are collected from the postgres database by default, while collection from the zabbix database is prohibited regardless of other settings.
Individual plugins can have their own databases configuration section:
tables:
enabled: true
databases:
- name: demo
In this case, plugins override acl.allow but still adhere to the acl.deny restrictions.
3.6.5.1. Using Regular Expressions with ACL #
pgpro-otel-collector supports regular expressions in ACL (Access Control List) configuration for both allowlists and denylists. Regular expressions eliminate the need to manually update ACL configurations when new database objects are created. Instead of listing individual objects, you can define patterns that automatically include or exclude objects based on their names. An example of such a regular expression is shown below.
receivers:
postgrespro:
transport: tcp
endpoint: &endpoint localhost:5432
database: postgres
username: postgres
password: ${env:POSTGRESQL_PASSWORD}
collection_interval: 60s
initial_delay: 1s
max_threads: 3
plugins:
databases:
allow:
- name: db1.*
schemas:
- name: sch1.*
tables:
- name: tb1.*
- name: tb2.*
indexes:
- name: idx2.*
activity:
enabled: true
tables:
enabled: true
indexes:
enabled: true
# Allowlists can be set up for a specific plugin
# databases:
# - name: db1.*
# schemas:
# - name: sch1.*
# tables:
# - name: tb1.*
# - name: tb2.*
# indexes:
# - name: idx2.*
functions:
enabled: true
bloat_tables:
enabled: true
bloat_indexes:
enabled: true
3.6.6. Basic Authenticator #
The basicauth extension is an open-source component of the OpenTelemetry Collector that implements basic HTTP authentication.
Below is the example procedure of enabling basic authentication for the prometheus exporter.
Create a configuration file (for example,
auth_basic.yml) with the following content:extensions: basicauth/prometheus: htpasswd: # The path to the htpasswd file # file: .htpasswd # # The htpasswd file inline content inline: | ${env:BASIC_AUTH_USERNAME}:${env:BASIC_AUTH_PASSWORD} exporters: prometheus: endpoint: :8889 send_timestamps: true # TLS configuration for the Prometheus HTTP endpoint. # When configured, the exporter will serve HTTPS instead of HTTP. # tls: # cert_file: /etc/pgpro-otel-collector/cert.d/server.crt # key_file: /etc/pgpro-otel-collector/cert.d/server.key # client_ca_file: /etc/pgpro-otel-collector/cert.d/ca.crt # mTLS # min_version: "1.3" auth: authenticator: basicauth/prometheus service: extensions: [ basicauth/prometheus ]You must either set
htpasswd.fileorhtpasswd.inline. If both are configured, thehtpasswd.inlinecredentials take precedence.For more details on TLS configuration parameters, refer to Section 3.6.4.
Start the collector, providing both the main configuration file and the authentication file:
BASIC_AUTH_USERNAME=username BASIC_AUTH_PASSWORD=password build/pgpro-otel-collector/pgpro-otel-collector --config configs/basic.yml --config configs/auth_basic.yml
Check whether a request without authentication is rejected:
$ curl 127.0.0.1:8889/metrics # Should return an error "no basic auth provided"
Check whether a request with valid credentials returns metrics:
$ curl -u username:password 127.0.0.1:8889/metrics # Should return Prometheus metrics