Files
cacti/automation_snmp.php
TheWitness f79dc15c08 Port #8166 SNMP credential cache + procedural SNMPv3 (with #8171/#8172 follow-ups) to develop (#8174)
* Port #8166 SNMP credential cache + procedural SNMPv3 to develop

Ports the shared SNMPv3 credential cache and procedural SNMPv3 routing from the
1.2.x feature (merged as #8166) onto develop, adapted to develop's refactored
SNMP layer. Parts of the 1.2.x change that do not apply to develop are omitted:
the cacti_exec() idle-timeout rewrite (develop has no cacti_exec()), the PHP
floor bump and composer/doc changes (develop is already 8.3+), and the cmd.php
max_oids batching (develop's cmd.php already collects SNMP in-process through
persistent sessions, so the per-item spawn the batching removed does not occur).

- lib/cache.php: new cross-process \Cacti\Cache\SharedCache (file + POSIX
  shared-memory + process-local tiers, optional AES-256-GCM sealing). Loaded via
  lib/snmp.php (the Cacti\Cache\ namespace is not PSR-4 autoloaded). The crypto
  helpers it seals with already live in develop's lib/auth.php, loaded by
  global.php, so no duplicate was added.
- lib/snmp.php: snmp_get_method() now routes SNMPv3 get/getnext to the
  procedural snmp3_*() calls when the running PHP supports the configured
  auth/privacy tokens and no context/engine id is set (SHA-224/384 and
  AES-192/256[C] stay on the binary before PHP 8.6); the three single-get
  functions gain the procedural v3 path with \Throwable handling; adds the
  credential-cache subsystem, protocol-option/MD5-DES helpers,
  snmp_native_protocol(), snmp_format_agent() and cacti_snmp_get_multi(); the
  binary v3 auth builder consults the cache when enabled.
- poller.php / script_server.php: prime / load the shared cache.
- poller_maintenance.php: daily out-of-band cache rebuild on every collector
  (per-poller lastrun marker).
- lib/api_device.php / lib/utility.php: bump snmp_cred_version only on v3
  credential add/change (and propagate the token to the affected remote poller).
- include/global.php: resolve and create the private cache/ directory.
- include/global_settings.php: add 'Enable Credential Cache' and 'Enable MD5 and
  DES for SNMPv3' settings (both off by default); default new-device v3
  auth/privacy to SHA/AES instead of legacy MD5/DES.
- host.php / automation_snmp.php: drop MD5/DES from the pickers when disabled and
  default new records to SHA/AES on upgraded installs.
- include/config.php.dist: document $config['cache_dir'].
- tests/Unit/Core/Cache/SharedCacheTest.php: SharedCache behaviour coverage.
- tests/security/baselines: baseline the two new lib/cache.php sinks.

* Incorporate #8171: binary fallback for unsupported SNMPv3 protocols

Layers PR #8171 onto the develop port so an SNMPv3 device whose auth/privacy
protocols the running PHP's ext-snmp cannot service natively (e.g. AES-256
before PHP 8.6) no longer fatals the poller or device-edit screen.

- lib/snmp.php: add CactiSnmpBinarySession, a session stand-in exposing the
  get/getnext/walk/close interface the cacti_snmp_session_*() helpers use and
  delegating each call to cacti_snmp_*() -> the Net-SNMP binary.
  cacti_snmp_session() returns it when php-snmp is absent or the v3 protocol is
  not natively serviceable, so cmd.php/host.php collect these devices via the
  binary on pre-8.6 and switch to the in-process path on 8.6 with no caller
  change. v1/v2 snmpget/snmp2_get now go through snmp_format_agent(). The
  ERRNO_TIMEOUT check tolerates php-snmp being absent. Drop the vendored
  classSNMP.php compatibility shim and its include (and the Yandex attribution).
- cmd.php: open_snmp_session() returns the down sentinel when a host is already
  marked down this run, instead of returning an unset (null) []
  that cacti_snmp_session_get() then dereferenced (TypeError).
- lib/ping.php: ping_snmp() runs the availability check through the procedural
  cacti_snmp_get()/getnext() path so an unsupported protocol falls back to the
  binary instead of raising a ValueError in SNMP::setSecurity().

* Incorporate #8172: retire include/vendor/phpsnmp, relocate into lib

Follow-up to #8171 on the develop port. After classSNMP.php was removed, the
include/vendor/phpsnmp/ directory held only Cacti-owned files; this retires it.

- lib/snmp.php: the ext-snmp subclass that carried Cacti's bulk_walk_size /
  value_output_format (previously vendor/phpsnmp/extension.php) is now declared
  directly as CactiSnmpNativeSession, guarded by CACTI_PHP_SNMP; the include and
  the 'use phpsnmp\SNMP' alias are gone, and new SNMP(...) / SNMP::VERSION_*
  now reference the native \SNMP and the new subclass.
- lib/mib_parser.php: moved from include/vendor/phpsnmp/mib_parser.php;
  lib/mib_cache.php includes it via __DIR__.
- Remove include/vendor/phpsnmp/extension.php and index.php (directory retired).
- tests: SnmpCoverageTest uses \SNMP::ERRNO_TIMEOUT now that phpsnmp\SNMP is
  gone; drop the stale include/vendor/phpsnmp/ entry from the vendor-policy
  allowlist.

develop's sink baseline tracks constant-based includes differently than 1.2.x,
so no baseline refresh was needed here.

* Address PR #8174 review: snmp_get_method params, v3 walk, getnext agent, cache bump, CHANGELOG

- lib/snmp.php: restore $php_snmp as the 6th snmp_get_method() parameter and move
  the new $auth_proto/$priv_proto after it (callers pass them by name), so the
  positional $php_snmp used by SnmpCoverageTest and others keeps working.
- lib/snmp.php: keep every SNMPv3 operation except get/getnext on the Net-SNMP
  binary - the native walk branch implements only v1/v2, so a v3 walk reaching
  the procedural gate would have silently returned empty when path_snmpbulkwalk
  is missing.
- lib/snmp.php: cacti_snmp_getnext() v1/v2 branches now use snmp_format_agent()
  like get/get_raw, so an IPv6 literal / non-default port is bracketed.
- lib/api_device.php: bump snmp_cred_version only when the host's v3 membership
  or one of the cached credential fields actually changed, instead of on every
  save of a v3 device.
- CHANGELOG: move the #8171 entry into the issue block and the #8166 entries into
  the feature block, matching the established section ordering.

* Fix CI: unbracket IPv4/DNS SNMP targets, inline auth-cache SQL columns, apply phpcsfixer standard

* Refresh sink inventory baseline after short-array normalization

* Restore lib/snmp.php 100% coverage after aligning v3 routing to 1.2.x

- update the three SnmpCoverageTest assertions that still encoded develop's
  pre-port behavior: v3 snmp_get_method now returns PHP, an unsupported-
  protocol v3 session returns the binary-delegating session object, and the
  v3 cacti_snmp_get path runs natively
- add a v3 noAuthNoPriv user to the snmp-coverage snmpd fixture so native
  snmp3_get is exercised deterministically
- add tests covering the ported subsystems to 100%: shared auth cache,
  binary-delegating session, protocol pickers, v3 credential args,
  cacti_snmp_get_multi, and the cacti_get_snmpv3_auth cache path
- snmp_auth_cache_load uses a resettable process guard so its enabled and
  disabled branches are both coverable in a single process

* Resolve phpstan errors in the relocated SNMP MIB parser and ported snmp.php

- lib/mib_parser.php: type the MibParser properties, add parameter/return
  types, guard file_get_contents()/preg_split() against false, correct the
  parse_bracket_token delimiter params (string, not integer), and drop the
  unreachable return after trigger_error(E_USER_ERROR) - now phpstan clean
- lib/mib_cache.php: drop the redundant isset($mp->oids) guard (the typed
  property is always initialized; $mp->mib is the real check)
- lib/snmp.php: type the CactiSnmpBinarySession and CactiSnmpNativeSession
  properties/methods and pass bool to snmp_set_quick_print()
- .phpstan.neon: ignore greaterOrEqual.alwaysFalse alongside the existing
  greater.alwaysFalse (the PHP_VERSION_ID >= 80600 forward-compat gate)
- regenerate phpstan-baseline.neon for the irreducible ext-snmp stub
  strictness (snmp3_get literal-union protocols, int<-1,max> timeouts) in
  the ported procedural v3 path, the new lib/cache.php shmop stubs, and the
  $config array-shape offsets in include/global.php

* Make the v3 getter catch coverage net-snmp-build-independent

The DES-rejection trick that drove the procedural snmp3_get()/snmp3_getnext()
try/catch blocks only works on net-snmp builds compiled without DES; CI's
Debian net-snmp accepts DES, so those catches went uncovered (98.3%).

- extend the existing native_get injection seam (already on cacti_snmp_get)
  to cacti_snmp_get_raw, cacti_snmp_getnext, and cacti_snmp_get_multi, and
  drive the catch blocks with a throwing native getter in the test
- mark the seam-less cacti_snmp_session() setSecurity catch with
  @codeCoverageIgnore (it only throws for a protocol the running net-snmp
  rejects, which is not portably reproducible in the fixture)

* Exclude ext-snmp/PHP-8.6-gated defensive branches from snmp coverage

Two branches in lib/snmp.php are unreachable on the PHP 8.3 + ext-snmp
coverage runner and were only "covered" locally via opcache dead-code
elimination:

- snmp_get_method()'s !function_exists('snmp3_get') fallback (ext-snmp
  always provides snmp3_get)
- snmp_php_v3_protocols_supported()'s PHP_VERSION_ID >= 80600 block
  (SHA-224/384 and AES-192/256 tokens are only accepted on PHP 8.6+)

Mark both with @codeCoverageIgnore so the 100% gate is deterministic
across runners regardless of opcache settings.

* Account for the #8166 SNMPv3 credential-cache gate query in the batching test

poller_update_poller_cache_from_buffer() now runs one SELECT per flush to
decide whether the flush touched SNMPv3 poller items before bumping the shared
credential-cache version (matching 1.2.x). UpdateDataQueryCacheBatchingIntegrationTest
counted 4 statements per flush; update it to 5 (and 3 per-row flushes to 15,
1 batched flush to 5). The guard's intent - batching issues fewer statements
than per-row flushes - still holds.

* Port #8175: group SNMP options under an SNMP Behavior section

Mirror the 1.2.x settings reorganization (#8175) on develop. develop already
keeps the SNMP options in a dedicated SNMP tab, so add an "SNMP Behavior"
spacer there, order the behavior options as md5/des, credential cache, max
get size, bulkwalk fetch size, and move "Disable increasing OID Check" out of
the Poller tab to sit last in that group. Display-only; no settings added or
removed and no behavior change. Adds the "SNMP Behavior" heading to cacti.pot.

* fix: complete dependabot htmx 2.0.10 to 2.0.11 bump

Dependabot bumped package.json and package-lock.json to htmx.org 2.0.11
(PR 8179) but left the vendored include/js/htmx.js, its version marker,
and the pinned SRI constant at 2.0.10. The htmx-filters CI workflow runs
npm ci, which regenerates include/js/htmx.js from the 2.0.11 package, so
HtmxTest's runtime sha384 no longer matches the HTMX_2_0_10_SRI constant
and the integrity assertion fails.

Complete the bump: regenerate the vendored include/js/htmx.js to the
2.0.11 build, bump include/js/htmx.js.version to 2.0.11, rename
HTMX_2_0_10_SRI to HTMX_2_0_11_SRI with the recomputed sha384 hash, and
update the version/integrity assertions in tests/Unit/Ui/Html/HtmxTest.php
and tests/HandOff/HtmxLoaderHandOffTest.php. package.json and
package-lock.json match the values dependabot already landed on develop.

* settings: move SNMP Agent Support under the SNMP Behavior spacer

Relocate the enable_snmp_agent setting (SNMP Agent Support Enabled) so it
is the first item under the SNMP Behavior spacer instead of sitting in the
Poller General group, grouping it with the other SNMP behavior options.

* Address PR #8174 review: keep SHA-224/384 on the binary, honor port on transport targets

Resolves the two still-valid Copilot review findings on lib/snmp.php that were
left unresolved (only marked outdated after later commits shifted their lines).

- snmp_php_v3_protocols_supported(): drop SHA224/SHA384 from the native auth
  allowlist. ext-snmp's SNMP::setSecurity()/snmp3_*() only map MD5/SHA/SHA256/
  SHA512 - there is no SHA-224/SHA-384 mapping on any build, including PHP 8.6
  (verified against php-src ext/snmp/snmp.c), so routing those tokens to the
  procedural path raised a ValueError instead of using the binary. They now
  always fall back to the Net-SNMP binary. The AES-192/256 privacy tokens that
  ext-snmp does add on 8.6 stay gated behind PHP_VERSION_ID >= 80600.
- snmp_format_agent(): a udp/tcp transport-qualified target that omits a port
  now has the configured non-default port appended (udp6:[2001:db8::1] + 1161 ->
  udp6:[2001:db8::1]:1161), matching the Net-SNMP binary path. Targets that
  already carry a port, and unix: sockets (no port), are left untouched.
- SnmpCoverageTest: cover the new transport-target branches; lib/snmp.php stays
  at 100%.
2026-10-05 10:18:41 -04:00

1026 lines
33 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
require('./include/auth.php');
require_once(CACTI_PATH_LIBRARY . '/api_automation.php');
require_once(CACTI_PATH_LIBRARY . '/snmp.php');
require_once(CACTI_PATH_LIBRARY . '/CactiValidator.php');
use Symfony\Component\Validator\Constraints as Assert;
$actions = [
1 => __('Delete'),
2 => __('Duplicate'),
3 => __('Export'),
];
// set default action
set_default_action();
// correct for a cancel button
if (isrv('cancel')) {
srv('action', '');
}
switch (grv('action')) {
case 'save':
if (isrv('save_component_import')) {
automation_import_process();
} else {
form_save();
}
break;
case 'import':
top_header();
automation_import();
bottom_footer();
break;
case 'export':
automation_export();
break;
case 'actions':
form_actions();
break;
case 'ajax_dnd':
automation_snmp_item_dnd();
break;
case 'item_movedown':
gfrv('id');
automation_snmp_item_movedown();
header('Location: automation_snmp.php?action=edit&id=' . grv('id'));
break;
case 'item_moveup':
gfrv('id');
automation_snmp_item_moveup();
header('Location: automation_snmp.php?action=edit&id=' . grv('id'));
break;
case 'item_remove_confirm':
automation_snmp_item_remove_confirm();
break;
case 'item_remove':
gfrv('id');
automation_snmp_item_remove();
header('Location: automation_snmp.php?action=edit&id=' . grv('id'));
break;
case 'item_edit':
top_header();
automation_snmp_item_edit();
bottom_footer();
break;
case 'edit':
top_header();
automation_snmp_edit();
bottom_footer();
break;
default:
top_header();
automation_snmp();
bottom_footer();
break;
}
function automation_export() : void {
// if we are to save this form, instead of display it
if (isrv('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(gnrv('selected_items'));
$snmp_option_ids = [];
if ($selected_items != false) {
if (cacti_sizeof($selected_items) == 1) {
$export_data = automation_snmp_option_export($selected_items[0]);
} else {
foreach ($selected_items as $id) {
$snmp_option_ids[] = $id;
}
$export_data = automation_snmp_option_export($snmp_option_ids);
}
if (cacti_sizeof($export_data)) {
$export_file_name = $export_data['export_name'];
header('Content-type: application/json');
header('Content-Disposition: attachment; filename=' . $export_file_name);
$output = json_encode($export_data, JSON_PRETTY_PRINT);
print $output;
} else {
}
}
}
}
function automation_import() : void {
$form_data = [
'import_file' => [
'friendly_name' => __('Import SNMP Options from Local File'),
'description' => __('If the JSON file containing the SNMP Options data is located on your local machine, select it here.'),
'method' => 'file',
'accept' => '.json'
],
'import_text' => [
'friendly_name' => __('Import SNMP Options from Text'),
'description' => __('If you have the JSON file containing the SNMP Options data as text, you can paste it into this box to import it.'),
'method' => 'textarea',
'value' => '',
'default' => '',
'textarea_rows' => '10',
'textarea_cols' => '80',
'class' => 'textAreaNotes'
]
];
form_start('automation_snmp.php', 'chk', true);
if ((isset($_SESSION['import_debug_info'])) && (is_array($_SESSION['import_debug_info']))) {
html_start_box(__('Import Results'), '60%', false, 3, 'center', '');
print '<tr class="tableHeader"><th>' . __('Cacti has Imported the following SNMP Options') . '</th></tr>';
foreach ($_SESSION['import_debug_info'] as $line) {
print '<tr><td>' . $line . '</td></tr>';
}
html_end_box();
kill_session_var('import_debug_info');
}
html_start_box(__('Import SNMP Options'), '60%', false, 3, 'center', '');
draw_edit_form(
[
'config' => ['no_form_tag' => true],
'fields' => $form_data
]
);
form_hidden_box('save_component_import', '1', '');
print " <tr><td><hr/></td></tr><tr>
<td class='saveRow'>
<input type='hidden' name='action' value='save'>
<button type='submit' value='import' title='" . __esc('Import SNMP Options') . "' class='ui-button ui-corner-all ui-widget ui-state-active'>" . __esc('Import') . "</button>
</td>
<script type='text/javascript'>
$(function() {
Pace.stop();
clearAllTimeouts();
});
</script>
</tr>";
form_end(true);
html_end_box();
}
function automation_import_process() : void {
$json_data = json_decode(gnrv('import_text'), true);
$debug_data = [];
$return_data = [];
// If we have text, then we were trying to import text, otherwise we are uploading a file for import
if (empty($json_data)) {
$json_data = automation_validate_upload();
}
if (is_array($json_data) && cacti_sizeof($json_data) && isset($json_data['snmp'])) {
foreach ($json_data['snmp'] as $snmp) {
$return_data += automation_snmp_option_import($snmp);
}
}
if (cacti_sizeof($return_data) && isset($return_data['success'])) {
foreach ($return_data['success'] as $message) {
$debug_data[] = '<span class="deviceUp">' . __('NOTE:') . '</span> ' . $message;
automation_log('NOTE: SNMP Options Import Succeeded! Message: ' . $message, AUTOMATION_LOG_LOW);
}
}
if (isset($return_data['errors'])) {
foreach ($return_data['errors'] as $error) {
$debug_data[] = '<span class="deviceDown">' . __('ERROR:') . '</span> ' . $error;
automation_log('NOTE: SNMP Options Import Error! Message: ' . $error, AUTOMATION_LOG_LOW);
}
}
if (isset($return_data['failure'])) {
foreach ($return_data['failure'] as $message) {
$debug_data[] = '<span class="deviceDown">' . __('ERROR:') . '</span> ' . $message;
automation_log('NOTE: Automation SNMP Option Import Failed! Message: ' . $message, AUTOMATION_LOG_LOW);
}
}
if (cacti_sizeof($debug_data)) {
$_SESSION['import_debug_info'] = $debug_data;
}
header('Location: automation_snmp.php?action=import');
exit();
}
function form_save() : void {
if (isrv('save_component_automation_snmp')) {
// ================= input validation =================
gfrv('id');
// ====================================================
$save['id'] = grv('id');
$save['hash'] = get_hash_automation(grv('id'), 'automation_snmp');
$save['name'] = CactiValidator::validateInput(gnrv('name'), 'name', [new Assert\NotBlank()]);
if (!is_error_message()) {
$id = sql_save($save, 'automation_snmp');
if ($id) {
raise_message(1);
} else {
raise_message(2);
}
}
header('Location: automation_snmp.php?action=edit&id=' . (empty($id) ? gnrv('id') : $id));
} elseif (isrv('save_component_automation_snmp_item')) {
// ================= input validation =================
gfrv('item_id');
gfrv('id');
// ====================================================
$save = [];
$save['id'] = CactiValidator::validateInput(grv('item_id'), 'item_id', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThanOrEqual(0)]);
$save['hash'] = get_hash_automation(grv('item_id'), 'automation_snmp_items');
$save['snmp_id'] = CactiValidator::validateInput(gnrv('id'), 'snmp_id', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThanOrEqual(0)]);
$save['sequence'] = CactiValidator::validateInput(gnrv('sequence'), 'sequence', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThanOrEqual(0)]);
$save['snmp_community'] = CactiValidator::validateInput(gnrv('snmp_community'), 'snmp_community', [new Assert\NotBlank()]);
$save['snmp_version'] = CactiValidator::validateInput(gnrv('snmp_version'), 'snmp_version', [new Assert\NotBlank(), new Assert\Choice(['1', '2', '3'])]);
$save['snmp_username'] = CactiValidator::validateInput(gnrv('snmp_username'), 'snmp_username', []);
$save['snmp_password'] = CactiValidator::validateInput(gnrv('snmp_password'), 'snmp_password', []);
$save['snmp_auth_protocol'] = CactiValidator::validateInput(gnrv('snmp_auth_protocol'), 'snmp_auth_protocol', []);
$save['snmp_priv_passphrase'] = CactiValidator::validateInput(gnrv('snmp_priv_passphrase'), 'snmp_priv_passphrase', []);
$save['snmp_priv_protocol'] = CactiValidator::validateInput(gnrv('snmp_priv_protocol'), 'snmp_priv_protocol', []);
$save['snmp_context'] = CactiValidator::validateInput(gnrv('snmp_context'), 'snmp_context', []);
$save['snmp_engine_id'] = CactiValidator::validateInput(gnrv('snmp_engine_id'), 'snmp_engine_id', []);
$save['snmp_port'] = CactiValidator::validateInput(gnrv('snmp_port'), 'snmp_port', [new Assert\NotBlank(), new Assert\Range(min: 1, max: 65535)]);
$save['snmp_timeout'] = CactiValidator::validateInput(gnrv('snmp_timeout'), 'snmp_timeout', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThan(0)]);
$save['snmp_retries'] = CactiValidator::validateInput(gnrv('snmp_retries'), 'snmp_retries', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThanOrEqual(0)]);
$save['max_oids'] = CactiValidator::validateInput(gnrv('max_oids'), 'max_oids', [new Assert\NotBlank(), new Assert\Type('numeric'), new Assert\GreaterThan(0)]);
$save['bulk_walk_size'] = CactiValidator::validateInput(gnrv('bulk_walk_size'), 'bulk_walk_size', [new Assert\NotBlank(), new Assert\Type('numeric')]);
$item_id = null;
if (!is_error_message()) {
$item_id = sql_save($save, 'automation_snmp_items');
if ($item_id) {
raise_message(1);
} else {
raise_message(2);
}
}
if (is_error_message()) {
header('Location: automation_snmp.php?action=item_edit&id=' . gnrv('id') . '&item_id=' . ($item_id === null ? gfrv('id') : $item_id));
} else {
header('Location: automation_snmp.php?action=edit&id=' . gnrv('id'));
}
} else {
raise_message(2);
header('Location: automation_snmp.php');
}
}
function form_actions() : void {
global $actions;
// ================= input validation =================
gfrv('drp_action');
// ====================================================
// if we are to save this form, instead of display it
if (isrv('selected_items')) {
$selected_items = sanitize_unserialize_selected_items(gnrv('selected_items'));
if ($selected_items != false) {
if (gnrv('drp_action') == '1') { // delete
db_execute('DELETE FROM automation_snmp WHERE ' . array_to_sql_or($selected_items, 'id'));
db_execute('DELETE FROM automation_snmp_items WHERE ' . str_replace('id', 'snmp_id', array_to_sql_or($selected_items, 'id')));
} elseif (gnrv('drp_action') == '2') { // duplicate
for ($i = 0; ($i < cacti_count($selected_items)); $i++) {
automation_duplicate_snmp_option($selected_items[$i], gnrv('name_format'));
}
} elseif (gnrv('drp_action') == '3') { // export
top_header();
print '<script text="text/javascript">
function DownloadStart(url) {
document.getElementById("download_iframe").src = url;
setTimeout(function() {
loadUrl({ url: "automation_snmp.php" });
Pace.stop();
}, 500);
}
$(function() {
//debugger;
DownloadStart(\'automation_snmp.php?action=export&selected_items=' . gnrv('selected_items') . '\');
});
</script>
<iframe id="download_iframe" style="display:none;"></iframe>';
bottom_footer();
exit;
}
}
header('Location: automation_snmp.php');
exit;
} else {
$ilist = '';
$iarray = [];
// loop through each of the graphs selected on the previous page and get more info about them
foreach ($_POST as $var => $val) {
if (preg_match('/^chk_([0-9]+)$/', $var, $matches)) {
// ================= input validation =================
input_validate_input_number($matches[1], 'chk[1]');
// ====================================================
$ilist .= '<li>' . htmle(db_fetch_cell_prepared('SELECT name FROM automation_snmp WHERE id = ?', [$matches[1]])) . '</li>';
$iarray[] = $matches[1];
}
}
$form_data = [
'general' => [
'page' => 'automation_snmp.php',
'actions' => $actions,
'optvar' => 'drp_action',
'item_array' => $iarray,
'item_list' => $ilist
],
'options' => [
1 => [
'smessage' => __('Click \'Continue\' to Delete the following SNMP Option.'),
'pmessage' => __('Click \'Continue\' to Delete following SNMP Options.'),
'scont' => __('Delete SNMP Option'),
'pcont' => __('Delete SNMP Options')
],
2 => [
'smessage' => __('Click \'Continue\' to Duplicate the following SNMP Option.'),
'pmessage' => __('Click \'Continue\' to Duplicate following SNMP Options.'),
'scont' => __('Duplicate SNMP Option'),
'pcont' => __('Duplicate SNMP Options'),
'extra' => [
'name_format' => [
'method' => 'textbox',
'title' => __('Name Format'),
'default' => '<name> (1)',
'width' => 25
]
]
],
3 => [
'smessage' => __('Click \'Continue\' to Export the following SNMP Option.'),
'pmessage' => __('Click \'Continue\' to Export following SNMP Options.'),
'scont' => __('Export SNMP Option'),
'pcont' => __('Export SNMP Options')
],
]
];
form_continue_confirmation($form_data);
}
}
function automation_duplicate_snmp_option(int $id, string $new_name) : void {
$name = db_fetch_cell_prepared('SELECT name
FROM automation_snmp
WHERE id = ?', [$id]);
$new_name = str_replace('<name>', $name, $new_name);
$save['id'] = 0;
$save['hash'] = generate_hash();
$save['name'] = $new_name;
$newid = sql_save($save, 'automation_snmp');
if ($newid > 0 && $id > 0) {
$hash = get_hash_automation($newid, 'automation_snmp_items');
db_execute_prepared("INSERT INTO automation_snmp_items
(hash, snmp_id, sequence, snmp_version, snmp_community, snmp_port, snmp_timeout,
snmp_retries, max_oids, snmp_username, snmp_password, snmp_auth_protocol,
snmp_priv_passphrase, snmp_priv_protocol, snmp_context, snmp_engine_id)
SELECT ?, $newid AS snmp_id, sequence, snmp_version, snmp_community, snmp_port, snmp_timeout,
snmp_retries, max_oids, snmp_username, snmp_password, snmp_auth_protocol,
snmp_priv_passphrase, snmp_priv_protocol, snmp_context, snmp_engine_id
FROM automation_snmp_items
WHERE snmp_id = ?",
[$hash, $id]);
raise_message('option_duplicated', __('SNMP Options has been Duplicated.'), MESSAGE_LEVEL_INFO);
} else {
raise_message('missing_options', __('Automation Item does not exist. Can not Duplicate.'), MESSAGE_LEVEL_ERROR);
}
}
function automation_snmp_item_dnd() : void {
// ================= Input validation =================
gfrv('id');
// ================= Input validation =================
if (isrv('snmp_item') && is_array(gnrv('snmp_item'))) {
$items = grv('snmp_item');
$sequence = 1;
foreach ($items as $item) {
$item = str_replace('line', '', $item);
input_validate_input_number($item, 'item');
db_execute_prepared('UPDATE automation_snmp_items
SET sequence = ?
WHERE id = ?',
[$sequence, $item]);
$sequence++;
}
}
header('Location: automation_snmp.php?action=edit&id=' . grv('id'));
exit;
}
function automation_snmp_item_movedown() : void {
// ================= input validation =================
gfrv('item_id');
gfrv('id');
// ====================================================
move_item_down('automation_snmp_items', grv('item_id'), 'snmp_id=' . grv('id'));
}
function automation_snmp_item_moveup() : void {
// ================= input validation =================
gfrv('item_id');
gfrv('id');
// ====================================================
move_item_up('automation_snmp_items', grv('item_id'), 'snmp_id=' . grv('id'));
}
function automation_snmp_item_remove_confirm() : void {
// ================= input validation =================
gfrv('id');
gfrv('item_id');
// ====================================================
form_start('automation_snmp.php');
html_start_box('', '100%', false, 3, 'center', '');
$snmp = db_fetch_row_prepared('SELECT * FROM automation_snmp WHERE id = ?', [grv('id')]);
$item = db_fetch_row_prepared('SELECT * FROM automation_snmp_items WHERE id = ?', [grv('item_id')]);
?>
<tr>
<td class='topBoxAlt'>
<p><?php print __('Click \'Continue\' to delete the following SNMP Option Item.'); ?></p>
<p><?php print __('SNMP Option:'); ?> <?php print htmle($snmp['name']); ?><br>
<?php print __('SNMP Version: <b>%s</b>', $item['snmp_version']); ?><br>
<?php print __esc('SNMP Community/Username: <b>%s</b>', ($item['snmp_version'] != 3 ? $item['snmp_community'] : $item['snmp_username'])); ?></p>
</td>
</tr>
<tr>
<td class='right'>
<button type='button' class='ui-button ui-corner-all ui-widget' id='cancel' name='cancel' onClick='$("#cdialog").dialog("close");'><?php print __esc('Cancel'); ?></button>
<button type='button' class='ui-button ui-corner-all ui-widget' id='continue' name='continue' title='<?php print __esc('Remove SNMP Item'); ?>'><?php print __esc('Continue'); ?></button>
</td>
</tr>
<?php
html_end_box();
form_end();
?>
<script type='text/javascript'>
$(function() {
$('#continue').click(function(data) {
var options = {
url: 'automation_snmp.php?action=item_remove',
funcEnd: 'automationSnmpRemoveItemFinalize'
}
var data = {
__csrf_magic: csrfMagicToken,
item_id: <?php print grv('item_id'); ?>,
id: <?php print grv('id'); ?>
}
postUrl(options, data);
});
});
function automationSnmpRemoveItemFinalize(data) {
$('#cdialog').dialog('close');
loadUrl({url:'automation_snmp.php?action=edit&id=<?php print grv('id'); ?>'})
}
</script>
<?php
}
function automation_snmp_item_remove() : void {
// ================= input validation =================
gfrv('item_id');
// ====================================================
db_execute_prepared('DELETE FROM automation_snmp_items WHERE id = ?', [grv('item_id')]);
}
function automation_snmp_item_edit() : void {
global $snmp_auth_protocols, $snmp_priv_protocols, $snmp_versions, $snmp_security_levels;
// require_once(CACTI_PATH_LIBRARY . '/automation_functions.php');
// ================= input validation =================
gfrv('id');
gfrv('item_id');
// ====================================================
// fetch the current mactrack snmp record
$snmp_option = db_fetch_row_prepared('SELECT *
FROM automation_snmp
WHERE id = ?', [grv('id')]);
// if an existing item was requested, fetch data for it
if (grv('item_id', '') !== '') {
$automation_snmp_item = db_fetch_row_prepared('SELECT *
FROM automation_snmp_items
WHERE id = ?', [grv('item_id')]);
$header_label = __esc('SNMP Options [edit: %s]', $snmp_option['name']);
} else {
$header_label = __('SNMP Options [new]');
$automation_snmp_item = [];
$automation_snmp_item['snmp_id'] = grv('id');
$automation_snmp_item['sequence'] = get_sequence(0, 'sequence', 'automation_snmp_items', 'snmp_id=' . grv('id'));
}
form_start('automation_snmp.php', 'automation_item_edit');
html_start_box($header_label, '100%', true, 3, 'center', '');
// this is snmp we are talking about here
unset($snmp_versions[0]);
global $fields_snmp_item_with_retry;
// file: mactrack_snmp.php, action: item_edit
$fields_automation_snmp_item_edit = $fields_snmp_item_with_retry + [
'sequence' => [
'method' => 'view',
'friendly_name' => __('Sequence'),
'description' => __('Sequence of Item.'),
'value' => '|arg1:sequence|'],
];
// drop the legacy MD5/DES SNMPv3 algorithms from the pickers when disabled
$fields_automation_snmp_item_edit['snmp_auth_protocol']['array'] = snmp_auth_protocol_options(isset($automation_snmp_item['snmp_auth_protocol']) ? $automation_snmp_item['snmp_auth_protocol'] : '');
$fields_automation_snmp_item_edit['snmp_priv_protocol']['array'] = snmp_priv_protocol_options(isset($automation_snmp_item['snmp_priv_protocol']) ? $automation_snmp_item['snmp_priv_protocol'] : '');
/* For a new Automation SNMP item the auth/priv defaults come from the global
* setting, which on an upgraded install may still be a legacy MD5/DES value just
* removed from the picker above; default a new item to the strongest available
* option when the legacy algorithms are disabled so it is not left on [None]. */
if (empty($automation_snmp_item['id']) && !snmp_md5_des_enabled()) {
if (!isset($fields_automation_snmp_item_edit['snmp_auth_protocol']['array'][read_config_option('snmp_auth_protocol')])) {
$fields_automation_snmp_item_edit['snmp_auth_protocol']['value'] = 'SHA';
}
if (!isset($fields_automation_snmp_item_edit['snmp_priv_protocol']['array'][read_config_option('snmp_priv_protocol')])) {
$fields_automation_snmp_item_edit['snmp_priv_protocol']['value'] = 'AES';
}
}
draw_edit_form([
'config' => ['no_form_tag' => true],
'fields' => inject_form_variables($fields_automation_snmp_item_edit, $automation_snmp_item)
]);
html_end_box(true, true);
form_hidden_box('item_id', (isrv('item_id') ? grv('item_id') : '0'), '');
form_hidden_box('id', (isset($automation_snmp_item['snmp_id']) ? $automation_snmp_item['snmp_id'] : '0'), '');
form_hidden_box('save_component_automation_snmp_item', '1', '');
form_save_button('automation_snmp.php?action=edit&id=' . grv('id'));
?>
<script type='text/javascript'>
$(function() {
// Need to set this for global snmpv3 functions to remain sane between edits
snmp_security_initialized = false;
setSNMP();
});
</script>
<?php
}
function automation_snmp_edit() : void {
global $fields_automation_snmp_edit;
// ================= input validation =================
gfrv('id');
// ====================================================
// display the mactrack snmp option set
$snmp_option = [];
if (!ierv('id')) {
$snmp_option = db_fetch_row_prepared('SELECT * FROM automation_snmp where id = ?', [grv('id')]);
// setup header
$header_label = __esc('SNMP Option Set [edit: %s]', $snmp_option['name']);
} else {
$header_label = __('SNMP Option Set [new]');
}
form_start('automation_snmp.php', 'automation_snmp_group');
html_start_box($header_label, '100%', true, 3, 'center', '');
// file: automation_snmp.php, action: edit
$fields_automation_snmp_edit = [
'name' => [
'method' => 'textbox',
'friendly_name' => __('Name'),
'description' => __('Fill in the name of this SNMP Option Set.'),
'value' => '|arg1:name|',
'default' => '',
'max_length' => '100',
'size' => '40'
]
];
draw_edit_form([
'config' => ['no_form_tag' => true],
'fields' => inject_form_variables($fields_automation_snmp_edit, $snmp_option)
]);
html_end_box(true, true);
form_hidden_box('id', (isrv('id') ? grv('id') : '0'), '');
form_hidden_box('save_component_automation_snmp', '1', '');
if (!ierv('id')) {
$items = db_fetch_assoc_prepared('SELECT *
FROM automation_snmp_items
WHERE snmp_id = ?
ORDER BY sequence', [grv('id')]);
html_start_box(__('SNMP Options'), '100%', false, 3, 'center', 'automation_snmp.php?action=item_edit&id=' . grv('id'));
$display_text = [
[
'display' => __('Item'),
'align' => 'left'
],
[
'display' => __('Version'),
'align' => 'left'
],
[
'display' => __('Community'),
'align' => 'left'
],
[
'display' => __('Port'),
'align' => 'right'
],
[
'display' => __('Timeout'),
'align' => 'right'
],
[
'display' => __('Retries'),
'align' => 'right'
],
[
'display' => __('Max OIDS'),
'align' => 'right'
],
[
'display' => __('Auth Username'),
'align' => 'left'
],
[
'display' => __('Auth Password'),
'align' => 'left'
],
[
'display' => __('Auth Protocol'),
'align' => 'left'
],
[
'display' => __('Priv Passphrase'),
'align' => 'left'
],
[
'display' => __('Priv Protocol'),
'align' => 'left'
],
[
'display' => __('Context'),
'align' => 'left'
],
[
'display' => __('Action'),
'align' => 'right'
]
];
html_header($display_text);
$i = 1;
$total_items = cacti_sizeof($items);
if (cacti_sizeof($items)) {
foreach ($items as $item) {
form_alternate_row('line' . $item['id'], true);
$form_data = "<td><a class='linkEditMain' href='" . htmle('automation_snmp.php?action=item_edit&item_id=' . $item['id'] . '&id=' . $item['snmp_id']) . "'>" . __('Item # %d', $i) . '</a></td>';
$form_data .= '<td>' . $item['snmp_version'] . '</td>';
$form_data .= '<td class="left">' . ($item['snmp_version'] == 3 ? __('none') : htmle($item['snmp_community'])) . '</td>';
$form_data .= '<td class="right">' . $item['snmp_port'] . '</td>';
$form_data .= '<td class="right">' . $item['snmp_timeout'] . '</td>';
$form_data .= '<td class="right">' . $item['snmp_retries'] . '</td>';
$form_data .= '<td class="right">' . $item['max_oids'] . '</td>';
$form_data .= '<td>' . ($item['snmp_version'] == 3 ? htmle($item['snmp_username']) : __('N/A')) . '</td>';
$form_data .= '<td>' . (($item['snmp_version'] == 3 && $item['snmp_password'] !== '') ? '*********' : __('N/A')) . '</td>';
$form_data .= '<td>' . ($item['snmp_version'] == 3 ? $item['snmp_auth_protocol'] : __('N/A')) . '</td>';
$form_data .= '<td>' . ($item['snmp_version'] == 3 ? '*********' : __('N/A')) . '</td>';
$form_data .= '<td>' . ($item['snmp_version'] == 3 ? $item['snmp_priv_protocol'] : __('N/A')) . '</td>';
$form_data .= '<td>' . ($item['snmp_version'] == 3 ? htmle($item['snmp_context']) : __('N/A')) . '</td>';
$form_data .= '<td class="nowrap right">';
if (read_config_option('drag_and_drop') == '') {
if ($i < $total_items) {
$form_data .= '<a class="pic ti ti-caret-down-filled moveArrow cactiPostAction" href="#" data-url="' . html_escape_url('automation_snmp.php?action=item_movedown&item_id=' . $item['id'] . '&id=' . $item['snmp_id']) . '" title="' . __esc('Move Down') . '"></a>';
} else {
$form_data .= '<span class="moveArrowNone"></span>';
}
if ($i > 1 && $i <= $total_items) {
$form_data .= '<a class="pic ti ti-caret-up-filled moveArrow cactiPostAction" href="#" data-url="' . html_escape_url('automation_snmp.php?action=item_moveup&item_id=' . $item['id'] . '&id=' . $item['snmp_id']) . '" title="' . __esc('Move Up') . '"></a>';
} else {
$form_data .= '<span class="moveArrowNone"></span>';
}
}
$form_data .= '<a class="delete deleteMarker ti ti-x" id="' . $item['id'] . '_' . $item['snmp_id'] . '" title="' . __esc('Delete') . '"></a>';
$form_data .= '</td>';
print $form_data;
form_end_row();
$i++;
}
} else {
print '<tr class="tableRow odd"><td colspan="' . (cacti_sizeof($display_text) + 1) . '"><em>' . __('No SNMP Items') . '</em></td></tr>';
}
html_end_box();
}
form_save_button('automation_snmp.php', 'return');
?>
<script type='text/javascript'>
$(function() {
$('.cdialog').remove();
$('#main').append("<div class='cdialog' id='cdialog'></div>");
$('#automation_snmp_edit2_child').attr('id', 'snmp_item');
$('img.action').click(function() {
strURL = $(this).attr('href');
loadUrl({url:strURL})
});
<?php if (read_config_option('drag_and_drop') == 'on') { ?>
$('#snmp_item').tableDnD({
onDrop: function(table, row) {
loadUrl({url:'automation_snmp.php?action=ajax_dnd&id=<?php isrv('id') ? print grv('id') : print 0; ?>&'+$.tableDnD.serialize()})
}
});
<?php } ?>
$('.delete').click(function (event) {
event.preventDefault();
id = $(this).attr('id').split('_');
request = 'automation_snmp.php?action=item_remove_confirm&item_id='+id[0]+'&id='+id[1];
$.get(request)
.done(function(data) {
$('#cdialog').html(data);
applySkin();
$('#cdialog').dialog({
title: '<?php print __('Delete SNMP Option Item'); ?>',
close: function () { $('.delete').blur(); $('.selectable').removeClass('selected'); },
minHeight: 80,
minWidth: 500
});
})
.fail(function(data) {
getPresentHTTPError(data);
});
}).css('cursor', 'pointer');
});
</script>
<?php
}
function automation_snmp() : void {
global $item_rows, $actions;
// create the page filter
$pageFilter = new CactiTableFilter(__('SNMP Options'), 'automation_snmp.php', 'snmp_form', 'sess_autom_snmp', 'automation_snmp.php?action=edit');
$pageFilter->rows_label = __('Rules');
$pageFilter->has_import = true;
$pageFilter->render();
if (grv('rows') == -1) {
$rows = read_config_option('num_rows_table');
} else {
$rows = grv('rows');
}
// form the 'where' clause for our main sql query
if (grv('filter') != '') {
$sql_where = 'WHERE asnmp.name LIKE ' . db_qstr('%' . grv('filter') . '%');
} else {
$sql_where = '';
}
$total_rows = db_fetch_cell("SELECT
COUNT(DISTINCT asnmp.id)
FROM automation_snmp AS asnmp
LEFT JOIN automation_networks AS anw
ON asnmp.id=anw.snmp_id
LEFT JOIN automation_snmp_items AS asnmpi
ON asnmp.id=asnmpi.snmp_id
$sql_where
GROUP BY asnmp.id");
$sql_order = get_order_string();
$sql_limit = ' LIMIT ' . ($rows * (grv('page') - 1)) . ',' . $rows;
$snmp_options = db_fetch_assoc("SELECT asnmp.*, COUNT(anw.id) AS networks,
COUNT(asnmpi.snmp_id) AS totals,
SUM(CASE WHEN asnmpi.snmp_version=1 THEN 1 ELSE 0 END) AS v1entries,
SUM(CASE WHEN asnmpi.snmp_version=2 THEN 1 ELSE 0 END) AS v2entries,
SUM(CASE WHEN asnmpi.snmp_version=3 THEN 1 ELSE 0 END) AS v3entries
FROM automation_snmp AS asnmp
LEFT JOIN automation_networks AS anw
ON asnmp.id=anw.snmp_id
LEFT JOIN automation_snmp_items AS asnmpi
ON asnmp.id=asnmpi.snmp_id
$sql_where
GROUP BY asnmp.id
$sql_order
$sql_limit");
$nav = html_nav_bar('automation_snmp.php?filter=' . grv('filter'), MAX_DISPLAY_PAGES, grv('page'), $rows, $total_rows, 12, __('SNMP Option Sets'), 'page', 'main');
form_start('automation_snmp.php', 'chk');
print $nav;
html_start_box('', '100%', false, 3, 'center', '');
$display_text = [
'name' => [
'display' => __('SNMP Option Set'),
'align' => 'left',
'sort' => 'ASC'
],
'networks' => [
'display' => __('Networks Using'),
'align' => 'right',
'sort' => 'DESC'
],
'totals' => [
'display' => __('SNMP Entries'),
'align' => 'right',
'sort' => 'DESC'
],
'v1entries' => [
'display' => __('V1 Entries'),
'align' => 'right',
'sort' => 'DESC'
],
'v2entries' => [
'display' => __('V2 Entries'),
'align' => 'right',
'sort' => 'DESC'
],
'v3entries' => [
'display' => __('V3 Entries'),
'align' => 'right',
'sort' => 'DESC'
]
];
html_header_sort_checkbox($display_text, grv('sort_column'), grv('sort_direction'), false);
if (cacti_sizeof($snmp_options)) {
foreach ($snmp_options as $snmp_option) {
form_alternate_row('line' . $snmp_option['id'], true);
form_selectable_cell(filter_value($snmp_option['name'], grv('filter'), 'automation_snmp.php?action=edit&id=' . $snmp_option['id'] . '&page=1'), $snmp_option['id']);
form_selectable_cell($snmp_option['networks'], $snmp_option['id'], '', 'right');
form_selectable_cell($snmp_option['totals'], $snmp_option['id'], '', 'right');
form_selectable_cell($snmp_option['v1entries'], $snmp_option['id'], '', 'right');
form_selectable_cell($snmp_option['v2entries'], $snmp_option['id'], '', 'right');
form_selectable_cell($snmp_option['v3entries'], $snmp_option['id'], '', 'right');
form_checkbox_cell($snmp_option['name'], $snmp_option['id']);
form_end_row();
}
} else {
print '<tr class="tableRow odd"><td colspan="' . (cacti_sizeof($display_text) + 1) . '"><em>' . __('No SNMP Option Sets Found') . '</em></td></tr>';
}
html_end_box(false);
if (cacti_sizeof($snmp_options)) {
print $nav;
}
// draw the dropdown containing a list of available actions for this form
draw_actions_dropdown($actions);
form_end();
}