Это перевод страницы документации с английского языка. Помогите нам сделать его лучше.

12. Ограничение проверок агента

Обзор

Можно ограничить проверки на стороне агента, создав чёрный список элементов данных, белый список или комбинацию белого/чёрного списков.

Для этого используйте комбинацию из двух параметров конфигурации агента:

  • AllowKey=<шаблон> — какие проверки разрешены; <шаблон> указывается с использованием выражения с подстановочным знаком (*)
  • DenyKey=<шаблон> — какие проверки запрещены; <шаблон> указывается с использованием выражения с подстановочным знаком (*)

Обратите внимание, что:

  • Все элементы данных system.run[*] (удалённые команды, скрипты) по умолчанию отключены, даже если не указаны запрещающие ключи; должно предполагаться, что неявно добавлено DenyKey=system.run[*].
  • Начиная с Zabbix 5.0.2, параметр агента EnableRemoteCommands:
  • считается устаревшим для Zabbix агента
  • не поддерживается Zabbix агентом 2

Поэтому, чтобы разрешить удалённые команды, укажите AllowKey=system.run[<команда>,*] по каждой разрешенной команде, * заменяет режимы wait и nowait. Также можно указать параметр AllowKey=system.run[*], чтобы разрешить все команды с режимами wait и nowait. Чтобы запретить определённые удалённые команды, добавьте параметры DenyKey с командами system.run[] до параметра AllowKey=system.run[*].

Важные правила

  • Белый список без запрещающего правила разрешён только для элементов данных system.run[*]. Для всех остальных элементов данных параметры AllowKey не допускаются без параметра DenyKey; в таком случае (при наличии только параметров AllowKey) Zabbix агент не запустится.
  • Порядок имеет значение. Указанные параметры проверяются по очереди в соответствии с порядком их появления в файле конфигурации:
    • Как только ключ элемента данных соответствует разрешающему/запрещающему правилу, элемент данных разрешается или запрещается; а проверка правил прекращается. Таким образом, если элемент данных соответствует и разрешающему правилу, и запрещающему правилу, результат будет зависеть от того, какое правило будет первым.
    • Порядок влияет также на параметр EnableRemoteCommands (если используется).
  • Поддерживается неограниченное количество параметров AllowKey/DenyKey.
  • Правила AllowKey, DenyKey не влияют на параметры конфигурации HostnameItem, HostMetadataItem, HostInterfaceItem.
  • Шаблон ключа — это выражение с подстановочным знаком, в котором подстановочный знак (*) соответствует любому количеству любых символов в определённой позиции. Его можно использовать как в имени ключа, так и в параметрах.
  • Если конкретный ключ элемента данных запрещён в конфигурации агента, элемент данных будет отмечен как неподдерживаемый (без указания причины);
  • Агент Zabbix с параметром командной строки --print (-p) не будет показывать ключи, которые не разрешены настройками;
  • Агент Zabbix с параметром командной строки --test (-t) вернёт состояние «Unsupported item key.» (Неподдерживаемый ключ элемента данных) для ключей, которые не разрешены настройками;
  • Отклонённые удалённые команды не записываются в журнал агента (если LogRemoteCommands = 1).

Allow/deny rule order

You can specify an unlimited number of AllowKey or DenyKey rules, though their order matters.

  • Rules are evaluated one by one, from top to bottom.
  • When an item key matches a rule, it is either allowed or denied, and rule evaluation stops.

For example, when evaluating vfs.file.contents[/etc/passwd], the rules are processed as follows:

AllowKey=vfs.file.contents[/tmp/app.log]    # Item key pattern does not match, agent proceeds to the next rule.
       AllowKey=vfs.file.contents[/etc/passwd]     # Item key pattern matches; agent allows the item check and stops rule evaluation.
       DenyKey=vfs.file.*[*]                       # Agent ignores the rule, as the evaluation has stopped.

The following rule order will deny the item check:

DenyKey=vfs.file.*[*]                       # Item key pattern matches; agent denies the item check and stops rule evaluation.
       AllowKey=vfs.file.contents[/etc/passwd]     # Agent ignores the rule, as the evaluation has stopped.
       AllowKey=vfs.file.contents[/tmp/app.log]    # Agent ignores the rule, as the evaluation has stopped.

Примеры использования

Allowing specific checks and commands

Allow only two vfs.file item checks and two system.run commands:

AllowKey=vfs.file.contents[/tmp/app.log]
       AllowKey=vfs.file.size[/tmp/app.log]
       AllowKey=system.run[/usr/bin/uptime]
       AllowKey=system.run[/usr/bin/df -h /]
       DenyKey=vfs.file.*[*]

Setting DenyKey=system.run[*] is unnecessary, because all other system.run commands are denied by default.

Allowing scripts

Allow Zabbix agent to execute scripts on hosts via all available methods:

  • Global scripts that can be executed in the frontend or via API (this method always uses the system.run[myscript.sh] key)
  • Remote commands from action operations (this method always uses the system.run[myscript.sh,nowait] key)
  • system.run Zabbix agent items with the script, for example:
    • system.run[myscript.sh]
    • system.run[myscript.sh,wait]
    • system.run[myscript.sh,nowait]
AllowKey=system.run[myscript.sh,*]

To control the wait/nowait parameter, you must set a different rule. For example, you can allow only system.run[myscript.sh,wait] items, thus excluding other methods:

AllowKey=system.run[myscript.sh,wait]
Securing allow/deny rules

This example shows how to secure overly permissive AllowKey or DenyKey rules.

Consider the following rules:

AllowKey=system.run["C:\Program^ Files\Zabbix^ Agent^ 2\scripts\test.bat*"]
       DenyKey=vfs.file.*
       DenyKey=system.cpu.load[*]

On Windows, you must escape spaces in the path using a caret (^).

These rules contain a wildcard (*), which can be misused:

  • The test.bat script can be executed with any arguments, including unintended ones.
  • The vfs.file.* pattern matches only item keys without parameters; however, all vfs.file items require parameters.
  • The system.cpu.load[*] pattern matches only item keys with parameters; however system.cpu.load items do not require parameters.

To secure these rules, explicitly allow executing test.bat only with specific arguments, and deny correct item key patterns; for example:

AllowKey=system.run["C:\Program^ Files\Zabbix^ Agent^ 2\scripts\test.bat status"]
       AllowKey=system.run["C:\Program^ Files\Zabbix^ Agent^ 2\scripts\test.bat version"]
       DenyKey=vfs.file.*[*]
       DenyKey=system.cpu.load
       DenyKey=system.cpu.load[*]

You can test the rules by running the following commands, which will return ZBX_NOTSUPPORTED.

cd "C:\Program Files\Zabbix Agent 2"
       zabbix_agent2.exe -t system.run["C:\Program^ Files\Zabbix^ Agent^ 2\scripts\test.bat debug"]
       zabbix_agent2.exe -t vfs.file.size["C:\ProgramData\MyApp\config.ini"]
       zabbix_agent2.exe -t vfs.file.contents["C:\Windows\System32\drivers\etc\hosts"]
       zabbix_agent2.exe -t system.cpu.load
       zabbix_agent2.exe -t system.cpu.load[all,avg1]

Примеры шаблонов

Шаблон Описание Соответствует Не соответствует
* Соответствует всем возможным ключам с параметрами или без них. Любой Нет
vfs.file.contents Соответствие vfs.file.contents без параметров. vfs.file.contents vfs.file.contents[/etc/passwd]
vfs.file.contents[] Соответствие vfs.file.contents с пустыми параметрами. vfs.file.contents[] vfs.file.contents
vfs.file.contents[*] Соответствие vfs.file.contents с любыми параметрами; не будет соответствовать vfs.file.contents без квадратных скобок. vfs.file.contents[]
vfs.file.contents[/путь/к/файлу]
vfs.file.contents
vfs.file.contents[/etc/passwd,*] Соответствие vfs.file.contents с первыми параметрами, соответствующими /etc/passwd, и всеми другими параметрами, имеющими любое значение (в том числе пустыми). vfs.file.contents[/etc/passwd,]
vfs.file.contents[/etc/passwd,utf8]
vfs.file.contents[/etc/passwd]
vfs.file.contents[/var/log/zabbix_server.log]
vfs.file.contents[]
vfs.file.contents[*passwd*] Соответствие vfs.file.contents с первым параметром, совпадающим с *passwd*, и без других параметров. vfs.file.contents[/etc/passwd] vfs.file.contents[/etc/passwd,]
vfs.file.contents[/etc/passwd, utf8]
vfs.file.contents[*passwd*,*] Соответствие vfs.file.contents только с первым параметром, совпадающим с *passwd*, и всеми последующими параметрами, имеющими любое значение (в том числе пустое). vfs.file.contents[/etc/passwd,]
vfs.file.contents[/etc/passwd, utf8]
vfs.file.contents[/etc/passwd]
vfs.file.contents[/tmp/test]
vfs.file.contents[/var/log/zabbix_server.log,*,abc] Соответствие vfs.file.contents с первым параметром, совпадающим с /var/log/zabbix_server.log, третьим параметром, совпадающим с «abc» и любым (в том числе пустым) вторым параметром. vfs.file.contents[/var/log/zabbix_server.log,,abc]
vfs.file.contents[/var/log/zabbix_server.log,utf8,abc]
vfs.file.contents[/var/log/zabbix_server.log,,abc,def]
vfs.file.contents[/etc/passwd,utf8] Соответствие vfs.file.contents с первым параметром, соответствующим /etc/passwd, вторым параметром, совпадающим с «utf8», и без других аргументов. vfs.file.contents[/etc/passwd,utf8] vfs.file.contents[/etc/passwd,]
vfs.file.contents[/etc/passwd,utf16]
vfs.file.* Соответствие любым ключам, начинающимся с vfs.file. без каких-либо параметров. vfs.file.contents
vfs.file.size
vfs.file.contents[]
vfs.file.size[/var/log/zabbix_server.log]
vfs.file.*[*] Соответствие любым ключам, начинающимся с vfs.file., с любыми параметрами. vfs.file.size.bytes[]
vfs.file.size[/var/log/zabbix_server.log, utf8]
vfs.file.size.bytes
vfs.*.contents Соответствие любому ключу, который начинается с vfs. и заканчивается на .contents без каких-либо параметров. vfs.mount.point.file.contents
vfs..contents
vfs.contents