Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

--- develop ---

* feature: Add per-account WinRM overrides, native PDH collection, poll health summaries, and bounded WMI response sizes
* issue: Configure CIM/WinRM defaults and clear stale cache values after successful empty results
* issue: Keep composite WMI cache indexes distinct, bound stalled PowerShell collectors, and document supported Windows transport requirements
* dev: Run the CI poller with the shared runner group so RRD files and structured directories pass permission verification
* dev: Extend the end-to-end fake wmic with --authentication-file and a stderr line, and cover host validation, the credentials file and the script-server scripts end to end
* issue: Point the script-server resource and its scripts at the files that exist, load Cacti from where it is, and register the wmic path as the path_wmi setting (default /usr/bin/wmic)
Expand Down
2 changes: 1 addition & 1 deletion INFO
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

[info]
name = wmi
version = 1.0
version = 1.1
longname = WMI Information Collector
author = The Cacti Group
email =
Expand Down
130 changes: 104 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,13 @@ Linux.
## Upgrade

Replace the plugin files. Cacti does not call the plugin's
`plugin_wmi_upgrade()` function (a search of Cacti 1.2.x and develop finds no
caller), so nothing runs on upgrade. Files that a newer release no longer
ships (`functions.php` and `linux_wmi.php` in the plugin root, listed under
`tombstones` in `manifest.json`) are not removed; delete them by hand.
`plugin_wmi_upgrade()` function during ordinary page loads. Cacti runs it when
the plugin version changes during its database audit/upgrade process. This
release provisions the WinRM account and poll-health columns through the
idempotent plugin schema setup. Run the Cacti database audit/upgrade after
replacing the files. Files that a newer release no longer ships (`functions.php`
and `linux_wmi.php` in the plugin root, listed under `tombstones` in
`manifest.json`) are not removed; delete them by hand.

## Disable and uninstall

Expand All @@ -98,26 +101,97 @@ server's operating system. Code that constructs `Linux_WMI` directly can pass
an explicit transport instead.

- **wmic** (default on a Linux server). Uses the Linux `wmic` client to reach
Windows hosts over DCOM. The client does not appear in the Debian 12 or Ubuntu
18.04 package lists, so install it from your own package source or build
it. The Query Tool and the poller take the binary from the `path_wmi`
setting and use `/usr/bin/wmic` when it is empty; `path_wmi` has no field on
the Settings page yet. `wmi_script.php` always uses `/usr/bin/wmic`, and `script/wmi-script.php`
looks for a `wmic` inside the plugin directory, which is not shipped. The
user name and password are passed to `wmic` as `--user` and `--password`
arguments, so a local user can read them in the process list while a query
runs. This client predates current Windows hardening. Hosts that disable
NTLMv1 or enforce the DCOM packet-integrity level (KB5004442, enforced
without an opt-out since March 2023) may reject it. There is currently no
console setting to switch a Linux Cacti server to the PowerShell transport;
it is only available to code that constructs `Linux_WMI` directly and
passes an explicit transport.
Windows hosts over DCOM. Windows 11 24H2 and later no longer include the
Windows WMIC utility, but WMI itself remains supported. The utility's
removal does not remove the remote WMI service used by this Linux-side
client ([Microsoft's WMIC and WMI notes](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmic)).
Hosts that enforce current DCOM authentication hardening may still reject
this legacy transport. The client does not appear in the Debian 12 or
Ubuntu 18.04 package lists, so install it from your own package source or
build it. The Query Tool and poller use `path_wmi`, defaulting to
`/usr/bin/wmic`; there is no Settings page field for this path yet.
Credentials normally go in a private temporary authentication file. If the
plugin cannot create that file, it warns and falls back to `--user` and
`--password` arguments, which local users may see in the process list.
- **PowerShell / CIM** (default on a Windows server). Runs `powershell.exe`
and uses `Get-CimInstance`, so it works when Cacti runs on Windows and
against a remote host over WinRM/CIM. Needs PowerShell on the Cacti server
and, for a remote host, WinRM enabled on the target. Credentials and every
device-supplied value are passed through the child process environment and a
fixed script on standard input, never on the command line.
and uses `Get-CimInstance`. This transport requires the Cacti server to run
Windows. Microsoft's [Get-CimInstance platform requirements](https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.5)
document the CIM cmdlets as Windows-only. Remote Windows targets need WinRM
configured and reachable. Use Kerberos with domain hostnames where
available. For connections without Kerberos, configure WinRM HTTPS or a
narrowly scoped TrustedHosts entry ([PowerShell remoting guidance](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-7.5)).
The Authentication account form can override SSL, port, and authentication
per credential account, or inherit the Settings > Misc defaults. Basic is
rejected unless HTTPS is selected; certificate validation remains enabled.
Leave the port blank to use the Windows default for the selected transport.
Credentials and device-supplied values pass through the child process
environment and a fixed script on standard input, never on the command line.

### Windows performance counter collection

For classic performance counter WMI classes, query the
[`Win32_PerfFormattedData_*` classes](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-tasks--performance-monitoring)
classes for provider-formatted values (for example, `Win32_PerfFormattedData_PerfOS_Processor`).
Use a Cacti polling interval appropriate to the signal and avoid collecting
high-cardinality instance data more frequently than needed. Microsoft notes
that many raw performance counters require two timestamped samples and a
counter-specific time base; this plugin runs independent WQL queries and does
not keep PDH sample state, so it must not derive rates from raw values itself.
If collecting monotonic raw totals, configure the Cacti data source as a
`COUNTER` or `DERIVE` where appropriate so RRDtool computes a rate and handles
counter behavior. Choose `COUNTER` only when its wrap assumptions match the
counter; use `DERIVE` when negative deltas are meaningful. Neither data source
can infer Windows counter metadata from an arbitrary WMI field. Use `GAUGE` for
point-in-time and already formatted values.

For process-level counters on Windows 11 and newer, Microsoft recommends the
Process V2 counter set because its instance names include the process ID and
avoid ambiguities when processes with the same name exit and start. Process V2
is a PDH counter set and is not exposed by this plugin's current generic CIM
WQL transport; use a native PDH/PerfMon collector for that data. Microsoft's
Windows Server performance guidance also shows bounded `logman` counter logs
with 15-second sampling for troubleshooting, while System Insights uses
15-minute intervals for its retained server telemetry. Choose the sampling
interval based on the operational need and Cacti poller load.

To collect a native PDH counter, create a query with `PDH` as its namespace and
one or more counter paths, one per line, in the Query field. The Windows-hosted
PowerShell collector invokes `Get-Counter` remotely over WinRM, collects two
samples one second apart, and returns the formatted value and timestamp from
the second sample. For Windows 11 process monitoring, paths from the Process V2
counter set include the process ID in the instance name; set the query's primary
key to `Path,Instance` so the cache keeps each counter instance distinct. This mode requires
PowerShell remoting enabled on the target and is available only when Cacti runs
the collector on Windows. Do not use raw PDH counter paths with the WQL query
mode.

Suggested starting WQL inventory and counter queries include:

- `SELECT Caption,Version,BuildNumber,OSArchitecture,LastBootUpTime FROM Win32_OperatingSystem`
- `SELECT Name,PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor`
- `SELECT AvailableMBytes,CommittedBytes,CommitLimit FROM Win32_PerfFormattedData_PerfOS_Memory`
- `SELECT Name,PercentDiskTime,AvgDiskQueueLength FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk`

These are starting points. Confirm that a class and property exists on the
target Windows version and avoid broad process or interface queries unless the
result cardinality and output size are needed. Each transport stops a query
whose response exceeds 16 MiB.

The WMI Queries list reports the number of devices with poll history, most recent poll,
currently failing devices, and cumulative timeout count. Query failures retain
the previous cached values and record a bounded error summary. Consecutive
failure counts reset after the next successful poll.

### Windows validation matrix

Before releasing changes to the Windows transport, run the collector from a
Windows Server Cacti host against a current Windows 11 target and Windows
Server 2025 target. Verify WQL collection over HTTP/Negotiate and HTTPS/Kerberos,
Basic over HTTPS, a rejected Basic-over-HTTP configuration, alternate ports,
invalid credentials, denied counter paths, empty results, response-size limits,
timeouts, and Process V2 paths with `Path,Instance` as the primary key. This is
a manual lab matrix; the plugin's current CI does not run on Windows and these
target combinations are not claimed as tested here.

## Usage

Expand All @@ -143,9 +217,13 @@ WMI Queries that are specific to Windows SQL Server there.
The plugin registers a WMI Management realm covering account management, query
definition, and the query tool. The Template Editor role is additionally
granted the query-definition page only; credential management and the live query
tool stay behind the WMI Management realm. The poller needs the host password
in cleartext, so accounts are stored reversibly (base64 of a serialized array),
not hashed or encrypted; protect the database accordingly.
tool stay behind the WMI Management realm. The poller needs the host password
in cleartext, so account passwords are stored reversibly (base64 of a serialized
array), not encrypted at rest. No cross-version Cacti secret-storage API is
available to this plugin. Restrict database access to the Cacti service
accounts, keep database traffic on a protected network, encrypt database
backups, and protect `config.php` and its database credentials with filesystem
permissions. A database dump includes the reversible WMI credentials.

## Settings

Expand Down
27 changes: 26 additions & 1 deletion includes/database.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
* host_wmi_cache, wmi_processes), and registers this plugin's two Data
* Input Methods ('Get WMI Data' and 'Get WMI Data (Indexed)') along with
* their input/output fields, if not already present. Called from
* plugin_wmi_install() during plugin installation.
* plugin_wmi_install() during installation and plugin_wmi_upgrade() during
* upgrades.
*
* @return void
*/
Expand All @@ -50,6 +51,9 @@ function plugin_wmi_setup_tables() {
`name` varchar(64) NOT NULL,
`username` varchar(64) NOT NULL,
`password` varchar(256) NOT NULL,
`winrm_ssl` varchar(8) NOT NULL DEFAULT 'inherit',
`winrm_port` varchar(5) NOT NULL DEFAULT '',
`winrm_auth` varchar(16) NOT NULL DEFAULT 'inherit',
PRIMARY KEY (`id`))
ENGINE=InnoDB
COMMENT='Holds Account Information for WMI Queries'");
Expand All @@ -75,10 +79,31 @@ function plugin_wmi_setup_tables() {
`last_started` timestamp NOT NULL DEFAULT '0000-00-00',
`last_runtime` double NOT NULL DEFAULT '0.00',
`last_failed` timestamp NOT NULL DEFAULT '0000-00-00',
`last_success` timestamp NULL DEFAULT NULL,
`last_error` varchar(1024) NOT NULL DEFAULT '',
`consecutive_failures` int(10) unsigned NOT NULL DEFAULT '0',
`timeout_count` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`host_id`,`wmi_query_id`))
ENGINE=InnoDB
COMMENT='Holds WMI Data Queries'");

foreach ([
['table' => 'wmi_user_accounts', 'column' => 'winrm_ssl', 'type' => 'varchar(8)', 'default' => 'inherit'],
['table' => 'wmi_user_accounts', 'column' => 'winrm_port', 'type' => 'varchar(5)', 'default' => ''],
['table' => 'wmi_user_accounts', 'column' => 'winrm_auth', 'type' => 'varchar(16)', 'default' => 'inherit'],
['table' => 'host_wmi_query', 'column' => 'last_success', 'type' => 'timestamp', 'NULL' => true, 'default' => null],
['table' => 'host_wmi_query', 'column' => 'last_error', 'type' => 'varchar(1024)', 'default' => ''],
['table' => 'host_wmi_query', 'column' => 'consecutive_failures', 'type' => 'int(10)', 'unsigned' => true, 'default' => '0'],
['table' => 'host_wmi_query', 'column' => 'timeout_count', 'type' => 'int(10)', 'unsigned' => true, 'default' => '0'],
] as $column) {
$table = $column['table'];
unset($column['table']);
$name = $column['column'];
unset($column['column']);

api_plugin_db_add_column('wmi', $table, array_merge(['name' => $name], $column));
}

db_execute("CREATE TABLE IF NOT EXISTS `host_template_wmi_query` (
`host_template_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
`wmi_query_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
Expand Down
55 changes: 51 additions & 4 deletions includes/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,9 +393,11 @@ function plugin_wmi_create_resource_xml($id) {
* @global array $config Cacti global configuration array; used to load
* this plugin's linux_wmi.php client.
*/
function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {
function run_store_wmi_query($host_id, $wmi_query_id, $transport = null, &$error = null) {
global $config;

$error = null;

$host_info = db_fetch_row_prepared('SELECT *
FROM host
WHERE id = ?',
Expand All @@ -419,10 +421,14 @@ function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {
$wmi_query = is_array($wmi_query) ? $wmi_query : [];

if (!cacti_sizeof($auth_info)) {
$error = 'WMI account not found';

return false;
}

if (!cacti_sizeof($wmi_query)) {
$error = 'WMI query not found';

return false;
}

Expand All @@ -446,6 +452,15 @@ function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {
$wmi->hostname = $host;
$wmi->username = $username;
$wmi->password = $wmi->decode($password);
if (in_array($auth_info['winrm_ssl'] ?? '', ['on', 'off'], true)) {
$wmi->winrm_ssl = $auth_info['winrm_ssl'] === 'on';
}
if (($auth_info['winrm_port'] ?? '') !== '') {
$wmi->winrm_port = ctype_digit((string) $auth_info['winrm_port']) ? (int) $auth_info['winrm_port'] : 0;
}
if (in_array($auth_info['winrm_auth'] ?? '', ['Negotiate', 'Kerberos', 'Basic'], true)) {
$wmi->winrm_authentication = $auth_info['winrm_auth'];
}
$wmi->querynspace = $namespace;
$wmi->command = $command;
$wmi->binary = read_config_option('path_wmi');
Expand All @@ -458,7 +473,9 @@ function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {
$wmi->querynspace = 'root\\\\CIMV2';
}

if ($wmi->fetch() !== false) {
$fetch_result = $wmi->fetch();

if ($fetch_result !== false) {
$indexes = $wmi->fetch_indexes();
$data = $wmi->fetch_data();
} else {
Expand All @@ -468,6 +485,17 @@ function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {

$indexes = is_array($indexes) ? $indexes : [];

if ($fetch_result !== false && $data === []) {
// A successful empty result is authoritative. A failed transport keeps
// the cached values intact, while an empty response removes stale data.
db_execute_prepared('DELETE FROM host_wmi_cache
WHERE host_id = ?
AND wmi_query_id = ?',
[$host_id, $wmi_query_id]);

return true;
}

if (cacti_sizeof($data)) {
$sql = [];

Expand Down Expand Up @@ -532,6 +560,7 @@ function run_store_wmi_query($host_id, $wmi_query_id, $transport = null) {
return true;
} else {
$reason = is_string($wmi->error) ? $wmi->error : 'WMI returned no rows';
$error = $reason;

cacti_log('WARNING: WMI Query[' . $wmi_query_id . '] for Device[' . $host_id . '] failed: ' . $reason, false, 'WMI', POLLER_VERBOSITY_MEDIUM);

Expand Down Expand Up @@ -569,6 +598,23 @@ function wmi_account_input_valid($name, $username, $password, $confirm, $id) {
return $password !== '' || $id > 0;
}

/**
* Validates per-account WinRM settings before they are written to the account
* record. Basic authentication must be explicitly paired with HTTPS.
*/
function wmi_account_winrm_input_valid($ssl, $port, $authentication) {
if (!in_array($ssl, ['inherit', 'off', 'on'], true) ||
!in_array($authentication, ['inherit', 'Negotiate', 'Kerberos', 'Basic'], true)) {
return false;
}

if ($port !== '' && (!ctype_digit($port) || (int) $port < 1 || (int) $port > 65535)) {
return false;
}

return $authentication !== 'Basic' || $ssl === 'on';
}

/**
* Checks that an encoded password fits the wmi_user_accounts.password
* column (varchar(256)) instead of being truncated or rejected by the
Expand All @@ -584,7 +630,8 @@ function wmi_account_password_fits($encoded) {

/**
* Builds the host_wmi_cache index value for one result row from the query's
* primary key. A comma separated key joins its columns' values with a comma.
* primary key. A comma separated key joins its columns' values with a comma;
* backslashes and commas inside values are escaped to keep tuples distinct.
* 'None', an empty key, or a key column missing from the result header yields
* 'N/A', which is the single shared index for queries that return one row.
*
Expand All @@ -604,7 +651,7 @@ function wmi_row_index($row, $indexes, $primary_key) {
return 'N/A';
}

$values[] = $row[$position];
$values[] = str_replace(['\\', ','], ['\\\\', '\\,'], $row[$position]);
}

return implode(',', $values);
Expand Down
Loading
Loading