diff --git a/extras/deploy-scripts/pandora_deploy_community_ubuntu_2204.sh b/extras/deploy-scripts/pandora_deploy_community_ubuntu_2204.sh index c5c8edbb34..1c1ed4b5f8 100644 --- a/extras/deploy-scripts/pandora_deploy_community_ubuntu_2204.sh +++ b/extras/deploy-scripts/pandora_deploy_community_ubuntu_2204.sh @@ -850,6 +850,11 @@ systemctl enable postfix --now &>> "$LOGFILE" systemctl disable --now snmptrapd &>> "$LOGFILE" systemctl disable --now snmptrapd.socket &>> "$LOGFILE" +# Adding legacy to openssl +sed -i '/default = default_sect/a legacy = legacy_sect' /etc/ssl/openssl.cnf +sed -i 's/# activate = 1/activate = 1/' /etc/ssl/openssl.cnf +sed -i '/activate = 1/a [legacy_sect]\nactivate = 1' /etc/ssl/openssl.cnf + #SSH banner [ "$(curl -s ifconfig.me)" ] && ipplublic=$(curl -s ifconfig.me) diff --git a/pandora_agents/pc/Win32/pandora_agent.conf b/pandora_agents/pc/Win32/pandora_agent.conf index 216e3149e3..f1cc960a5c 100644 --- a/pandora_agents/pc/Win32/pandora_agent.conf +++ b/pandora_agents/pc/Win32/pandora_agent.conf @@ -122,6 +122,7 @@ module_min_critical 91 module_max_critical 0 module_end + # Number processes module_begin module_name Number processes diff --git a/pandora_agents/pc/pandora_agent_installer b/pandora_agents/pc/pandora_agent_installer index 7d8de1134d..bcfee3eb00 100644 --- a/pandora_agents/pc/pandora_agent_installer +++ b/pandora_agents/pc/pandora_agent_installer @@ -467,7 +467,7 @@ fi # Script banner at start echo " " -echo "Pandora FMS Agent UNIX Installer $PI_VERSION $PI_BUILD (c) 2008-2015 ArticaST" +echo "Pandora FMS Agent UNIX Installer $PI_VERSION $PI_BUILD (c) 2008-2024 PandoraFMS" echo "This program is licensed under GPL2 Terms. http://pandorafms.com" echo " " diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 4540647ff4..366e1ec0cb 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.775-240212 +Version: 7.0NG.775-240227 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index f1bb519b3a..a0e23e10ee 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.775-240212" +pandora_version="7.0NG.775-240227" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index e32233b28d..bfea44a925 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -1039,7 +1039,7 @@ my $Sem = undef; my $ThreadSem = undef; use constant AGENT_VERSION => '7.0NG.775'; -use constant AGENT_BUILD => '240212'; +use constant AGENT_BUILD => '240227'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 72733d6131..cbd83fc2f1 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -4,7 +4,7 @@ %global __os_install_post %{nil} %define name pandorafms_agent_linux %define version 7.0NG.775 -%define release 240212 +%define release 240227 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.redhat_bin.el8.spec b/pandora_agents/unix/pandora_agent.redhat_bin.el8.spec index 586d2e851e..04b3a359b6 100644 --- a/pandora_agents/unix/pandora_agent.redhat_bin.el8.spec +++ b/pandora_agents/unix/pandora_agent.redhat_bin.el8.spec @@ -5,7 +5,7 @@ %define name pandorafms_agent_linux_bin %define source_name pandorafms_agent_linux %define version 7.0NG.775 -%define release 240212 +%define release 240227 %define debug_package %{nil} Summary: Pandora FMS Linux agent, binary version diff --git a/pandora_agents/unix/pandora_agent.redhat_bin.el9.spec b/pandora_agents/unix/pandora_agent.redhat_bin.el9.spec index 3b7519d4e9..35f3b996c3 100644 --- a/pandora_agents/unix/pandora_agent.redhat_bin.el9.spec +++ b/pandora_agents/unix/pandora_agent.redhat_bin.el9.spec @@ -5,7 +5,7 @@ %define name pandorafms_agent_linux_bin %define source_name pandorafms_agent_linux %define version 7.0NG.775 -%define release 240212 +%define release 240227 %define debug_package %{nil} Summary: Pandora FMS Linux agent, binary version diff --git a/pandora_agents/unix/pandora_agent.redhat_bin.spec b/pandora_agents/unix/pandora_agent.redhat_bin.spec index e4642d5e3b..ed5d2bae39 100644 --- a/pandora_agents/unix/pandora_agent.redhat_bin.spec +++ b/pandora_agents/unix/pandora_agent.redhat_bin.spec @@ -5,7 +5,7 @@ %define name pandorafms_agent_linux_bin %define source_name pandorafms_agent_linux %define version 7.0NG.775 -%define release 240212 +%define release 240227 Summary: Pandora FMS Linux agent, binary version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 596bb71efe..7773cebed3 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -4,7 +4,7 @@ %global __os_install_post %{nil} %define name pandorafms_agent_linux %define version 7.0NG.775 -%define release 240212 +%define release 240227 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index 45b115904a..f0feb34207 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -10,7 +10,7 @@ # ********************************************************************** PI_VERSION="7.0NG.775" -PI_BUILD="240212" +PI_BUILD="240227" OS_NAME=`uname -s` FORCE=0 @@ -579,7 +579,7 @@ fi # Script banner at start echo " " -echo "Pandora FMS Agent UNIX Installer $PI_VERSION $PI_BUILD (c) 2008-2015 ArticaST" +echo "Pandora FMS Agent UNIX Installer $PI_VERSION $PI_BUILD (c) 2008-2024 PandoraFMS" echo "This program is licensed under GPL2 Terms. http://pandorafms.com" echo " " diff --git a/pandora_agents/win32/bin/pandora_agent.conf b/pandora_agents/win32/bin/pandora_agent.conf index 2ff61033c6..d832ba792a 100644 --- a/pandora_agents/win32/bin/pandora_agent.conf +++ b/pandora_agents/win32/bin/pandora_agent.conf @@ -157,8 +157,8 @@ ehorus_conf "C:\Program Files\ehorus_agent\ehorus_agent.conf" module_begin module_name CPU Load module_type generic_data -module_wmiquery SELECT LoadPercentage FROM Win32_Processor -module_wmicolumn LoadPercentage +module_wmiquery SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor where name like '_Total' +module_wmicolumn PercentProcessorTime module_max 100 module_min 0 module_description User CPU Usage (%) @@ -526,7 +526,7 @@ module_plugin "%PROGRAMFILES%\Pandora_Agent\util\autodiscover.exe" --default # Hardening plugin for security compliance analysis. #module_begin -#module_plugin "%PROGRAMFILES%\Pandora_Agent\util\pandora_hardening.exe -t 150" +#module_plugin "%PROGRAMFILES%\Pandora_Agent\util\pandora_hardening.exe" -t 150 #module_absoluteinterval 7d #module_end diff --git a/pandora_agents/win32/bin/util/pandora_hardening.exe b/pandora_agents/win32/bin/util/pandora_hardening.exe index 25776c36b6..f13a1f0a6a 100755 --- a/pandora_agents/win32/bin/util/pandora_hardening.exe +++ b/pandora_agents/win32/bin/util/pandora_hardening.exe @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:db207ef67053764be7e9b42cd04ea5509cc2a023548aab1c037745ca277b68a3 -size 4858753 +oid sha256:520619d823dd5396cc90de59e745d9ab3872d25d85358c9abb4890987b5f5426 +size 4859595 diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index 89f3ebefbc..22dece60e2 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{240212} +{240227} ViewReadme {Yes} diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 69f5bb8200..ed9c1be337 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.775 Build 240212") +#define PANDORA_VERSION ("7.0NG.775 Build 240227") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index 047164560c..65ca2d63d6 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Pandora FMS" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.775(Build 240212))" + VALUE "ProductVersion", "(7.0NG.775(Build 240227))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index 2085adac6e..a7a4d0ecb3 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.775-240212 +Version: 7.0NG.775-240227 Architecture: all Priority: optional Section: admin diff --git a/pandora_console/DEBIAN/make_deb_package.sh b/pandora_console/DEBIAN/make_deb_package.sh index 0a0086ffb2..e163d0f901 100644 --- a/pandora_console/DEBIAN/make_deb_package.sh +++ b/pandora_console/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.775-240212" +pandora_version="7.0NG.775-240227" package_pear=0 package_pandora=1 diff --git a/pandora_console/extensions/agents_modules.php b/pandora_console/extensions/agents_modules.php index 90c9527e55..0b43ce0bba 100644 --- a/pandora_console/extensions/agents_modules.php +++ b/pandora_console/extensions/agents_modules.php @@ -496,6 +496,10 @@ function mainAgentsModules() $agents = []; } + if (isset($agents_id) === false) { + $agents_id = ''; + } + $filter_agents = html_print_label_input_block( __('Agents'), html_print_select( diff --git a/pandora_console/extensions/module_groups.php b/pandora_console/extensions/module_groups.php index 957d3a17a1..15c9e614ee 100644 --- a/pandora_console/extensions/module_groups.php +++ b/pandora_console/extensions/module_groups.php @@ -91,7 +91,7 @@ function mainModuleGroups() $module_group_search = get_parameter('module_group_search', ''); // Check the user's group permissions. - $user_groups = users_get_groups($config['user'], 'AR'); + $user_groups = users_get_groups($config['id_user'], 'AR'); $info = array_filter( $info, function ($v) use ($user_groups) { @@ -112,7 +112,7 @@ function mainModuleGroups() ); if (empty($info) === false) { - $groups_view = ($is_not_paginated) ? $info : array_slice( + $groups_view = (isset($is_not_paginated) === true) ? $info : array_slice( $info, $offset, $config['block_size'] @@ -374,6 +374,10 @@ function mainModuleGroups() '…' ); $j = 1; + if (isset($background_color) === false) { + $background_color = 'none'; + } + if (isset($array_data[$key])) { foreach ($value['gm'] as $k => $v) { if (isset($array_data[$key][$k])) { diff --git a/pandora_console/extensions/quick_shell.php b/pandora_console/extensions/quick_shell.php index 9ea79ba364..d47d65ef56 100644 --- a/pandora_console/extensions/quick_shell.php +++ b/pandora_console/extensions/quick_shell.php @@ -273,6 +273,14 @@ function buildConnectionURL($method) { global $config; + if (isset($config['gotty_ssh_use_ssl']) === false) { + $config['gotty_ssh_use_ssl'] = ''; + } + + if (isset($config['gotty_telnet_use_ssl']) === false) { + $config['gotty_telnet_use_ssl'] = ''; + } + $address = (empty($config['gotty_addr']) === true) ? $_SERVER['SERVER_ADDR'] : $config['gotty_addr']; $use_ssl = ($method === 'ssh') ? $config['gotty_ssh_use_ssl'] : $config['gotty_telnet_use_ssl']; $protocol = ((bool) $use_ssl === true) ? 'https://' : 'http://'; @@ -353,6 +361,18 @@ function quickShellSettings() config_update_value('gotty_telnet_enabled', $gotty_telnet_enabled); } + if (isset($config['gotty_addr']) === false) { + $config['gotty_addr'] = ''; + } + + if (isset($config['gotty_ssh_use_ssl']) === false) { + $config['gotty_ssh_use_ssl'] = ''; + } + + if (isset($config['gotty_telnet_use_ssl']) === false) { + $config['gotty_telnet_use_ssl'] = ''; + } + if ($config['gotty_addr'] != $gotty_addr) { config_update_value('gotty_addr', $gotty_addr); } @@ -389,12 +409,31 @@ function quickShellSettings() $general_table->data = []; $general_table->style = []; $general_table->style[0] = 'width: 50%;'; + if (isset($config['gotty_addr']) === false) { + $config['gotty_addr'] = ''; + } + + if (isset($config['gotty_ssh_enabled']) === false) { + $config['gotty_ssh_enabled'] = ''; + } + + if (isset($config['gotty_ssh_use_ssl']) === false) { + $config['gotty_ssh_use_ssl'] = ''; + } + + if (isset($disable_agentaccess) === false) { + $disable_agentaccess = ''; + } + + if (isset($config['gotty_telnet_use_ssl']) === false) { + $config['gotty_telnet_use_ssl'] = ''; + } $general_table->data[0][] = html_print_label_input_block( __('Address'), html_print_input_text( 'gotty_addr', - $config['gotty_addr'], + ($config['gotty_addr'] ?? ''), '', 30, 100, @@ -443,9 +482,8 @@ function quickShellSettings() html_print_checkbox_switch( 'gotty_ssh_use_ssl', 1, - $config['gotty_ssh_use_ssl'], - true, - $disable_agentaccess + ($config['gotty_ssh_use_ssl'] ?? false), + true ) ); @@ -497,7 +535,7 @@ function quickShellSettings() html_print_checkbox_switch( 'gotty_telnet_use_ssl', 1, - $config['gotty_telnet_use_ssl'], + ($config['gotty_telnet_use_ssl'] ?? false), true ) ); diff --git a/pandora_console/extensions/resource_exportation.php b/pandora_console/extensions/resource_exportation.php deleted file mode 100755 index 476b7ef1bf..0000000000 --- a/pandora_console/extensions/resource_exportation.php +++ /dev/null @@ -1,497 +0,0 @@ -'."\n"; - echo "\n"; - echo '\n"; - if (isset($report['description'])) { - echo '\n"; - } - - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $report['id_group']); - echo '\n"; - $items = db_get_all_rows_field_filter( - 'treport_content', - 'id_report', - $report['id_report'] - ); - foreach ($items as $item) { - echo "\n"; - echo ''.io_safe_output($item['type'])."\n"; - echo ''.io_safe_output($item['description'])."\n"; - echo ''.io_safe_output($item['period'])."\n"; - if ($item['id_agent'] != 0) { - $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); - } - - if ($item['id_agent_module'] != 0) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agent_module']); - $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); - - echo '\n"; - } - - if (isset($agent)) { - echo '\n"; - } - - $agent = null; - switch (io_safe_output($item['type'])) { - case 2: - case 'custom_graph': - case 'automatic_custom_graph': - $graph = db_get_value('name', 'tgraph', 'id_graph', $item['id_gs']); - echo '\n"; - break; - - case 3: - case 'SLA': - echo ''.$item['only_display_wrong']."\n"; - echo ''.$item['monday']."\n"; - echo ''.$item['tuesday']."\n"; - echo ''.$item['wednesday']."\n"; - echo ''.$item['thursday']."\n"; - echo ''.$item['friday']."\n"; - echo ''.$item['saturday']."\n"; - echo ''.$item['sunday']."\n"; - echo ''.$item['time_from']."\n"; - echo ''.$item['time_to']."\n"; - - $slas = db_get_all_rows_field_filter('treport_content_sla_combined', 'id_report_content', $item['id_rc']); - if ($slas === false) { - $slas = []; - } - - foreach ($slas as $sla) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $sla['id_agent_module']); - $agent = db_get_value('alias', 'tagente', 'id_agente', $item['id_agent']); - echo ''; - echo '\n"; - echo '\n"; - echo ''.$sla['sla_max']."\n"; - echo ''.$sla['sla_min']."\n"; - echo ''.$sla['sla_limit']."\n"; - echo ''; - } - break; - - case 'text': - echo '\n"; - break; - - case 'sql': - echo '\n"; - if (!empty($item['external_source'])) { - echo '\n"; - } else { - $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); - echo ''.io_safe_output($sql)."\n"; - } - break; - - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - echo ''.io_safe_output($item['header_definition'])."\n"; - if (!empty($item['external_source'])) { - echo ''.io_safe_output($item['external_source'])."\n"; - } else { - $sql = db_get_value('sql', 'treport_custom_sql', 'id', $item['treport_custom_sql_id']); - echo ''.io_safe_output($sql)."\n"; - } - break; - - case 'event_report_group': - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $item['id_agent']); - echo '\n"; - break; - - case 'url': - echo ''; - break; - - case 'database_serialized': - echo ''; - echo ''; - echo ''; - break; - - case 1: - case 'simple_graph': - case 'simple_baseline_graph': - case 6: - case 'monitor_report': - case 7: - case 'avg_value': - case 8: - case 'max_value': - case 9: - case 'min_value': - case 10: - case 'sumatory': - case 'agent_detailed_event': - case 'event_report_agent': - case 'event_report_module': - case 'alert_report_module': - case 'alert_report_agent': - case 'alert_report_group': - default: - // Do nothing. - break; - } - - echo "\n"; - } - - echo "\n"; -} - - -function output_xml_visual_console($id) -{ - $visual_map = db_get_row('tlayout', 'id', $id); - - echo ''."\n"; - echo "\n"; - echo '\n"; - if ($visual_map['id_group'] != 0) { - $group = db_get_value('nombre', 'tgrupo', 'id_grupo', $visual_map['id_group']); - echo '\n"; - } - - echo '\n"; - echo ''.io_safe_output($visual_map['height'])."\n"; - echo ''.io_safe_output($visual_map['width'])."\n"; - $items = db_get_all_rows_field_filter('tlayout_data', 'id_layout', $visual_map['id']); - if ($items === false) { - $items = []; - } - - foreach ($items as $item) { - echo "\n"; - echo ''.$item['id']."\n"; - // OLD ID USE FOR parent item - $agent = ''; - if ($item['id_agent'] != 0) { - $agent = db_get_value('nombre', 'tagente', 'id_agente', $item['id_agent']); - } - - if (!empty($item['label'])) { - echo '\n"; - } - - echo ''.$item['pos_x']."\n"; - echo ''.$item['pos_y']."\n"; - echo ''.$item['type']."\n"; - if ($item['width'] != 0) { - echo ''.$item['width']."\n"; - } - - if ($item['height'] != 0) { - echo ''.$item['height']."\n"; - } - - if (!empty($item['image'])) { - echo ''.$item['image']."\n"; - } - - if ($item['period'] != 0) { - echo ''.$item['period']."\n"; - } - - if (isset($item['id_agente_modulo'])) { - if ($item['id_agente_modulo'] != 0) { - $module = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); - $id_agent = db_get_value('id_agente', 'tagente_modulo', 'id_agente_modulo', $item['id_agente_modulo']); - $agent = db_get_value('nombre', 'tagente', 'id_agente', $id_agent); - - echo '\n"; - } - } - - if (!empty($agent)) { - echo '\n"; - } - - if ($item['id_layout_linked'] != 0) { - echo ''.$item['id_layout_linked']."\n"; - } - - if ($item['parent_item'] != 0) { - echo ''.$item['parent_item']."\n"; - } - - if (!empty($item['clock_animation'])) { - echo ''.$item['clock_animation']."\n"; - } - - if (!empty($item['fill_color'])) { - echo ''.$item['fill_color']."\n"; - } - - if (!empty($item['type_graph'])) { - echo ''.$item['type_graph']."\n"; - } - - if (!empty($item['time_format'])) { - echo ''.$item['time_format']."\n"; - } - - if (!empty($item['timezone'])) { - echo ''.$item['timezone']."\n"; - } - - if (!empty($item['border_width'])) { - echo ''.$item['border_width']."\n"; - } - - if (!empty($item['border_color'])) { - echo ''.$item['border_color']."\n"; - } - - echo "\n"; - } - - echo "\n"; -} - - -function get_name_xml_resource($hook_enterprise) -{ - global $config; - - $type = get_parameter('type'); - $id = (int) get_parameter('id'); - - switch ($type) { - case 'report': - $name = db_get_value('name', 'treport', 'id_report', $id); - break; - - case 'visual_console': - $name = db_get_value('name', 'tlayout', 'id', $id); - break; - - default: - if ($hook_enterprise === true) { - return enterprise_get_name_xml_resource($type, $id); - } - break; - } - - $file = io_safe_output($name).'.ptr'; - - return $file; -} - - -function get_xml_resource() -{ - global $config; - - $hook_enterprise = enterprise_include('extensions/resource_exportation/functions.php'); -} - - -function resource_exportation_extension_main() -{ - global $config; - - check_login(); - - if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { - db_pandora_audit( - AUDIT_LOG_ACL_VIOLATION, - 'Trying to access Setup Management' - ); - include 'general/noaccess.php'; - return; - } - - $hook_enterprise = enterprise_include('extensions/resource_exportation/functions.php'); - - ui_print_standard_header( - __('Resource exportation'), - 'images/extensions.png', - false, - '', - true, - [], - [ - [ - 'link' => '', - 'label' => __('Resources'), - ], - [ - 'link' => '', - 'label' => __('Resource exporting'), - ], - ] - ); - - ui_print_warning_message( - __('This extension makes exportation of resource template more easy.').'
'.__('You can export resource templates in .ptr format.') - ); - - $table = new stdClass(); - $table->class = 'databox filter-table-adv'; - $table->id = 'resource_exportation_table'; - $table->style = []; - $table->style[0] = 'width: 30%'; - $table->style[1] = 'vertical-align: bottom;'; - $table->data = []; - $table->data[0][] = html_print_label_input_block( - __('Report'), - html_print_div( - [ - 'class' => 'flex-content-left', - 'content' => html_print_select_from_sql('SELECT id_report, name FROM treport', 'report', '', '', '', 0, true), - ], - true - ) - ); - $table->data[0][] = html_print_button(__('Export'), '', false, 'export_to_ptr("report");', '', true); - - $table->data[1][] = html_print_label_input_block( - __('Visual console'), - html_print_div( - [ - 'class' => 'flex-content-left', - 'content' => html_print_select_from_sql('SELECT id, name FROM tlayout', 'visual_console', '', '', '', 0, true), - ], - true - ) - ); - $table->data[1][] = html_print_button(__('Export'), '', false, 'export_to_ptr("visual_console");', '', true); - - if ($hook_enterprise === true) { - add_rows_for_enterprise($table->data); - } - - html_print_table($table); - - ?> - - $name) { - $values['id_report'] = $id; - $result = (bool) db_process_sql_insert('treport_content', $values); - - ui_print_result_message( - $result, - sprintf( - __("Success add '%s' item in report '%s'."), - $values['type'], - $name - ), - sprintf( - __("Error create '%s' item in report '%s'."), - $values['type'], - $name - ) - ); - } -} - - -function process_upload_xml_report($xml, $group_filter=0) -{ - foreach ($xml->xpath('/report') as $reportElement) { - $values = []; - - if (isset($reportElement->name)) { - $values['name'] = $reportElement->name; - - $posible_name = $values['name']; - $exist = true; - $loops = 30; - // Loops to exit or tries. - while ($exist && $loops > 0) { - $exist = (bool) db_get_row_filter( - 'treport', - ['name' => io_safe_input($posible_name)] - ); - - if ($exist) { - $loops--; - $posible_name = $values['name'].' ('.(30 - $loops).')'; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' report, the name exist and there aren't free name."), - $reportElement->name - ) - ); - break; - } else if ($loops != 30) { - ui_print_warning_message( - sprintf( - __("Warning create '%s' report, the name exist, the report have a name %s."), - $reportElement->name, - $posible_name - ) - ); - } - - $values['name'] = io_safe_input($posible_name); - } else { - ui_print_error_message(__("Error the report haven't name.")); - break; - } - - if (isset($reportElement->group) === true - && empty($reportElement->group) === false - ) { - $id_group = db_get_value( - 'id_grupo', - 'tgrupo', - 'nombre', - $reportElement->group - ); - if ($id_group === false) { - ui_print_error_message(__("Error the report haven't group.")); - break; - } - } - - if (isset($reportElement->description) === true) { - $values['description'] = $reportElement->description; - } - - $id_report = db_process_sql_insert('treport', $values); - - ui_print_result_message( - $id_report, - sprintf(__("Success create '%s' report."), $posible_name), - sprintf(__("Error create '%s' report."), $posible_name) - ); - - if ($id_report) { - db_pandora_audit( - AUDIT_LOG_REPORT_MANAGEMENT, - 'Create report '.$id_report, - false, - false - ); - } else { - db_pandora_audit( - AUDIT_LOG_REPORT_MANAGEMENT, - 'Fail to create report', - false, - false - ); - break; - } - - foreach ($reportElement->item as $item) { - $item = (array) $item; - - $values = []; - $values['id_report'] = $id_report; - if (isset($item['description']) === true) { - $values['description'] = io_safe_input($item['description']); - } - - if (isset($item['period']) === true) { - $values['period'] = io_safe_input($item['period']); - } - - if (isset($item['type']) === true) { - $values['type'] = io_safe_input($item['type']); - } - - $agents_item = []; - if (isset($item['agent']) === true) { - $agents = agents_get_agents( - ['id_grupo' => $group_filter], - [ - 'id_agente', - 'alias', - ] - ); - - $agent_clean = str_replace( - [ - '[', - ']', - ], - '', - io_safe_output($item['agent']) - ); - $regular_expresion = ($agent_clean != $item['agent']); - - foreach ($agents as $agent) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['alias']))) { - $agents_item[$agent['id_agente']]['name'] = $agent['alias']; - } - } else { - if ($agent_clean == io_safe_output($agent['alias'])) { - $agents_item[$agent['id_agente']]['name'] = $agent['alias']; - } - } - } - } - - if (isset($item['module']) === true) { - $module_clean = str_replace(['[', ']'], '', $item['module']); - $regular_expresion = ($module_clean != $item['module']); - - foreach ($agents_item as $id => $agent) { - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - $agents_item[$id]['modules'] = []; - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $agents_item[$id]['modules'][$module['id_agente_modulo']]['name'] = $module['nombre']; - } - } - } - } - } - - switch ($item['type']) { - case 2: - case 'custom_graph': - case 'automatic_custom_graph': - $group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item['graph'])); - $values['id_gs'] = $group; - break; - - case 3: - case 'SLA': - if (isset($item['only_display_wrong'])) { - $values['only_display_wrong'] = (string) $item['only_display_wrong']; - } - - if (isset($item['monday'])) { - $values['monday'] = (string) $item['monday']; - } - - if (isset($item['tuesday'])) { - $values['tuesday'] = (string) $item['tuesday']; - } - - if (isset($item['wednesday'])) { - $values['wednesday'] = (string) $item['wednesday']; - } - - if (isset($item['thursday'])) { - $values['thursday'] = (string) $item['thursday']; - } - - if (isset($item['friday'])) { - $values['friday'] = (string) $item['friday']; - } - - if (isset($item['saturday'])) { - $values['saturday'] = (string) $item['saturday']; - } - - if (isset($item['sunday'])) { - $values['sunday'] = (string) $item['sunday']; - } - - if (isset($item['time_from'])) { - $values['time_from'] = (string) $item['time_from']; - } - - if (isset($item['time_to'])) { - $values['time_to'] = (string) $item['time_to']; - } - - $slas = []; - if (!isset($item['sla'])) { - $item['sla'] = []; - } - - foreach ($item['sla'] as $sla_xml) { - if (isset($sla_xml->agent)) { - $agents = agents_get_agents(['id_grupo' => $group_filter], ['id_agente', 'nombre']); - - $agent_clean = str_replace(['[', ']'], '', $sla_xml->agent); - $regular_expresion = ($agent_clean != $sla_xml->agent); - - foreach ($agents as $agent) { - $id_agent = false; - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent['nombre']))) { - $id_agent = $agent['id_agente']; - } else { - if ($agent_clean == io_safe_output($agent['nombre'])) { - $id_agent = $agent['id_agente']; - } - } - } - - if ($id_agent) { - if (isset($sla_xml->module)) { - $module_clean = str_replace(['[', ']'], '', $sla_xml->module); - $regular_expresion = ($module_clean != $sla_xml->module); - - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id_agent], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $slas[] = [ - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string) $sla_xml->sla_max, - 'sla_min' => (string) $sla_xml->sla_min, - 'sla_limit' => (string) $sla_xml->sla_limit, - ]; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $slas[] = [ - 'id_agent_module' => $module['id_agente_modulo'], - 'sla_max' => (string) $sla_xml->sla_max, - 'sla_min' => (string) $sla_xml->sla_min, - 'sla_limit' => (string) $sla_xml->sla_limit, - ]; - } - } - } - } - } - } - } - } - break; - - case 'text': - $values['text'] = io_safe_input($item['text']); - break; - - case 'sql': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - - case 'sql_graph_pie': - case 'sql_graph_vbar': - case 'sql_graph_hbar': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['external_source'] = io_safe_input($item['sql']); - break; - - case 'event_report_group': - $values['id_agent'] = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($item->group)); - break; - - case 'url': - $values['external_source'] = io_safe_input($item['url']); - break; - - case 'database_serialized': - $values['header_definition'] = io_safe_input($item['header_definition']); - $values['line_separator'] = io_safe_input($item['line_separator']); - $values['column_separator'] = io_safe_input($item['column_separator']); - break; - - case 1: - case 'simple_graph': - case 'simple_baseline_graph': - case 6: - case 'monitor_report': - case 7: - case 'avg_value': - case 8: - case 'max_value': - case 9: - case 'min_value': - case 10: - case 'sumatory': - case 'event_report_module': - case 'alert_report_module': - case 'alert_report_agent': - case 'alert_report_group': - case 'agent_detailed_event': - case 'event_report_agent': - default: - // Do nothing. - break; - } - - if (empty($agents_item) === true) { - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - - if ($item['type'] == 'SLA') { - foreach ($slas as $sla) { - $sla['id_report_content'] = $id_content; - $result = db_process_sql_insert('treport_content_sla_combined', $sla); - ui_print_result_message( - $result, - sprintf(__("Success add '%s' SLA."), $sla['id_agent_module']), - sprintf(__("Error add '%s' SLA."), $sla['id_agent_module']) - ); - } - } - } else { - foreach ($agents_item as $id_agent => $agent) { - if (empty($agent['modules'])) { - $values['id_agent'] = $id_agent; - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - } else { - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent_module'] = $id_module; - $values['id_agent'] = $id_agent; - - $id_content = db_process_sql_insert('treport_content', $values); - ui_print_result_message( - $id_content, - sprintf(__("Success add '%s' content."), $values['type']), - sprintf(__("Error add '%s' action."), $values['type']) - ); - } - } - } - } - } - } -} - - -function process_upload_xml_visualmap($xml, $filter_group=0) -{ - global $config; - - foreach ($xml->xpath('/visual_map') as $visual_map) { - if (isset($visual_map->name)) { - $values['name'] = (string) $visual_map->name; - } else { - ui_print_error_message( - __("Error create '%s' visual map, lost tag name.") - ); - break; - } - - $values['id_group'] = 0; - if (isset($visual_map->group)) { - $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($visual_map->group)); - if ($id_group !== false) { - $values['id_group'] = $id_group; - } - } - - if (isset($visual_map->background)) { - $values['background'] = (string) $visual_map->background; - } - - $values['width'] = 0; - if (isset($visual_map->width)) { - $values['width'] = (string) $visual_map->width; - } - - $values['height'] = 0; - if (isset($visual_map->height)) { - $values['height'] = (string) $visual_map->height; - } - - $posible_name = $values['name']; - $exist = true; - $loops = 30; - // Loops to exit or tries - while ($exist && $loops > 0) { - $exist = (bool) db_get_row_filter('tlayout', ['name' => io_safe_input($posible_name)]); - - if ($exist) { - $loops--; - $posible_name = $values['name'].' ('.(30 - $loops).')'; - } - } - - if ($exist) { - ui_print_error_message( - sprintf( - __("Error create '%s' visual map, the name exist and there aren't free name."), - $values['name'] - ) - ); - continue; - } else if ($loops != 30) { - ui_print_error_message( - sprintf( - __("Warning create '%s' visual map, the name exist, the report have a name %s."), - $values['name'], - $posible_name - ) - ); - } - - $values['name'] = io_safe_input($posible_name); - $id_visual_map = db_process_sql_insert('tlayout', $values); - - ui_print_result_message( - (bool) $id_visual_map, - sprintf(__("Success create '%s' visual map."), $posible_name), - sprintf(__("Error create '%s' visual map."), $posible_name) - ); - - if ($id_visual_map !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Visual Console #%s', $id_visual_map), - $config['id_user'] - ); - } else { - break; - } - - $relation_other_ids = []; - - foreach ($visual_map->item as $item) { - $no_agents = true; - - if (isset($item->agent)) { - $agent_clean = str_replace(['[', ']'], '', $item->agent); - $regular_expresion = ($agent_clean != $item->agent); - - $agents = agents_get_agents(['id_grupo' => $filter_group], ['id_agente', 'nombre']); - if ($agents === false) { - $agents = []; - } - - $temp = []; - foreach ($agents as $agent) { - $temp[$agent['id_agente']] = $agent['nombre']; - } - - $agents = $temp; - - $agents_in_item = []; - foreach ($agents as $id => $agent) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$agent_clean.'/', io_safe_output($agent))) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - } - } else { - if ($agent_clean == io_safe_output($agent)) { - $agents_in_item[$id]['name'] = $agent; - $no_agents = false; - break; - } - } - } - } - - $no_modules = true; - if (isset($item->module)) { - $module_clean = str_replace(['[', ']'], '', $item->module); - $regular_expresion = ($module_clean != $item->module); - - foreach ($agents_in_item as $id => $agent) { - $modules = db_get_all_rows_filter( - 'tagente_modulo', - ['id_agente' => $id], - [ - 'id_agente_modulo', - 'nombre', - ] - ); - - $modules_in_item = []; - foreach ($modules as $module) { - if ($regular_expresion) { - if ((bool) preg_match('/'.$module_clean.'/', io_safe_output($module['nombre']))) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - } - } else { - if ($module_clean == io_safe_output($module['nombre'])) { - $modules_in_item[$module['id_agente_modulo']] = $module['nombre']; - $no_modules = false; - break; - } - } - } - - $agents_in_item[$id]['modules'] = $modules_in_item; - } - } - - $values = []; - - $values['id_layout'] = $id_visual_map; - if (isset($item->label)) { - $values['label'] = io_safe_input($item->label); - } - - if (isset($item->x)) { - $values['pos_x'] = (string) $item->x; - } - - if (isset($item->y)) { - $values['pos_y'] = (string) $item->y; - } - - if (isset($item->height)) { - $values['height'] = (string) $item->height; - } - - if (isset($item->width)) { - $values['width'] = (string) $item->width; - } - - if (isset($item->image)) { - $values['image'] = (string) $item->image; - } - - if (isset($item->period)) { - $values['period'] = (string) $item->period; - } - - if (isset($item->parent_item)) { - // Hack for link the items use the OTHER_ID - // and have too OTHER_ID - // then $relation_other_ids[OTHER_ID] have the item_id in DB. - $values['parent_item'] = (string) $relation_other_ids[(string) $item->parent_item]; - } - - if (isset($item->map_linked)) { - $values['id_layout_linked'] = (string) $item->map_linked; - } - - if (isset($item->type)) { - $values['type'] = (string) $item->type; - } - - if (isset($item->clock_animation)) { - $values['clock_animation'] = (string) $item->clock_animation; - } - - if (isset($item->fill_color)) { - $values['fill_color'] = (string) $item->fill_color; - } - - if (isset($item->type_graph)) { - $values['type_graph'] = (string) $item->type_graph; - } - - if (isset($item->time_format)) { - $values['time_format'] = (string) $item->time_format; - } - - if (isset($item->timezone)) { - $values['timezone'] = (string) $item->timezone; - } - - if (isset($item->border_width)) { - $values['border_width'] = (string) $item->border_width; - } - - if (isset($item->border_color)) { - $values['border_color'] = (string) $item->border_color; - } - - if ($no_agents) { - $id_item = db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item type '%d' visual map."), $values['type']), - sprintf(__("Error create item type '%d' visual map."), $values['type']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } else { - foreach ($agents_in_item as $id => $agent) { - if ($no_modules) { - $values['id_agent'] = $id; - - $id_item = db_process_sql_insert('tlayout_data', $values); - - if (isset($item->other_id) === true) { - $relation_other_ids[(string) $item->other_id] = $id_item; - } - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } else { - // TODO: Review this else. - foreach ($agent['modules'] as $id_module => $module) { - $values['id_agent'] = $id; - $values['id_agente_modulo'] = $id_module; - - db_process_sql_insert('tlayout_data', $values); - - ui_print_result_message( - (bool) $id_item, - sprintf(__("Success create item for agent '%s' visual map."), $agent['name']), - sprintf(__("Error create item for agent '%s' visual map."), $agent['name']) - ); - - if ($id_item !== false) { - db_pandora_audit( - AUDIT_LOG_VISUAL_CONSOLE_MANAGEMENT, - sprintf('Create Item %s in Visual Console #%s', $id_item, $values['id_layout']), - $config['id_user'] - ); - } - } - } - } - } - } - } -} - - -function process_upload_xml_component($xml) -{ - // Extract components. - $components = []; - foreach ($xml->xpath('/component') as $componentElement) { - $name = io_safe_input((string) $componentElement->name); - $id_os = (int) $componentElement->id_os; - $os_version = io_safe_input((string) $componentElement->os_version); - $data = io_safe_input((string) $componentElement->data); - $type = (int) $componentElement->type; - $group = (int) $componentElement->group; - $description = io_safe_input((string) $componentElement->description); - $module_interval = (int) $componentElement->module_interval; - $max = (float) $componentElement->max; - $min = (float) $componentElement->min; - $tcp_send = io_safe_input((string) $componentElement->tcp_send); - $tcp_rcv_text = io_safe_input((string) $componentElement->tcp_rcv_text); - $tcp_port = (int) $componentElement->tcp_port; - $snmp_oid = io_safe_input((string) $componentElement->snmp_oid); - $snmp_community = io_safe_input((string) $componentElement->snmp_community); - $id_module_group = (int) $componentElement->id_module_group; - $module_source = (int) $componentElement->module_source; - $plugin = (int) $componentElement->plugin; - $plugin_username = io_safe_input((string) $componentElement->plugin_username); - $plugin_password = io_safe_input((string) $componentElement->plugin_password); - $plugin_parameters = io_safe_input((string) $componentElement->plugin_parameters); - $max_timeout = (int) $componentElement->max_timeout; - $max_retries = (int) $componentElement->max_retries; - $historical_data = (int) $componentElement->historical_data; - $dynamic_interval = (int) $componentElement->dynamic_interval; - $dynamic_min = (int) $componentElement->dynamic_min; - $dynamic_max = (int) $componentElement->dynamic_max; - $dynamic_two_tailed = (int) $componentElement->dynamic_two_tailed; - $min_war = (float) $componentElement->min_war; - $max_war = (float) $componentElement->max_war; - $str_war = (string) $componentElement->str_war; - $min_cri = (float) $componentElement->min_cri; - $max_cri = (float) $componentElement->max_cri; - $str_cri = (string) $componentElement->str_cri; - $ff_treshold = (int) $componentElement->ff_treshold; - $snmp_version = (int) $componentElement->snmp_version; - $auth_user = io_safe_input((string) $componentElement->auth_user); - $auth_password = io_safe_input((string) $componentElement->auth_password); - $auth_method = io_safe_input((string) $componentElement->auth_method); - $privacy_method = io_safe_input((string) $componentElement->privacy_method); - $privacy_pass = io_safe_input((string) $componentElement->privacy_pass); - $security_level = io_safe_input((string) $componentElement->security_level); - $wmi_query = io_safe_input((string) $componentElement->wmi_query); - $key_string = io_safe_input((string) $componentElement->key_string); - $field_number = (int) $componentElement->field_number; - $namespace = io_safe_input((string) $componentElement->namespace); - $wmi_user = io_safe_input((string) $componentElement->wmi_user); - $wmi_password = io_safe_input((string) $componentElement->wmi_password); - $post_process = io_safe_input((float) $componentElement->post_process); - - $idComponent = false; - switch ((int) $componentElement->module_source) { - case 1: - // Local component. - $values = [ - 'description' => $description, - 'id_network_component_group' => $group, - 'os_version' => $os_version, - ]; - $return = enterprise_hook('local_components_create_local_component', [$name, $data, $id_os, $values]); - if ($return !== ENTERPRISE_NOT_HOOK) { - $idComponent = $return; - } - break; - - case 2: - // Network component - // for modules - // 15 = remote_snmp, 16 = remote_snmp_inc, - // 17 = remote_snmp_string, 18 = remote_snmp_proc. - $custom_string_1 = ''; - $custom_string_2 = ''; - $custom_string_3 = ''; - if ($type >= 15 && $type <= 18) { - // New support for snmp v3. - $tcp_send = $snmp_version; - $plugin_user = $auth_user; - $plugin_pass = $auth_password; - $plugin_parameters = $auth_method; - $custom_string_1 = $privacy_method; - $custom_string_2 = $privacy_pass; - $custom_string_3 = $security_level; - } - - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 4: - // Plugin component. - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $tcp_send, - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $tcp_port, - 'snmp_oid' => $snmp_oid, - 'snmp_community' => $snmp_community, - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $plugin_username, - 'plugin_pass' => $plugin_password, - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 6: - // WMI component. - $idComponent = network_components_create_network_component( - $name, - $type, - $group, - [ - 'description' => $description, - 'module_interval' => $module_interval, - 'max' => $max, - 'min' => $min, - 'tcp_send' => $namespace, - // work around - 'tcp_rcv' => $tcp_rcv_text, - 'tcp_port' => $field_number, - // work around - 'snmp_oid' => $wmi_query, - // work around - 'snmp_community' => $key_string, - // work around - 'id_module_group' => $id_module_group, - 'id_modulo' => $module_source, - 'id_plugin' => $plugin, - 'plugin_user' => $wmi_user, - // work around - 'plugin_pass' => $wmi_password, - // work around - 'plugin_parameter' => $plugin_parameters, - 'max_timeout' => $max_timeout, - 'max_retries' => $max_retries, - 'history_data' => $historical_data, - 'dynamic_interval' => $dynamic_interval, - 'dynamic_min' => $dynamic_min, - 'dynamic_max' => $dynamic_max, - 'dynamic_two_tailed' => $dynamic_two_tailed, - 'min_warning' => $min_war, - 'max_warning' => $max_war, - 'str_warning' => $str_war, - 'min_critical' => $min_cri, - 'max_critical' => $max_cri, - 'str_critical' => $str_cri, - 'min_ff_event' => $ff_treshold, - 'custom_string_1' => $custom_string_1, - 'custom_string_2' => $custom_string_2, - 'custom_string_3' => $custom_string_3, - 'post_process' => $post_process, - ] - ); - if ((bool) $idComponent === true) { - $components[] = $idComponent; - } - break; - - case 5: - // Prediction component. - case 7: - // Web component. - default: - // Do nothing. - break; - } - - ui_print_result_message( - (bool) $idComponent, - sprintf(__("Success create '%s' component."), $name), - sprintf(__("Error create '%s' component."), $name) - ); - } - - // Extract the template. - $templateElement = $xml->xpath('//template'); - if (empty($templateElement) === false) { - $templateElement = $templateElement[0]; - - $templateName = (string) $templateElement->name; - $templateDescription = (string) $templateElement->description; - - $idTemplate = db_process_sql_insert('tnetwork_profile', ['name' => $templateName, 'description' => $templateDescription]); - - $result = false; - if ((bool) $idTemplate) { - foreach ($components as $idComponent) { - db_process_sql_insert('tnetwork_profile_component', ['id_nc' => $idComponent, 'id_np' => $idTemplate]); - } - } - } -} - - -function process_upload_xml($xml) -{ - $hook_enterprise = enterprise_include('extensions/resource_registration/functions.php'); - - // Extract component. - process_upload_xml_component($xml); - - $group_filter = get_parameter('group'); - - // Extract visual map. - process_upload_xml_visualmap($xml, $group_filter); - - // Extract policies. - if ($hook_enterprise === true) { - $centralized_management = is_management_allowed(); - if ($centralized_management === true) { - process_upload_xml_policy($xml, $group_filter); - } - } - - // Extract reports. - process_upload_xml_report($xml, $group_filter); -} - - -function resource_registration_extension_main() -{ - global $config; - - if (! check_acl($config['id_user'], 0, 'PM') && ! is_user_admin($config['id_user'])) { - db_pandora_audit( - AUDIT_LOG_ACL_VIOLATION, - 'Trying to access Setup Management' - ); - include 'general/noaccess.php'; - return; - } - - include_once $config['homedir'].'/include/functions_network_components.php'; - include_once $config['homedir'].'/include/functions_db.php'; - enterprise_include_once('include/functions_local_components.php'); - - ui_print_standard_header( - __('Resource registration'), - 'images/extensions.png', - false, - '', - true, - [], - [ - [ - 'link' => '', - 'label' => __('Resources'), - ], - [ - 'link' => '', - 'label' => __('Resource registration'), - ], - ] - ); - - if (extension_loaded('libxml') === false) { - ui_print_error_message(_('Error, please install the PHP libXML in the system.')); - - return; - } - - if (is_management_allowed() === false) { - if (is_metaconsole() === false) { - $url = ''.__('metaconsole').''; - } else { - $url = __('any node'); - } - - ui_print_warning_message( - __( - 'This node is configured with centralized mode. Go to %s to create a policy.', - $url - ) - ); - - return; - } - - ui_print_warning_message( - __('This extension makes registering resource templates easier.').'
'.__('Here you can upload a resource template in .ptr format.').'
'.__('Please refer to our documentation for more information on how to obtain and use %s resources.', get_product_name()).' '.'

'.__('You can get more resurces in our Public Resource Library') - ); - - $table = new stdClass(); - $table->class = 'databox filter-table-adv'; - $table->id = 'resource_registration_table'; - - $table->data = []; - - $table->data[0][] = html_print_label_input_block( - __('File to upload'), - html_print_input_file('resource_upload', true) - ); - - $table->data[0][] = html_print_label_input_block( - __('Group filter'), - html_print_select_groups(false, 'AW', true, 'group', '', '', __('All'), 0, true) - ); - - // Upload form. - echo '
'; - html_print_table($table); - html_print_action_buttons( - html_print_submit_button( - __('Upload'), - 'upload', - false, - [ 'icon' => 'wand' ], - true - ), - ['type' => 'form_action'] - ); - echo '
'; - /* - echo ''; - echo ''; - echo "'; - echo ''; - echo "'; - echo '
"; - echo ''.__('Group filter: ').''; - html_print_select_groups(false, 'AW', true, 'group'); - echo '"; - echo '
';*/ - - if (isset($_FILES['resource_upload']['tmp_name']) === false) { - return; - } - - $xml = simplexml_load_file($_FILES['resource_upload']['tmp_name'], null, LIBXML_NOCDATA); - - if ($xml === false) { - ui_print_error_message( - __('Error uploading resource. Check if the selected file is a valid resource template in .ptr format') - ); - } else { - process_upload_xml($xml); - } -} - - -extensions_add_godmode_menu_option(__('Resource registration'), 'PM', 'gagente', '', 'v1r1'); -extensions_add_godmode_function('resource_registration_extension_main'); diff --git a/pandora_console/extensions/users_connected.php b/pandora_console/extensions/users_connected.php index 4b76957344..712dcd014d 100644 --- a/pandora_console/extensions/users_connected.php +++ b/pandora_console/extensions/users_connected.php @@ -229,7 +229,7 @@ function users_extension_main_god($god=true) $data = []; $data[0] = ''.$row['id_user'].''; - $data[1] = $last_login_data['ip_origin']; + $data[1] = $last_login_data['ip_origen']; $data[2] = date($config['date_format'], $last_login_data['utimestamp']); $data[3] = date($config['date_format'], $row['last_connect']); array_push($table->data, $data); diff --git a/pandora_console/extras/delete_files/delete_files.txt b/pandora_console/extras/delete_files/delete_files.txt index f3eada8070..b3fbea46dd 100644 --- a/pandora_console/extras/delete_files/delete_files.txt +++ b/pandora_console/extras/delete_files/delete_files.txt @@ -1736,3 +1736,5 @@ extensions/files_repo/sql/files_repo.oracle.sql extensions/files_repo/sql/files_repo.postgreSQL.sql extensions/files_repo/sql/files_repo.sql extensions/files_repo +extensions/resource_exportation.php +extensions/resource_registration.php diff --git a/pandora_console/extras/discovery/DiscoveryApplicationsMigrateCodes.ini b/pandora_console/extras/discovery/DiscoveryApplicationsMigrateCodes.ini index d05611a6b5..ea136c996c 100644 --- a/pandora_console/extras/discovery/DiscoveryApplicationsMigrateCodes.ini +++ b/pandora_console/extras/discovery/DiscoveryApplicationsMigrateCodes.ini @@ -1,5 +1,5 @@ pandorafms.vmware=248788e0fb2cd4e11623e4a52ee7d05b -pandorafms.mysql=fadb4750d18285c0eca34f47c6aa3cfe +pandorafms.mysql=ca7dd8b80a1a03a25eb0fb077818ad63 pandorafms.mssql=1cc215409741d19080269ffba112810e pandorafms.oracle=abdfd7280f76276f696115cabdac731e pandorafms.db2=122f2abff0ec1d668c35ee0911483021 diff --git a/pandora_console/extras/mr/68.sql b/pandora_console/extras/mr/68.sql index 9fdf9ffea3..48eeed226c 100644 --- a/pandora_console/extras/mr/68.sql +++ b/pandora_console/extras/mr/68.sql @@ -12,6 +12,15 @@ CREATE TABLE IF NOT EXISTS `ttoken` ( FOREIGN KEY (`id_user`) REFERENCES `tusuario` (`id_user`) ON DELETE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET=UTF8MB4; +-- Watch out! The following field migration must be done before altering the corresponding table. +UPDATE `tevent_filter` +SET `search` = `regex`, + `regex` = '1' +WHERE `regex` IS NOT NULL AND `regex` != ''; + +-- Watch out! The following alter command must be done after the previous update of this table. +ALTER TABLE `tevent_filter` MODIFY COLUMN `regex` TINYINT unsigned NOT NULL DEFAULT 0; + CREATE TABLE IF NOT EXISTS `tmerge_error` ( `id` int(10) NOT NULL auto_increment, `id_node` int(10) default 0, @@ -65,14 +74,59 @@ ADD COLUMN `id_agent_data` int not null default 0 AFTER `script_type`; ALTER TABLE `tusuario` CHANGE COLUMN `metaconsole_data_section` `metaconsole_data_section` TEXT NOT NULL DEFAULT '' ; ALTER TABLE `tmensajes` ADD COLUMN `icon_notification` VARCHAR(250) NULL DEFAULT NULL AFTER `url`; +ALTER TABLE `tagente_modulo` ADD COLUMN `disabled_by_safe_mode` TINYINT UNSIGNED NOT NULL DEFAULT 0; + UPDATE `tncm_template` SET `vendors` = CONCAT('["', TRIM(BOTH '"' FROM TRIM(BOTH ']' FROM TRIM(BOTH '[' FROM vendors))), '"]'), `models` = CONCAT('["', TRIM(BOTH '"' FROM TRIM(BOTH ']' FROM TRIM(BOTH '[' FROM models))), '"]'); UPDATE `tncm_agent_data_template` SET `vendors` = CONCAT('["', TRIM(BOTH '"' FROM TRIM(BOTH ']' FROM TRIM(BOTH '[' FROM vendors))), '"]'), `models` = CONCAT('["', TRIM(BOTH '"' FROM TRIM(BOTH ']' FROM TRIM(BOTH '[' FROM models))), '"]'); -- Update version for plugin oracle UPDATE `tdiscovery_apps` SET `version` = '1.2' WHERE `short_name` = 'pandorafms.oracle'; +-- Update version for plugin mysql +UPDATE `tdiscovery_apps` SET `version` = '1.1' WHERE `short_name` = 'pandorafms.mysql'; + SET @widget_id = NULL; SELECT @widget_id := `id` FROM `twidget` WHERE `unique_name` = 'GisMap'; INSERT IGNORE INTO `twidget` (`id`,`class_name`,`unique_name`,`description`,`options`,`page`) VALUES (@widget_id,'GisMap','GisMap','Gis map','','GisMap.php'); +SET @class_name = 'ITSMIncidences'; +SET @unique_name = 'ITSMIncidences'; +SET @description = 'Pandora ITSM tickets'; +SET @page = 'ITSMIncidences.php'; +SET @widget_id = NULL; +SELECT @widget_id := `id` FROM `twidget` WHERE `unique_name` = @unique_name; +INSERT IGNORE INTO `twidget` (`id`,`class_name`,`unique_name`,`description`,`options`,`page`) VALUES (@widget_id,@class_name,@unique_name,@description,'',@page); + +-- Create SNMPv3 credentials for recon tasks and update them +SET @creds_name = 'Recon-SNMP-creds-'; +INSERT IGNORE INTO `tcredential_store` (`identifier`, `id_group`, `product`, `extra_1`) + SELECT + CONCAT(@creds_name,`id_rt`) AS `identifier`, + `id_group`, + 'SNMP' AS `product`, + CONCAT( + '{', + '"community":"',`snmp_community`,'",', + '"version":"',`snmp_version`,'",', + '"securityLevelV3":"',`snmp_security_level`,'",', + '"authUserV3":"',`snmp_auth_user`,'",', + '"authMethodV3":"',`snmp_auth_method`,'",', + '"authPassV3":"',`snmp_auth_pass`,'",', + '"privacyMethodV3":"',`snmp_privacy_method`,'",', + '"privacyPassV3":"',`snmp_privacy_pass`,'"', + '}' + ) AS `extra1` + FROM `trecon_task` WHERE `snmp_version` = 3 AND `snmp_enabled` = 1 +; +UPDATE `trecon_task` SET `auth_strings` = IF(`auth_strings` = '',CONCAT(@creds_name,`id_rt`),CONCAT(@creds_name,`id_rt`,',',`auth_strings`)) WHERE `snmp_version` = 3 AND `snmp_enabled` = 1; + +ALTER TABLE `tdatabase` ADD COLUMN `disabled` TINYINT NOT NULL DEFAULT 0; + +CREATE TABLE IF NOT EXISTS `tmetaconsole_ha_databases` ( + `node_id` int NOT NULL, + `host` varchar(255) DEFAULT '', + `master` tinyint unsigned DEFAULT '0', + PRIMARY KEY (`node_id`, `host`) +) ENGINE=InnoDB DEFAULT CHARSET=UTF8MB4; + COMMIT; \ No newline at end of file diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 35b994fead..5eee6a6669 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -54,7 +54,7 @@ echo sprintf('
', $menuTypeClass); // ======= Servers List =============================================== if ((bool) check_acl($config['id_user'], 0, 'AW') !== false) { $servers = []; - $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['all'] = (int) count((servers_get_info() ?? [])); if ($servers['all'] != 0) { $servers['up'] = (int) servers_check_status(); $servers['down'] = ($servers['all'] - $servers['up']); @@ -161,6 +161,10 @@ echo sprintf('
', $menuTypeClass); 'code' => false, ]; + if (isset($_GET['sec']) === false) { + $_GET['sec'] = ''; + } + if (!isset($_GET['sec2'])) { $_GET['sec2'] = ''; } diff --git a/pandora_console/general/noaccess.php b/pandora_console/general/noaccess.php index b2fe4515a2..9299489864 100644 --- a/pandora_console/general/noaccess.php +++ b/pandora_console/general/noaccess.php @@ -152,9 +152,11 @@ echo __('Access to this page is restricted to authorized users only, please contact system administrator if you need assistance.'); echo '

'; echo __('Please know that all attempts to access this page are recorded in security logs of %s System Database', get_product_name()); - if ($config['logged'] == false) { - if (session_status() === PHP_SESSION_ACTIVE) { - session_destroy(); + if (isset($config['logged']) === true) { + if ($config['logged'] == false) { + if (session_status() === PHP_SESSION_ACTIVE) { + session_destroy(); + } } } ?> diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index 283610e06a..c1c9159134 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -246,6 +246,7 @@ if ($new_agent === true) { // QR Code table. +$CodeQRContent = ''; if ($new_agent === false) { $CodeQRContent .= html_print_div(['id' => 'qr_container_image'], true); $CodeQRContent .= html_print_anchor( @@ -354,10 +355,21 @@ $tableAgent->rowspan = []; // Agent name. if ($new_agent === false) { - $tableAgent->data['caption_name'][0] = __('Agent name'); + $tableAgent->data['caption_name'][0] = __('Agent name').ui_print_help_tip(__('The agent name is a unique identifier (which is automatically generated in software agents). If you set it manually, make sure it is not duplicated. Although it accepts spaces, we do not recommend you to use them in the agent name, you may use them in the agent alias. The agent name is not displayed in the interface, it is an internal name.'), true); $tableAgent->rowclass['name'] = 'w540px'; $tableAgent->cellstyle['name'][0] = 'width: 100%;'; - $tableAgent->data['name'][0] = html_print_input_text('agente', $nombre_agente, '', 76, 100, true, false, false, '', 'w100p'); + $tableAgent->data['name'][0] = html_print_input_text( + 'agente', + $nombre_agente, + '', + 76, + 100, + true, + true, + false, + '', + 'w100p' + ); $tableAgent->data['name'][0] .= html_print_div( [ 'class' => 'moduleIdBox', @@ -365,12 +377,35 @@ if ($new_agent === false) { ], true ); + + // Other than Linux, Solaris, AIX, BSD, HPUX, MacOs, and Windows. + if ($id_os !== LINUX && $id_os !== SOLARIS && $id_os !== AIX + && $id_os !== BSD && $id_os !== HPUX && $id_os !== MACOS + && $id_os !== WINDOWS + ) { + $tableAgent->data['name'][0] .= html_print_anchor( + [ + 'content' => html_print_image( + 'images/edit.svg', + true, + [ + 'border' => 0, + 'title' => __('Edit agent name'), + 'class' => 'main_menu_icon invert_filter after_input_icon forced_title clickable', + 'onclick' => 'editAgent()', + ] + ), + ], + true + ); + } + // Agent options for QR code. $agent_options_update = 'agent_options_update'; } // Alias. -$tableAgent->data['caption_alias'][0] = __('Alias'); +$tableAgent->data['caption_alias'][0] = __('Alias').ui_print_help_tip(__('This will be the text label that will represent the agent on all types of screens and reports. It may be duplicated, contain spaces and non-ASCII characters.'), true); $tableAgent->rowclass['alias'] = 'w540px'; $tableAgent->data['alias'][0] = html_print_input_text('alias', $alias, '', 50, 100, true, false, true, '', 'w540px'); if ($new_agent === true) { @@ -453,7 +488,7 @@ if ($new_agent === false) { } // Select primary group. -$tableAgent->data['caption_primary_group'][0] = __('Primary group'); +$tableAgent->data['caption_primary_group'][0] = __('Primary group').ui_print_help_tip(__('Although an agent can belong to multiple groups, it can only have a parent group.'), true); if (isset($groups[$grupo]) === true || $new_agent === true) { $tableAgent->rowclass['primary_group'] = 'w540px'; // Cannot change primary group if user have not permission for that group. @@ -520,7 +555,7 @@ if (enterprise_installed()) { } if ($broker === false) { - $tableAgent->data['caption_interval'][0] = __('Interval'); + $tableAgent->data['caption_interval'][0] = __('Interval').ui_print_help_tip(__('Time that elapses when updating data in the agent. Remote modules have their own interval, but this time is used to find out if an agent stopped responding (unknown state). When twice the time interval defined in an agent goes by, it is considered to be in unknown state (or also if all its remote modules are in unknown state). An agent may be in unknown state if all of its local (software agent-based) modules have a last contact time longer than twice the agent interval, even if it has updated remote modules.'), true); // $tableAgent->rowstyle['interval'] = 'width: 260px'; $tableAgent->rowclass['interval'] = 'w540px'; $tableAgent->data['interval'][0] = html_print_extended_select_for_time( @@ -584,7 +619,7 @@ $tableAgent->data['os_version'][0] = html_print_input_text( 'w540px' ); -$tableAgent->data['caption_server'][0] = __('Server'); +$tableAgent->data['caption_server'][0] = __('Server').ui_print_help_tip(__('Server that will preferentially execute remote tasks.'), true); $tableAgent->rowclass['server'] = 'w540px'; $tableAgent->data['server'][0] = html_print_select( $servers, @@ -674,6 +709,19 @@ if (enterprise_installed()) { } } + if ($id_os === '1') { + $modules = $agent_plugin->getModules(); + foreach ($modules as $key => $row) { + if (preg_match('/Syslog/', $row['raw']) === 1) { + if ($row['disabled'] === 1) { + $enable_log_collector = 0; + } else { + $enable_log_collector = 1; + } + } + } + } + if ($id_os === '9') { $modules = $agent_plugin->getModules(); foreach ($modules as $key => $row) { @@ -888,7 +936,7 @@ $switchButtons[] = html_print_radio_button_extended( ); $tableAdvancedAgent->data['module_definition'][] = html_print_label_input_block( - __('Module definition'), + __('Module definition').ui_print_help_tip(__('Three working modes can be selected for module definition. Learning mode: Default mode, if an XML arrives with new modules, they will be created automatically; it is a learning behavior. Normal mode: If an XML arrives with new modules, they will only be created if they are previously declared in the Console. Autodisable mode: It is the same as learning mode, but if all modules go into unknown, the agent will be disabled until information arrives again.'), true), html_print_div( [ 'class' => 'switch_radio_button', @@ -900,7 +948,7 @@ $tableAdvancedAgent->data['module_definition'][] = html_print_label_input_block( // CPS - Cascade Protection Services. $tableAdvancedAgent->data['cps_value'][] = html_print_label_input_block( - __('Cascade protection services'), + __('Cascade protection services').ui_print_help_tip(__('To avoid an avalanche of cascading alerts. You may choose any agent module (any) or a specific module. In the first case, when there is at least one module in critical, that event/alert will be launched, but no other of another module of the same agent. In the second case, when the specified module is in critical, the agent will not generate alerts/events.'), true), html_print_checkbox_switch('cps', $cps_val, ($cps >= 0), true) ); @@ -989,7 +1037,7 @@ $tableAdvancedAgent->data['url_description'][] = html_print_label_input_block( // Agent status. $tableAdvancedAgent->data['agent_status'][] = html_print_label_input_block( - __('Disabled mode'), + __('Disabled mode').ui_print_help_tip(__('A deactivated agent does not generate activity (or issue events/alerts) or process data or actively generate monitoring. In many listings it does not even appear.'), true), html_print_checkbox_switch( 'disabled', 1, @@ -1000,7 +1048,7 @@ $tableAdvancedAgent->data['agent_status'][] = html_print_label_input_block( // Quiet mode. $tableAdvancedAgent->data['agent_quiet'][] = html_print_label_input_block( - __('Quiet'), + __('Quiet').ui_print_help_tip(__('A \'silent\' agent continues to process monitoring data, but does not generate events or alerts.'), true), html_print_checkbox_switch('quiet', 1, $quiet, true) ); @@ -1066,7 +1114,7 @@ $safeOperationElements[] = html_print_select( ); $tableAdvancedAgent->data['safe_operation'][] = html_print_label_input_block( - __('Safe operation mode'), + __('Safe operation mode').ui_print_help_tip(__('When the module set in this option goes into critical state, the other modules of the agent are automatically deactivated. This option can be very useful to avoid wasting resources, especially in remote checks. For example, if a Host alive module is chosen, SNMP checks will not be performed on the device when there is no connectivity with it.'), true), html_print_div( [ 'class' => 'flex-row-center', @@ -1478,7 +1526,6 @@ ui_require_jquery_file('bgiframe'); 128 ); } - $("#text-agente").prop('readonly', true); $("#text-direccion").on('change',function(e){ @@ -1525,6 +1572,39 @@ ui_require_jquery_file('bgiframe'); } } + function editAgent() { + $(`#text-agente`).attr(`readonly`, false); + const title = ''; + const text = ''; + const id = uniqId(); + $("body").append('
'); + $("#" + id).empty(); + $("#" + id).append(text); + $("#" + id).dialog({ + height: 150, + width: 528, + opacity: 1, + modal: true, + position: { + my: "center", + at: "center", + of: window, + collision: "fit" + }, + title: title, + closeOnEscape: true, + buttons: [{ + text: "OK", + click: function() { + $(this).dialog("close"); + } + }], + open: function(event, ui) { + $(".ui-dialog-titlebar-close").hide(); + }, + }).show(); + } + function check_unique_ip() { const direccion = $('#text-direccion').val(); diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index c2e3a2f4f6..6a1084e605 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -816,6 +816,23 @@ if ($id_agente) { $helper = ($help_header === 'main_tab') ? 'main_tab' : ''; $pure = (int) get_parameter('pure'); + $menu_tabs = []; + // Agent details. + $menu_tab_url = ''.__('General setup').''; + array_push($menu_tabs, $menu_tab_url); + // Agent details. + $menu_tab_url = ''.__('Agent detail').''; + array_push($menu_tabs, $menu_tab_url); + // Manage agents. + $menu_tab_url = ''.__('Manage agents').''; + array_push($menu_tabs, $menu_tab_url); + // Events. + $menu_tab_url = ''.__('View events').''; + array_push($menu_tabs, $menu_tab_url); + // Events. + $menu_tab_url = ''.__('Custom reports').''; + array_push($menu_tabs, $menu_tab_url); + $dots = dot_tab($menu_tabs); if ($pure === 0) { ui_print_standard_header( __('Agent setup view').' ( '.strtolower(agents_get_alias($id_agente)).' )', @@ -837,7 +854,9 @@ if ($id_agente) { 'link' => '', 'label' => $tab_name, ], - ] + ], + [], + $dots ); } } else { @@ -857,7 +876,9 @@ if ($id_agente) { 'link' => 'index.php?sec=gagente&sec2=godmode/agentes/modificar_agente', 'label' => __('Manage agents'), ], - ] + ], + [], + $dots ); } @@ -949,6 +970,13 @@ if ($update_agent) { $mssg_warning = 0; $id_agente = (int) get_parameter_post('id_agente'); $nombre_agente = str_replace('`', '‘', (string) get_parameter_post('agente', '')); + $repeated_name = db_get_row_sql( + sprintf( + 'SELECT nombre FROM tagente WHERE id_agente <> %s AND nombre like "%s"', + $id_agente, + $nombre_agente + ) + ); $alias_safe_output = strip_tags(io_safe_output(get_parameter('alias', ''))); $alias = io_safe_input(trim(preg_replace('/[\/\\\|%#&$]/', '', $alias_safe_output))); $alias_as_name = (int) get_parameter_post('alias_as_name', 0); @@ -1077,14 +1105,17 @@ if ($update_agent) { } } + // Verify if there is another agent with the same name but different ID. + if (empty($repeated_name) === false) { + ui_print_error_message(__('Agent with repeated name')); + } + if ($mssg_warning) { ui_print_warning_message(__('The ip or dns name entered cannot be resolved')); } - // Verify if there is another agent with the same name but different ID. if ($alias == '') { ui_print_error_message(__('No agent alias specified')); - // If there is an agent with the same name, but a different ID. } $old_group = agents_get_agent_group($id_agente); @@ -1139,13 +1170,16 @@ if ($update_agent) { 'ignore_unknown' => $ignore_unknown, ]; + if (empty($repeated_name) === true) { + $values['nombre'] = $nombre_agente; + } + if ($config['metaconsole_agent_cache'] == 1) { $values['update_module_count'] = 1; // Force an update of the agent cache. } - $result = db_process_sql_update('tagente', $values, ['id_agente' => $id_agente]); - + $result = (bool) db_process_sql_update('tagente', $values, ['id_agente' => $id_agente]); if ($result === false && $update_custom_result == false) { ui_print_error_message( __('There was a problem updating the agent') @@ -1299,8 +1333,11 @@ if ($update_agent) { } $modules = $agent->getModules(); + foreach ($modules as $key => $row) { - if (preg_match('/PandoraAgent_log/', $row['raw']) === 1) { + if (preg_match('/PandoraAgent_log/', $row['raw']) === 1 + || ($id_os === 1 && preg_match('/Syslog/', $row['raw']) === 1) + ) { if ($enable_log_collector === 1) { if ($row['disabled'] === 1) { $agent->enableModule($row['module_name'], $row); @@ -2318,6 +2355,23 @@ if ($delete_module) { exit; } + // Check if module is used by agent for Safe mode. + $is_safe_mode_module = modules_check_safe_mode($id_borrar_modulo); + if ($is_safe_mode_module === true && isset($id_agente) === true) { + db_process_sql_update('tagente', ['safe_mode_module' => '0'], ['id_agente' => $id_agente]); + db_process_sql_update( + 'tagente_modulo', + [ + 'disabled' => 0, + 'disabled_by_safe_mode' => 0, + ], + [ + 'id_agente' => $id_agente, + 'disabled_by_safe_mode' => 1, + ] + ); + } + // Before delete the main module, check and delete the childrens from the original module. module_check_childrens_and_delete($id_borrar_modulo); diff --git a/pandora_console/godmode/agentes/configure_field.php b/pandora_console/godmode/agentes/configure_field.php index 904b807bbd..44332487ce 100755 --- a/pandora_console/godmode/agentes/configure_field.php +++ b/pandora_console/godmode/agentes/configure_field.php @@ -55,7 +55,7 @@ if ($id_field) { $display_on_front = $field['display_on_front']; $is_password_type = $field['is_password_type']; $combo_values = $field['combo_values'] ? $field['combo_values'] : ''; - $is_combo_enable = $config['is_combo_enable']; + $is_combo_enable = (isset($config['is_combo_enable']) === true) ? $config['is_combo_enable'] : false; $is_link_enabled = $field['is_link_enabled']; $header_title = __('Update agent custom field'); } else { @@ -162,6 +162,10 @@ $table->data[2][0] = html_print_label_input_block( ) ); +if (isset($config['is_combo_enable']) === false) { + $config['is_combo_enable'] = false; +} + $table->data[2][1] = html_print_label_input_block( __('Enabled combo'), html_print_checkbox_switch_extended( diff --git a/pandora_console/godmode/agentes/modificar_agente.php b/pandora_console/godmode/agentes/modificar_agente.php index a7ee6bf4c0..b0f071c1b4 100644 --- a/pandora_console/godmode/agentes/modificar_agente.php +++ b/pandora_console/godmode/agentes/modificar_agente.php @@ -697,7 +697,7 @@ if ($agents !== false) { $tableAgents->head = []; $tableAgents->data = []; // Header. - $tableAgents->head[0] = ''.__('Agent name').''; + $tableAgents->head[0] = ''.__('Agent alias').''; $tableAgents->head[0] .= ui_get_sorting_arrows($url_up_agente, $url_down_agente, $selectNameUp, $selectNameDown); $tableAgents->head[1] = ''.__('R').''; $tableAgents->head[1] .= ui_get_sorting_arrows($url_up_remote, $url_down_remote, $selectRemoteUp, $selectRemoteDown); diff --git a/pandora_console/godmode/agentes/module_manager_editor.php b/pandora_console/godmode/agentes/module_manager_editor.php index 543d241fc9..20fe16c626 100644 --- a/pandora_console/godmode/agentes/module_manager_editor.php +++ b/pandora_console/godmode/agentes/module_manager_editor.php @@ -765,7 +765,7 @@ $outputForm .= ui_toggle( $outputForm .= ui_toggle( html_print_table($table_macros, true), - ''.__('Custom macros').'', + ''.__('Custom macros').ui_print_help_tip(__('Allows you to set custom macros for this module (e.g. name \'_location_\', value \'Office\'). These macros can then be used in alerts to provide additional information about the module in question.'), true).'', '', '', true, @@ -784,7 +784,7 @@ if ((int) $moduletype !== 13) { $table_relations, true ), - ''.__('Module relations').'', + ''.__('Module relations').ui_print_help_tip(__('Used to replace the module in SLA reports, either directly () or in Failover mode ().'), true).'', '', '', true, diff --git a/pandora_console/godmode/agentes/module_manager_editor_common.php b/pandora_console/godmode/agentes/module_manager_editor_common.php index a9d809d29f..fda655f314 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_common.php +++ b/pandora_console/godmode/agentes/module_manager_editor_common.php @@ -446,7 +446,9 @@ $tableBasicThresholds->rowclass['caption_warning_threshold'] = 'field_half_width $tableBasicThresholds->rowclass['warning_threshold'] = 'field_half_width'; $tableBasicThresholds->data['caption_warning_threshold'][0] .= __('Warning threshold').' '; -$tableBasicThresholds->data['caption_warning_threshold'][0] .= '('.__('Min / Max').')'; +$tableBasicThresholds->data['caption_warning_threshold'][0] .= '
('.__('Min / Max').')
'; +$tableBasicThresholds->data['caption_warning_threshold'][0] .= ''; +$tableBasicThresholds->data['caption_warning_threshold'][0] .= ui_print_help_tip(__('Normal: Any value within the specified range will cause a state change. Inverse interval: Any value outside the specified range will cause a state change. Percentage: This mode takes into account the module variation percentage (regarding its previous value), and will cause a change of state if it complies with the indicated increase or decrease values. A value that matches the Warning and Critical thresholds will trigger the Critical status. In numeric modules, a Max 0 value represents infinity.'), true); $tableBasicThresholds->data['warning_threshold'][0] .= html_print_input_text( 'min_warning', $min_warning, @@ -534,7 +536,9 @@ $tableBasicThresholds->data['warning_time'][1] .= '  '.__('interval $tableBasicThresholds->rowclass['caption_critical_threshold'] = 'field_half_width pdd_t_10px'; $tableBasicThresholds->rowclass['critical_threshold'] = 'field_half_width'; $tableBasicThresholds->data['caption_critical_threshold'][0] .= __('Critical threshold').' '; -$tableBasicThresholds->data['caption_critical_threshold'][0] .= '('.__('Min / Max').')'; +$tableBasicThresholds->data['caption_critical_threshold'][0] .= '
('.__('Min / Max').')
'; +$tableBasicThresholds->data['caption_critical_threshold'][0] .= ''; +$tableBasicThresholds->data['caption_critical_threshold'][0] .= ui_print_help_tip(__('Normal: Any value within the specified range will cause a state change.\nInverse interval: Any value outside the specified range will cause a state change. Percentage: This mode takes into account the module variation percentage (regarding its previous value), and will cause a change of state if it complies with the indicated increase or decrease values. A value that matches the Warning and Critical thresholds will trigger the Critical status. In numeric modules, a Max 0 value represents infinity.'), true).'
'; $tableBasicThresholds->data['critical_threshold'][0] .= html_print_input_text( 'min_critical', $min_critical, @@ -622,7 +626,7 @@ if (modules_is_string_type($id_module_type) === false || (bool) $edit === true) } $table_simple->rowclass['caption_historical_data'] = 'mrgn_top_10px'; -$table_simple->data['caption_historical_data'][0] = __('Historical data'); +$table_simple->data['caption_historical_data'][0] = __('Historical data').ui_print_help_tip(__('If disabled, it will only save the last known data, being unable to display graphs. It is useful to save DB space. It should be disabled only in those cases where it is necessary for the system to flow faster and save resources.'), true); if ($disabledBecauseInPolicy) { // If is disabled, we send a hidden in his place and print a false // checkbox because HTML dont send disabled fields @@ -1134,7 +1138,7 @@ if (isset($id_agente) === true && (int) $moduletype === MODULE_DATA) { $table_advanced->rowclass['cron_section'] = 'table_section full_section mrgn_top_mod_0px'; $table_advanced->data['cron_section'] = html_print_table($tableCron, true); -$table_advanced->data['title_3'] = html_print_subtitle_table(__('Thresholds and state changes')); +$table_advanced->data['title_3'] = html_print_subtitle_table(__('Thresholds and state changes').ui_print_help_tip(__('It indicates the minimum and maximum values accepted by the module. Any value outside this range will be discarded. For example, with a Max. value of 100, a data value of 200 will not be saved in a database.'), true)); $table_advanced->rowclass['caption_min_max_values'] = 'w50p pdd_t_10px'; $table_advanced->rowclass['min_max_values'] = 'w50p pdd_b_10px'; @@ -1152,7 +1156,7 @@ $tableDynamicThreshold->style = []; $tableDynamicThreshold->rowclass = []; $tableDynamicThreshold->data = []; -$tableDynamicThreshold->data['caption_dynamic_threshold_interval'][0] = __('Dynamic Threshold Interval'); +$tableDynamicThreshold->data['caption_dynamic_threshold_interval'][0] = __('Dynamic Threshold Interval').ui_print_help_tip(__('If this option is enabled, the module thresholds will be automatically adjusted based on the mean and standard deviation of their values in the specified time interval.'), true); $tableDynamicThreshold->rowclass['dynamic_threshold_interval'] = 'w540px'; $tableDynamicThreshold->data['dynamic_threshold_interval'][0] = html_print_extended_select_for_time( 'dynamic_interval', @@ -1174,8 +1178,8 @@ $tableDynamicThreshold->cellclass['caption_adv_dynamic_threshold_interval'][0] = $tableDynamicThreshold->cellclass['caption_adv_dynamic_threshold_interval'][1] = 'w33p'; $tableDynamicThreshold->cellclass['adv_dynamic_threshold_interval'][0] = 'w33p'; $tableDynamicThreshold->cellclass['adv_dynamic_threshold_interval'][1] = 'w33p'; -$tableDynamicThreshold->data['caption_adv_dynamic_threshold_interval'][0] = __('Min.'); -$tableDynamicThreshold->data['caption_adv_dynamic_threshold_interval'][1] = __('Max.'); +$tableDynamicThreshold->data['caption_adv_dynamic_threshold_interval'][0] = __('Min.').ui_print_help_tip(__('It allows to adjust the lower limit of the dynamic threshold, in percentage. For example, if the module average value is 60 and the lower critical state threshold was set to 80, a Dynamic Threshold Max to 10 would set the threshold to 88, 10% lower than what was set.'), true); +$tableDynamicThreshold->data['caption_adv_dynamic_threshold_interval'][1] = __('Max.').ui_print_help_tip(__('It allows to adjust the upper limit of the dynamic threshold, in percentage. For example, if the module average value is 60 and the upper critical state threshold has been set to 80, a Dynamic Threshold Max to 10 would set the threshold to 88, 10% higher than what was set.'), true); $tableDynamicThreshold->data['adv_dynamic_threshold_interval'][0] = html_print_input_text( 'dynamic_min', $dynamic_min, @@ -1205,7 +1209,7 @@ $tableDynamicThreshold->rowclass['caption_adv_dynamic_threshold_twotailed'] = 'p $tableDynamicThreshold->rowclass['adv_dynamic_threshold_twotailed'] = 'w100p'; $tableDynamicThreshold->cellclass['caption_adv_dynamic_threshold_twotailed'][0] = 'w33p'; $tableDynamicThreshold->cellclass['adv_dynamic_threshold_twotailed'][0] = 'w33p'; -$tableDynamicThreshold->data['caption_adv_dynamic_threshold_twotailed'][0] = __('Two Tailed'); +$tableDynamicThreshold->data['caption_adv_dynamic_threshold_twotailed'][0] = __('Two Tailed').ui_print_help_tip(__('It allows to set a lower threshold in addition to the upper one by default. If enabled, both very high and very low values will cause a state change.'), true); $tableDynamicThreshold->data['adv_dynamic_threshold_twotailed'][0] = html_print_checkbox_switch( 'dynamic_two_tailed', 1, @@ -1224,7 +1228,7 @@ $tableFFThreshold->style = []; $tableFFThreshold->rowclass = []; $tableFFThreshold->data = []; // FF stands for Flip-flop. -$tableFFThreshold->data['caption_ff_main_thresholds'][0] = __('FF threshold'); +$tableFFThreshold->data['caption_ff_main_thresholds'][0] = __('FF threshold').ui_print_help_tip(__('It indicates the number of consecutive values at a threshold that must be received for the module to change state. For example, with a value 0 (default) the module will change state as soon as it receives a data within the critical threshold, but with a value 2 the module must receive two more critical data (consecutively) to change to critical state. It is possible to set the same \'tolerance\' for all status changes or choose a different value for each one. This option is especially useful in unstable environments, as it helps prevent false positives.'), true); $tableFFThreshold->rowclass['ff_main_thresholds'] = 'w100p'; $tableFFThreshold->data['ff_main_thresholds'][0] = html_print_switch_radio_button( [ @@ -1366,7 +1370,7 @@ $table_advanced->data['title_4'] = html_print_subtitle_table(__('Data and their $table_advanced->rowclass['caption_process_unit'] = 'w50p'; $table_advanced->rowclass['process_unit'] = 'w50p'; $table_advanced->data['caption_process_unit'][0] = __('Unit'); -$table_advanced->data['caption_process_unit'][1] = __('Post process'); +$table_advanced->data['caption_process_unit'][1] = __('Post process').ui_print_help_tip(__('It allows you to change the unit of the received data. To do this, multiply the data received by the value set in this option (e.g. Seconds * 0.016666666667 = Minutes). The data is saved already transformed in the database, so changing this parameter when the module has data can cause anomalies in graphs and other elements.'), true); $table_advanced->data['process_unit'][0] = html_print_extended_select_for_unit( 'unit', $unit, @@ -1449,7 +1453,7 @@ $table_advanced->data['discard_unknown'][0] = html_print_checkbox_switch( $disabledBecauseInPolicy ); -$table_advanced->data['caption_quiet'][0] = __('Quiet'); +$table_advanced->data['caption_quiet'][0] = __('Quiet').ui_print_help_tip(__('A module in silent mode will continue to receive and store data, but will not trigger alerts or generate events.'), true); $table_advanced->data['quiet'][0] = html_print_checkbox_switch( 'quiet_module', 1, @@ -1458,7 +1462,7 @@ $table_advanced->data['quiet'][0] = html_print_checkbox_switch( $disabledBecauseInPolicy ); -$table_advanced->data['caption_cascade_protection'][0] = __('Cascade Protection Services'); +$table_advanced->data['caption_cascade_protection'][0] = __('Cascade Protection Services').ui_print_help_tip(__('To avoid an avalanche of cascading alerts. You may choose any agent module (any) or a specific module. In the first case, when there is at least one module in critical, that event/alert will be launched, but no other of another module of the same agent. In the second case, when the specified module is in critical, the agent will not generate alerts/events.'), true); $table_advanced->data['cascade_protection'][0] = html_print_select($cps_array, 'cps_module', $cps_module, '', '', 0, true, false, true, '', $disabledBecauseInPolicy); @@ -2377,11 +2381,21 @@ ui_require_jquery_file('json'); if ($('#radius-percentage_warning').is(':checked') === true){ min_w = 0; max_w = 0; + $('#caption_warning_minmax').addClass('invisible'); + $('#caption_warning_crease').removeClass('invisible'); + } else { + $('#caption_warning_minmax').removeClass('invisible'); + $('#caption_warning_crease').addClass('invisible'); } if ($('#radius-percentage_critical').is(':checked') === true){ min_c = 0; max_c = 0; + $('#caption_critical_minmax').addClass('invisible'); + $('#caption_critical_crease').removeClass('invisible'); + } else { + $('#caption_critical_minmax').removeClass('invisible'); + $('#caption_critical_crease').addClass('invisible'); } paint_graph_status( diff --git a/pandora_console/godmode/agentes/module_manager_editor_plugin.php b/pandora_console/godmode/agentes/module_manager_editor_plugin.php index abbbc4d9c1..affa225969 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_plugin.php +++ b/pandora_console/godmode/agentes/module_manager_editor_plugin.php @@ -164,12 +164,13 @@ foreach ($password_fields as $k => $p) { return; } - const moduleId = ; - + const moduleId = 0) ? $module['id'] : $id_agent_module; ?>; + const isPolicy = 0) ? '1' : '0'; ?>; + load_plugin_description($("#id_plugin").val()); - - load_plugin_macros_fields('simple-macro', moduleId); - + + load_plugin_macros_fields('simple-macro', moduleId, isPolicy); + forced_title_callback(); $('select#id_plugin').select2('close'); diff --git a/pandora_console/godmode/alerts/alert_commands.php b/pandora_console/godmode/alerts/alert_commands.php index a5b4de7c80..b242e41e29 100644 --- a/pandora_console/godmode/alerts/alert_commands.php +++ b/pandora_console/godmode/alerts/alert_commands.php @@ -109,7 +109,7 @@ if (is_ajax()) { for ($i = 1; $i <= $config['max_macro_fields']; $i++) { $field_description = $fields_descriptions[($i - 1)]; $field_value = $fields_values[($i - 1)]; - $field_hidden = $fields_hidden_checked[($i - 1)]; + $field_hidden = (isset($fields_hidden_checked[($i - 1)]) === true) ? $fields_hidden_checked[($i - 1)] : ''; if (!empty($field_description)) { diff --git a/pandora_console/godmode/alerts/alert_list.list.php b/pandora_console/godmode/alerts/alert_list.list.php index 5d71895ecd..fe0790f71b 100644 --- a/pandora_console/godmode/alerts/alert_list.list.php +++ b/pandora_console/godmode/alerts/alert_list.list.php @@ -253,7 +253,7 @@ if (is_metaconsole() === true) { echo '
'; } -if (!$id_cluster) { +if (isset($id_cluster) === false) { ui_toggle( $form_filter, ''.__('Alert control filter').'', @@ -1115,7 +1115,7 @@ if (isset($dont_display_alert_create_bttn)) { } } -if ($display_create && (check_acl($config['id_user'], 0, 'LW') || check_acl($config['id_user'], $template_group, 'LM')) && !$id_cluster) { +if ($display_create && (check_acl($config['id_user'], 0, 'LW') || check_acl($config['id_user'], $template_group, 'LM')) && isset($id_cluster) === false) { echo '
'; $actionButtons = html_print_submit_button( __('Create'), diff --git a/pandora_console/godmode/category/category.php b/pandora_console/godmode/category/category.php index 46095b6efb..02a221fee8 100755 --- a/pandora_console/godmode/category/category.php +++ b/pandora_console/godmode/category/category.php @@ -242,6 +242,7 @@ if (empty($result) === false) { html_print_table($table); $tablePagination = ui_pagination($total_categories, $url, $offset, 0, true, 'offset', false); } else { + $tablePagination = ''; // No categories available or selected. ui_print_info_message(['no_close' => true, 'message' => __('No categories found') ]); } diff --git a/pandora_console/godmode/extensions.php b/pandora_console/godmode/extensions.php index 3ff09273c6..3db36f71a9 100644 --- a/pandora_console/godmode/extensions.php +++ b/pandora_console/godmode/extensions.php @@ -195,13 +195,13 @@ foreach ($extensions as $file => $extension) { $data[] = ''.$file.''; // Get version of this extensions - if ($config['extensions'][$file]['operation_menu']) { + if (isset($config['extensions'][$file]['operation_menu']) === true) { $data[] = $config['extensions'][$file]['operation_menu']['version']; - } else if ($config['extensions'][$file]['godmode_menu']) { + } else if (isset($config['extensions'][$file]['godmode_menu']) === true) { $data[] = $config['extensions'][$file]['godmode_menu']['version']; - } else if ($config['extensions'][$file]['extension_ope_tab']) { + } else if (isset($config['extensions'][$file]['extension_ope_tab']) === true) { $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; - } else if ($config['extensions'][$file]['extension_god_tab']) { + } else if (isset($config['extensions'][$file]['extension_god_tab']) === true) { $data[] = $config['extensions'][$file]['extension_god_tab']['version']; } else { $data[] = __('N/A'); @@ -216,7 +216,7 @@ foreach ($extensions as $file => $extension) { $data[] = $config['extensions'][$file]['godmode_menu']['version']; } else if (isset($config['extensions'][$file]['extension_ope_tab'])) { $data[] = $config['extensions'][$file]['extension_ope_tab']['version']; - } else if ($config['extensions'][$file]['extension_god_tab']) { + } else if (isset($config['extensions'][$file]['extension_god_tab']) === true) { $data[] = $config['extensions'][$file]['extension_god_tab']['version']; } else { $data[] = __('N/A'); diff --git a/pandora_console/godmode/groups/configure_group.php b/pandora_console/godmode/groups/configure_group.php index f7fa7a76b7..3376f42804 100644 --- a/pandora_console/godmode/groups/configure_group.php +++ b/pandora_console/godmode/groups/configure_group.php @@ -234,7 +234,7 @@ $table->data[1][0] = html_print_label_input_block( if ((bool) $config['enterprise_installed'] === true) { $table->data[1][1] .= html_print_label_input_block( - __('Group Password'), + __('Group Password').ui_print_help_tip(__('If a group is password protected, it will only accept XML from those software agents that have a group password configured with the same name. Do not use spaces or symbols.'), true), html_print_input_password('group_pass', $group_pass, '', 16, 255, true) ); } @@ -250,7 +250,7 @@ $table->data[2][1] = html_print_label_input_block( ); $table->data[3][0] = html_print_label_input_block( - __('Custom ID'), + __('Custom ID').ui_print_help_tip(__('It is an external ID used for integrations. Do not use spaces or symbols.'), true), html_print_input_text('custom_id', $custom_id, '', 16, 255, true) ); diff --git a/pandora_console/godmode/groups/group_list.php b/pandora_console/godmode/groups/group_list.php index 66717bc35b..6aad60e71d 100644 --- a/pandora_console/godmode/groups/group_list.php +++ b/pandora_console/godmode/groups/group_list.php @@ -560,13 +560,13 @@ if ($is_management_allowed === true && $update_group === true) { } } +$id_group = (int) get_parameter('id_group'); + // Delete group. if ($is_management_allowed === true && $delete_group === true - && ((bool) check_acl($config['id_user'], 0, 'PM') === true) + && ((bool) check_acl($config['id_user'], $id_group, 'PM') === true) ) { - $id_group = (int) get_parameter('id_group'); - $usedGroup = groups_check_used($id_group); if (!$usedGroup['return']) { @@ -880,6 +880,28 @@ if ($tab == 'tree') { echo "
"; + if (users_can_manage_group_all('AR') === false) { + $user_groups_acl = users_get_groups(false, 'AR'); + $groups_acl = implode('","', $user_groups_acl); + if (empty($groups_acl) === true) { + $is_management_allowed = false; + } + } + + html_print_div( + [ + 'content' => ui_print_info_message( + [ + 'no_close' => true, + 'message' => __('There are no defined groups'), + ], + '', + true + ), + 'class' => 'invisible', + 'id' => 'message-tree-info', + ] + ); } else { /* * Group list view. @@ -1183,9 +1205,9 @@ $tab = 'group_edition'; \ No newline at end of file diff --git a/pandora_console/godmode/servers/modificar_server.php b/pandora_console/godmode/servers/modificar_server.php index 8a78de9592..e4c5d7aa09 100644 --- a/pandora_console/godmode/servers/modificar_server.php +++ b/pandora_console/godmode/servers/modificar_server.php @@ -496,8 +496,8 @@ if (isset($_GET['server']) === true) {
'; $output .= '
'; $table = new stdClass(); + $table->data = []; $table->class = 'table-adv-filter'; - $table->data[0][0] .= '
'.__('From').':
'; + $table->data[0][0] = '
'.__('From').':
'; $table->data[0][0] .= html_print_input_text('date_init', $date_init, '', 12, 10, true).' '; $table->data[0][0] .= html_print_input_text('time_init', $time_init, '', 10, 7, true).' '; $table->data[0][0] .= '
'; @@ -7740,3 +7742,45 @@ function print_email_test_modal_window($id) echo ''; } + + +function dot_tab(array $tabs=[], array $jump_to=[]) +{ + $tabs_link = ''; + + $tabs_jump_to = ''; + if (isset($jump_to) === true) { + foreach ($jump_to as $value) { + $tabs_jump_to .= $value; + } + } + + $output = ' +
+
+
+
+
+
+ '.$tabs_link; + if ($tabs_jump_to !== '') { + $output .= '
+ '.__('Jump to').': + '.$tabs_jump_to.' +
'; + } + + $output .= '
+
+
+ '; + + return $output; +} \ No newline at end of file diff --git a/pandora_console/include/functions_inventory.php b/pandora_console/include/functions_inventory.php index afa61c3811..3fd8c3f198 100644 --- a/pandora_console/include/functions_inventory.php +++ b/pandora_console/include/functions_inventory.php @@ -788,22 +788,24 @@ function inventory_get_datatable( $rows = db_get_all_rows_sql($sql); if ($order_by_agent === false) { $modules = []; - foreach ($rows as $row) { - if ($row['utimestamp'] !== $row['last_update']) { - $row['timestamp'] = $row['last_update_timestamp']; - } - - $data_rows = explode(PHP_EOL, $row['data_inventory']); - foreach ($data_rows as $data_key => $data_value) { - if (empty($inventory_search_string) !== true) { - $search_check = strpos(str_replace(' ', ' ', $data_value), $inventory_search_string); - } else { - $search_check = true; + if ($rows !== false) { + foreach ($rows as $row) { + if ($row['utimestamp'] !== $row['last_update']) { + $row['timestamp'] = $row['last_update_timestamp']; } - if (empty($data_value) === false && $search_check !== false) { - $row['data'] = $data_value; - $modules[$row['name']][$row['name_agent'].'-'.$data_key.'-'.$data_value] = $row; + $data_rows = explode(PHP_EOL, $row['data_inventory']); + foreach ($data_rows as $data_key => $data_value) { + if (empty($inventory_search_string) !== true) { + $search_check = strpos(str_replace(' ', ' ', $data_value), $inventory_search_string); + } else { + $search_check = true; + } + + if (empty($data_value) === false && $search_check !== false) { + $row['data'] = $data_value; + $modules[$row['name']][$row['name_agent'].'-'.$data_key.'-'.$data_value] = $row; + } } } } @@ -890,6 +892,15 @@ function get_data_basic_info_sql($params, $count=false) if ($params['id_group'] > 0) { $where .= sprintf(' AND id_grupo = %d', $params['id_group']); + } else { + global $config; + $user_groups = implode(',', array_keys(users_get_groups($config['id_user']))); + // Avoid errors if there are no groups. + if (empty($user_groups) === true) { + $user_groups = '"0"'; + } + + $where .= sprintf(' AND id_grupo IN (%s)', $user_groups); } if ($params['search'] > 0) { diff --git a/pandora_console/include/functions_menu.php b/pandora_console/include/functions_menu.php index aa19f58ded..9e2824f9e4 100644 --- a/pandora_console/include/functions_menu.php +++ b/pandora_console/include/functions_menu.php @@ -699,9 +699,9 @@ function menu_get_sec($with_categories=false) } $sec_array[$k]['optgroup'] = $category; - $sec_array[$k]['name'] = $v['text']; + $sec_array[$k]['name'] = (isset($v['text']) === true) ? $v['text'] : ''; } else { - $sec_array[$k] = $v['text']; + $sec_array[$k] = (isset($v['text']) === true) ? $v['text'] : ''; } } diff --git a/pandora_console/include/functions_modules.php b/pandora_console/include/functions_modules.php index 2d3b5676ec..06ea8ce480 100755 --- a/pandora_console/include/functions_modules.php +++ b/pandora_console/include/functions_modules.php @@ -2700,6 +2700,14 @@ function modules_get_agentmodule_data_for_humans($module) if ($data_macro !== false) { $salida = $data_macro; } else { + if (isset($module['current_interval']) === false) { + $module['current_interval'] = 0; + } + + if (isset($module['module_name']) === false) { + $module['module_name'] = 0; + } + $salida = ui_print_module_string_value( $module['datos'], empty($module['id']) ? $module['id_agente_modulo'] : $module['id'], @@ -5074,3 +5082,28 @@ function modules_made_compatible($id_tipo_modulo) return true; } } + + +/** + * Check if module is used by agent for Safe mode. + * + * @param integer $id_module Id for module to check + * + * @return boolean + */ +function modules_check_safe_mode($id_module) +{ + $id_agent = modules_give_agent_id_from_module_id($id_module); + if ($id_agent === 0) { + // No exist agent with this id. + return false; + } + + $agent = agents_get_agent($id_agent); + + if (isset($agent['safe_mode_module']) === true && (int) $agent['safe_mode_module'] === (int) $id_module) { + return true; + } else { + return false; + } +} diff --git a/pandora_console/include/functions_register.php b/pandora_console/include/functions_register.php index db1bc8bf21..6b1d6ec0a7 100644 --- a/pandora_console/include/functions_register.php +++ b/pandora_console/include/functions_register.php @@ -144,7 +144,7 @@ function config_wiz_modal( 'UTC' => __('UTC'), ]; - if ($zone_selected == '') { + if (isset($zone_selected) === false) { if ($config['timezone'] != '') { $zone_array = explode('/', $config['timezone']); $zone_selected = $zone_array[0]; diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 7534cb5e23..c5c7090623 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -12546,7 +12546,7 @@ function reporting_get_stats_indicators($data, $width=280, $height=20, $html=tru $table_ind = html_get_predefined_table(); $servers = []; - $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['all'] = (int) count((servers_get_info() ?? [])); $servers['up'] = (int) servers_check_status(); $servers['down'] = ($servers['all'] - $servers['up']); if ($servers['all'] == 0) { @@ -12607,7 +12607,7 @@ function reporting_get_stats_indicators_mobile($data, $width=280, $height=20, $h $table_ind = html_get_predefined_table(); $servers = []; - $servers['all'] = (int) db_get_value('COUNT(id_server)', 'tserver'); + $servers['all'] = (int) count((servers_get_info() ?? [])); $servers['up'] = (int) servers_check_status(); $servers['down'] = ($servers['all'] - $servers['up']); if ($servers['all'] == 0) { @@ -16206,7 +16206,8 @@ function reporting_module_histogram_graph($report, $content, $pdf=0) // Si viene de no iniciado busco el primer dato del modulo y si es de histórico. $first_utimestamp = false; $search_historydb = false; - $extract_first_data = modules_get_first_date($content['id_agent_module'], 0); + // Limitamos el primer dato al rango de tiempo seleccionado por el usuario. + $extract_first_data = modules_get_first_date($content['id_agent_module'], $date_start); if (empty($extract_first_data) === false) { $first_utimestamp = $extract_first_data['first_utimestamp']; $search_historydb = (isset($extract_first_data['search_historydb']) === true) ? $extract_first_data['search_historydb'] : false; @@ -16311,7 +16312,8 @@ function reporting_module_histogram_graph($report, $content, $pdf=0) $return['data_ok'] = $check_ok; $return['data_total'] = $check_total; if ($check_total > 0) { - $return['percent_ok'] = (($time_ok * 100) / $content['period']); + $percent_ok = (($time_ok * 100) / $content['period']); + $return['percent_ok'] = ($percent_ok > 100) ? 100 : $percent_ok; } else { $return['percent_ok'] = 0; } diff --git a/pandora_console/include/functions_reports.php b/pandora_console/include/functions_reports.php index bb9f57f5c3..c8e774acc7 100755 --- a/pandora_console/include/functions_reports.php +++ b/pandora_console/include/functions_reports.php @@ -1435,7 +1435,7 @@ function custom_fields_macros_report($macro, $key_macro) $macro['server_id'] ); if (metaconsole_connect($server) != NOERR) { - continue; + break; } } diff --git a/pandora_console/include/functions_servers.php b/pandora_console/include/functions_servers.php index bdc8a56fc9..8805998232 100644 --- a/pandora_console/include/functions_servers.php +++ b/pandora_console/include/functions_servers.php @@ -615,7 +615,7 @@ function servers_get_rate($avg_interval, $num_modules) * This function will get all the server information in an array * or a specific server. * - * @param integer $id_server An optional integer or array of integers + * @param integer|array $id_server An optional integer or array of integers * to select specific servers. * * @return mixed False in case the server doesn't exist or an array with info. @@ -624,28 +624,63 @@ function servers_get_info($id_server=-1, $sql_limit=-1) { global $config; - if (is_array($id_server)) { - $select_id = ' WHERE id_server IN ('.implode(',', $id_server).')'; + $select_id = ''; + if (is_array($id_server) === true) { + $select_id = ' AND id_server IN ('.implode(',', $id_server).')'; } else if ($id_server > 0) { - $select_id = ' WHERE id_server IN ('.(int) $id_server.')'; - } else { - $select_id = ''; + $select_id = ' AND id_server IN ('.(int) $id_server.')'; } - $sql = ' - SELECT * - FROM tserver '.$select_id.' - ORDER BY server_type'; + $types_sql = sprintf( + ' AND ( + `server_type` != %d AND + `server_type` != %d + )', + SERVER_TYPE_AUTOPROVISION, + SERVER_TYPE_MIGRATION + ); + if (is_metaconsole() === true && isset($config['ndbh']) === false) { + $types_sql = sprintf( + ' AND ( + `server_type` = %d OR + `server_type` = %d OR + `server_type` = %d OR + `server_type` = %d + )', + SERVER_TYPE_AUTOPROVISION, + SERVER_TYPE_EVENT, + SERVER_TYPE_MIGRATION, + SERVER_TYPE_PREDICTION + ); + } + + $sql = sprintf( + 'SELECT * + FROM tserver + WHERE 1=1 + %s + %s + ORDER BY server_type', + $select_id, + $types_sql + ); if ($sql_limit !== -1) { - $sql = ' - SELECT * - FROM tserver '.$select_id.' - ORDER BY server_type'.$sql_limit; + $sql = sprintf( + 'SELECT * + FROM tserver + WHERE 1=1 + %s + %s + ORDER BY server_type + %s', + $select_id, + $types_sql, + $sql_limit + ); } $result = db_get_all_rows_sql($sql); - $time = get_system_time(); if (empty($result)) { return false; @@ -1445,6 +1480,12 @@ function servers_get_server_string_name(int $server) case SERVER_TYPE_NCM: return __('NCM server'); + case SERVER_TYPE_AUTOPROVISION: + return __('Autoprovision server'); + + case SERVER_TYPE_MIGRATION: + return __('Migration server'); + default: return __('N/A'); } diff --git a/pandora_console/include/functions_snmp_browser.php b/pandora_console/include/functions_snmp_browser.php index 99a0b07612..d545ff102b 100644 --- a/pandora_console/include/functions_snmp_browser.php +++ b/pandora_console/include/functions_snmp_browser.php @@ -37,26 +37,27 @@ enterprise_include_once( // Date format for nfdump. global $nfdump_date_format; -$nfdump_date_format = 'Y/m/d.H:i:s';/** - * Generates a Tree with given $tree information. - * - * Selects all netflow filters (array (id_name => id_name)) or filters filtered - * Used also in Cloud Wizard. - * - * @param string $tree SNMP tree returned by snmp_broser_get_tree. - * @param string $id Level ID. Do not set, used for recursion. - * @param string $depth Branch depth. Do not set, used for recursion. - * @param integer $last Last. - * @param array $last_array Last_array. - * @param string $sufix Sufix. - * @param array $checked Checked. - * @param boolean $descriptive_ids Descriptive_ids. - * @param string $previous_id Previous_id. - * - * @return string HTML code with complete tree. - */ +$nfdump_date_format = 'Y/m/d.H:i:s'; +/** + * Generates a Tree with given $tree information. + * + * Selects all netflow filters (array (id_name => id_name)) or filters filtered + * Used also in Cloud Wizard. + * + * @param string $tree SNMP tree returned by snmp_broser_get_tree. + * @param string $id Level ID. Do not set, used for recursion. + * @param string $depth Branch depth. Do not set, used for recursion. + * @param integer $last Last. + * @param array $last_array Last_array. + * @param string $sufix Sufix. + * @param array $checked Checked. + * @param boolean $descriptive_ids Descriptive_ids. + * @param string $previous_id Previous_id. + * + * @return string HTML code with complete tree. + */ function snmp_browser_get_html_tree( $tree, $id=0, @@ -741,7 +742,7 @@ function snmp_browser_print_container( ) ); - $table->data[0][1] .= html_print_label_input_block( + $table->data[0][1] = html_print_label_input_block( __('Port'), html_print_input( [ diff --git a/pandora_console/include/functions_ui.php b/pandora_console/include/functions_ui.php index 45aa64df22..3999857995 100755 --- a/pandora_console/include/functions_ui.php +++ b/pandora_console/include/functions_ui.php @@ -1445,11 +1445,13 @@ function ui_format_alert_row( if (is_metaconsole() === true) { // Do not show link if user cannot access node if ((bool) can_user_access_node() === true) { - $url = $server['server_url'].'/index.php?'.'sec=estado&'.'sec2=operation/agentes/ver_agente&'.'id_agente='.$agente['id_agente']; + $hashdata = metaconsole_get_server_hashdata($server); + $url = $server['server_url'].'/index.php?sec=estado&sec2=operation/agentes/ver_agente&loginhash=auto&loginhash_data='.$hashdata.'&loginhash_user='.str_rot13($config['id_user']).'&id_agente='.$agente['id_agente']; $data[$index['agent_name']] .= html_print_anchor( [ 'href' => $url, 'content' => ''.$agente['alias'].'', + 'target' => '_blank', ], true ); @@ -2940,18 +2942,22 @@ function ui_print_help_tip( $img = 'images/info@svg.svg'; } - $output = ''; + $text_title = (strlen($text) >= 60) ? substr($text, 0, 60).'...' : $text; + + $id = random_int(1, 99999); + $output = ''; if ($return) { return $output; @@ -4016,19 +4022,21 @@ function ui_print_datatable(array $parameters) $parameters['order']['order'] = $order; $parameters['order']['direction'] = $direction; - foreach ($parameters['no_sortable_columns'] as $key => $find) { - $found = array_search( - $parameters['no_sortable_columns'][$key], - $columns_tmp - ); + if (isset($parameters['no_sortable_columns']) === true) { + foreach ($parameters['no_sortable_columns'] as $key => $find) { + $found = array_search( + $parameters['no_sortable_columns'][$key], + $columns_tmp + ); - if ($found !== false) { - unset($parameters['no_sortable_columns'][$key]); - array_push($parameters['no_sortable_columns'], $found); - } + if ($found !== false) { + unset($parameters['no_sortable_columns'][$key]); + array_push($parameters['no_sortable_columns'], $found); + } - if (is_int($parameters['no_sortable_columns'][$key]) === false) { - unset($parameters['no_sortable_columns'][$key]); + if (is_int($parameters['no_sortable_columns'][$key]) === false) { + unset($parameters['no_sortable_columns'][$key]); + } } } @@ -4092,11 +4100,13 @@ function ui_print_datatable(array $parameters) $filter .= '
    '; - foreach ($parameters['form']['inputs'] as $input) { - if ($input['type'] === 'date_range') { - $filter .= '
  • '.html_print_select_date_range('date', true).'
  • '; - } else { - $filter .= html_print_input(($input + ['return' => true]), 'li'); + if (isset($parameters['form']['inputs']) === true) { + foreach ($parameters['form']['inputs'] as $input) { + if ($input['type'] === 'date_range') { + $filter .= '
  • '.html_print_select_date_range('date', true).'
  • '; + } else { + $filter .= html_print_input(($input + ['return' => true]), 'li'); + } } } @@ -4246,7 +4256,7 @@ function ui_print_datatable(array $parameters) } $parameters['phpDate'] = date('Y-m-d'); - $parameters['dataElements'] = json_encode($parameters['data_element']); + $parameters['dataElements'] = (isset($parameters['data_element']) === true) ? json_encode($parameters['data_element']) : ''; // * START JAVASCRIPT. $file_path = $config['homedir'].'/include/javascript/datatablesFunction.js'; @@ -5230,7 +5240,8 @@ function ui_print_standard_header( bool $godmode=false, array $options=[], array $breadcrumbs=[], - array $fav_menu_config=[] + array $fav_menu_config=[], + string $dots='', ) { // For standard breadcrumbs. ui_require_css_file('discovery'); @@ -5269,7 +5280,8 @@ function ui_print_standard_header( '', $headerInformation->printHeader(true), false, - $fav_menu_config + $fav_menu_config, + $dots ); if ($return !== true) { echo $output; @@ -5310,7 +5322,8 @@ function ui_print_page_header( $alias='', $breadcrumbs='', $hide_left_small=false, - $fav_menu_config=[] + $fav_menu_config=[], + $dots='', ) { global $config; @@ -5441,12 +5454,22 @@ function ui_print_page_header( } } - $buffer .= '
'; + $buffer .= ''; + if (isset($dots) === true) { + $buffer .= ''; + } + + $buffer .= '
'; } else { if ($options != '') { $buffer .= ''; + $buffer .= ''; + if (isset($dots) === true) { + $buffer .= ''; + } + + $buffer .= '
'; } } @@ -6774,6 +6797,10 @@ function ui_print_module_string_value( $value = io_safe_input($value); } + if (isset($module) === false) { + $module['datos'] = ''; + } + $is_snapshot = is_snapshot_data($module['datos']); $is_large_image = is_text_to_black_string($module['datos']); if (($config['command_snapshot']) && ($is_snapshot || $is_large_image)) { diff --git a/pandora_console/include/functions_welcome_wizard.php b/pandora_console/include/functions_welcome_wizard.php index f1b8d672f1..249fa53e20 100644 --- a/pandora_console/include/functions_welcome_wizard.php +++ b/pandora_console/include/functions_welcome_wizard.php @@ -472,14 +472,124 @@ function create_module_packet_lost($id_agent, $id_group, $ip_target) /** * Create module packet lost and return module id. * - * @param string $ip_target Ip and red mask. + * @param string $ip_target Ip and red mask. + * @param string $snmp_communities SNMP Communities to use in recon task. + * @param array $wmi_credentials WMI Credentials to use in recon task. + * @param array $rcmd_credentials RCMD Credentials to use in recon task. * * @return interger Module id. */ -function create_net_scan($ip_target) +function create_net_scan($ip_target, $snmp_version, $snmp_communities, $wmi_credentials, $rcmd_credentials) { global $config; include_once $config['homedir'].'/godmode/wizards/HostDevices.class.php'; + include_once $config['homedir'].'/include/functions_groups.php'; + + $group_name = 'AutoDiscovery'; + $id_group = db_get_value('id_grupo', 'tgrupo', 'nombre', io_safe_input($group_name)); + if (!($id_group > 0)) { + $id_group = groups_create_group( + io_safe_input($group_name), + [ + 'icon' => 'applications.png', + 'description' => '', + 'contact' => '', + 'other' => '', + ] + ); + + if (!($id_group > 0)) { + $id_group = 10; + } + } + + $auth_strings = []; + + $default_templates = [ + io_safe_input('Linux System'), + io_safe_input('Windows System'), + io_safe_input('Windows Hardware'), + io_safe_input('Network Management'), + ]; + + $default_templates_ids = db_get_all_rows_sql( + 'SELECT id_np + FROM tnetwork_profile + WHERE name IN ('.implode( + ',', + array_map( + function ($template) { + return "'".$template."'"; + }, + $default_templates + ) + ).') + ORDER BY name' + ); + + $id_base = 'autoDiscovery-WMI-'; + $id = 0; + foreach ($wmi_credentials as $wmi) { + $id++; + $identifier = $id_base.$id; + while (db_get_value_sql( + sprintf( + 'SELECT COUNT(*) AS count FROM tcredential_store WHERE identifier = "%s"', + $identifier + ) + ) > 0) { + $id++; + $identifier = $id_base.$id; + } + + $storeKey = db_process_sql_insert( + 'tcredential_store', + [ + 'identifier' => $identifier, + 'id_group' => $id_group, + 'product' => 'WMI', + 'username' => $wmi['credential']['user'], + 'password' => $wmi['credential']['pass'], + 'extra_1' => $wmi['credential']['namespace'], + ] + ); + + if ($storeKey !== false) { + $auth_strings[] = $identifier; + } + } + + $id_base = 'autoDiscovery-RCMD-'; + $id = 0; + foreach ($rcmd_credentials as $rcmd) { + $id++; + $identifier = $id_base.$id; + while (db_get_value_sql( + sprintf( + 'SELECT COUNT(*) AS count FROM tcredential_store WHERE identifier = "%s"', + $identifier + ) + ) > 0) { + $id++; + $identifier = $id_base.$id; + } + + $storeKey = db_process_sql_insert( + 'tcredential_store', + [ + 'identifier' => $identifier, + 'id_group' => $id_group, + 'product' => 'CUSTOM', + 'username' => $rcmd['credential']['user'], + 'password' => $rcmd['credential']['pass'], + ] + ); + + if ($storeKey !== false) { + $auth_strings[] = $identifier; + } + } + $HostDevices = new HostDevices(1); $id_recon_server = db_get_row_filter('tserver', ['server_type' => SERVER_TYPE_DISCOVERY], 'id_server')['id_server']; @@ -493,7 +603,7 @@ function create_net_scan($ip_target) 'taskname' => __('Basic network'), 'id_recon_server' => $id_recon_server, 'network' => $ip_target, - 'id_group' => '8', + 'id_group' => $id_group, 'comment' => __('Created on welcome'), ]; $task_created = $HostDevices->parseNetScan(); @@ -504,13 +614,13 @@ function create_net_scan($ip_target) 'page' => '2', 'recon_ports' => '', 'auto_monitor' => 'on', - 'id_network_profile' => ['0' => '2'], + 'id_network_profile' => array_column($default_templates_ids, 'id_np'), 'review_results' => 'on', 'review_limited' => '0', 'snmp_enabled' => 'on', - 'snmp_version' => '1', + 'snmp_version' => $snmp_version, 'snmp_skip_non_enabled_ifs' => 'on', - 'community' => '', + 'community' => $snmp_communities, 'snmp_context' => '', 'snmp_auth_user' => '', 'snmp_security_level' => 'authNoPriv', @@ -523,6 +633,9 @@ function create_net_scan($ip_target) 'parent_detection' => 'on', 'parent_recursion' => 'on', 'vlan_enabled' => 'on', + 'wmi_enabled' => 'on', + 'rcmd_enabled' => 'on', + 'auth_strings' => $auth_strings, ]; $task_final_created = $HostDevicesFinal->parseNetScan(); diff --git a/pandora_console/include/graphs/fgraph.php b/pandora_console/include/graphs/fgraph.php index d8db7d64d9..5861f67033 100644 --- a/pandora_console/include/graphs/fgraph.php +++ b/pandora_console/include/graphs/fgraph.php @@ -1355,12 +1355,12 @@ function get_build_setup_charts($type, $options, $data) $chart->labels()->exchangeArray($options['labels']); foreach ($data as $key => $dataset) { $dataSet = $chart->createDataSet(); - $dataSet->setLabel($dataset['label']); + $dataSet->setLabel((isset($dataset['label']) === true) ? $dataset['label'] : ''); $dataSet->setBackgroundColor($dataset['backgroundColor']); $dataSet->setBorderColor($dataset['borderColor']); $dataSet->setPointBackgroundColor($dataset['pointBackgroundColor']); - $dataSet->setPointBorderColor($dataset['pointBorderColor']); - $dataSet->setPointHoverBackgroundColor($dataset['pointHoverBackgroundColor']); + $dataSet->setPointBorderColor((isset($dataset['pointBorderColor']) === true) ? $dataset['pointBorderColor'] : ''); + $dataSet->setPointHoverBackgroundColor((isset($dataset['pointHoverBackgroundColor']) === true) ? $dataset['pointHoverBackgroundColor'] : ''); $dataSet->setPointHoverBorderColor($dataset['pointHoverBorderColor']); $dataSet->data()->exchangeArray($dataset['data']); $chart->addDataSet($dataSet); diff --git a/pandora_console/include/graphs/functions_flot.php b/pandora_console/include/graphs/functions_flot.php index c51e3283df..40530a49be 100644 --- a/pandora_console/include/graphs/functions_flot.php +++ b/pandora_console/include/graphs/functions_flot.php @@ -205,6 +205,14 @@ function flot_area_graph( $red_inverse = false; } } else if (isset($params['combined']) === false || !$params['combined']) { + if (isset($data_module_graph['w_min']) === false) { + $data_module_graph['w_min'] = ''; + } + + if (isset($data_module_graph['c_min']) === false) { + $data_module_graph['c_min'] = ''; + } + $yellow_threshold = $data_module_graph['w_min']; $red_threshold = $data_module_graph['c_min']; // Get other required module datas to draw warning and critical. diff --git a/pandora_console/include/graphs/functions_utils.php b/pandora_console/include/graphs/functions_utils.php index a96cf8f4c2..e217e25034 100644 --- a/pandora_console/include/graphs/functions_utils.php +++ b/pandora_console/include/graphs/functions_utils.php @@ -43,7 +43,11 @@ function unserialize_in_temp($serial_id=null, $delete=true, $ttl=1) } } - $content = file_get_contents($file_path); + if (file_exists($file_path) === false) { + return false; + } else { + $content = file_get_contents($file_path); + } if ($content === false) { return false; diff --git a/pandora_console/include/javascript/graph_analytics.js b/pandora_console/include/javascript/graph_analytics.js index 475a310ebc..5a83c7c88f 100644 --- a/pandora_console/include/javascript/graph_analytics.js +++ b/pandora_console/include/javascript/graph_analytics.js @@ -253,30 +253,35 @@ function createDroppableZones( ) ); - // Create remove button. if ( - graphDiv - .children() - .children() - .hasClass("parent_graph") === true + $("#hidden-section").val() === + "operation/reporting/graph_analytics" ) { - graphDiv - .children() - .children() - .children(":first-child") - .prepend( - $( - '' - ) - ); - } else { - graphDiv - .children() - .append( - $( - '' - ) - ); + // Create remove button. + if ( + graphDiv + .children() + .children() + .hasClass("parent_graph") === true + ) { + graphDiv + .children() + .children() + .children(":first-child") + .prepend( + $( + '' + ) + ); + } else { + graphDiv + .children() + .append( + $( + '' + ) + ); + } } } } @@ -753,7 +758,7 @@ $("#button-share-modal").click(function(e) { window.open( configHomeurl + - "/operation/reporting/graph_analytics_public.php?" + + "operation/reporting/graph_analytics_public.php?" + queryParams ); }); diff --git a/pandora_console/include/javascript/pandora.js b/pandora_console/include/javascript/pandora.js index 2c39e69288..46892cca07 100644 --- a/pandora_console/include/javascript/pandora.js +++ b/pandora_console/include/javascript/pandora.js @@ -2450,6 +2450,33 @@ $(document).ready(function() { }); } } + + $("[id^='div_tip_']").click(function() { + var id = $(this) + .attr("id") + .split("_")[2]; + + $("#tip_dialog_" + id).dialog({ + title: $("#tip_dialog_" + id).data("title"), + modal: true, + maxWidth: 600, + minWidth: 400, + show: { + effect: "fade", + duration: 200 + }, + hide: { + effect: "fade", + duration: 200 + }, + closeOnEscape: true, + buttons: { + Close: function() { + $(this).dialog("close"); + } + } + }); + }); }); function close_info_box(id) { diff --git a/pandora_console/include/javascript/pandora_modules.js b/pandora_console/include/javascript/pandora_modules.js index b4445e0877..6b697fc2bb 100644 --- a/pandora_console/include/javascript/pandora_modules.js +++ b/pandora_console/include/javascript/pandora_modules.js @@ -1011,7 +1011,7 @@ function add_macro_field(macro, row_model_id, type_copy, k) { $("#" + row_id).show(); } -function load_plugin_macros_fields(row_model_id, moduleId = 0) { +function load_plugin_macros_fields(row_model_id, moduleId = 0, is_policy = 0) { // Get plugin macros when selected and load macros fields var id_plugin = $("#id_plugin").val(); @@ -1024,6 +1024,7 @@ function load_plugin_macros_fields(row_model_id, moduleId = 0) { params.push("get_plugin_macros=1"); } params.push("id_plugin=" + id_plugin); + params.push("is_policy=" + is_policy); jQuery.ajax({ data: params.join("&"), diff --git a/pandora_console/include/lib/Dashboard/Manager.php b/pandora_console/include/lib/Dashboard/Manager.php index fc54d29d2c..9c823ead01 100644 --- a/pandora_console/include/lib/Dashboard/Manager.php +++ b/pandora_console/include/lib/Dashboard/Manager.php @@ -1266,16 +1266,18 @@ class Manager implements PublicLogin } if (empty($cells) === false) { - $result = array_reduce( - $cells, - function ($carry, $item) { - $carry[$item['order']]['id'] = $item['id']; - $carry[$item['order']]['position'] = $item['position']; - $carry[$item['order']]['widgetId'] = $item['id_widget']; + $result = array_values( + array_reduce( + $cells, + function ($carry, $item) { + $carry[$item['order']]['id'] = $item['id']; + $carry[$item['order']]['position'] = $item['position']; + $carry[$item['order']]['widgetId'] = $item['id_widget']; - return $carry; - }, - [] + return $carry; + }, + [] + ) ); } diff --git a/pandora_console/include/lib/Dashboard/Widgets/maps_status.php b/pandora_console/include/lib/Dashboard/Widgets/maps_status.php index 2e59af771c..12d0ef9461 100755 --- a/pandora_console/include/lib/Dashboard/Widgets/maps_status.php +++ b/pandora_console/include/lib/Dashboard/Widgets/maps_status.php @@ -253,7 +253,7 @@ class MapsStatusWidget extends Widget $fields = array_reduce( $dataVc, function ($carry, $item) { - $carry[$item['id']] = $item['name']; + $carry[$item['id']] = io_safe_output($item['name']); return $carry; }, [] @@ -350,7 +350,7 @@ class MapsStatusWidget extends Widget // This will give us the group name. $data[0] = ''; - $data[0] .= $user_layouts[$id_layout]['name']; + $data[0] .= io_safe_output($user_layouts[$id_layout]['name']); $data[0] .= ''; // Status 0 is OK. diff --git a/pandora_console/include/lib/ITSM/ITSM.php b/pandora_console/include/lib/ITSM/ITSM.php index 4879ac9f39..14792e99ee 100644 --- a/pandora_console/include/lib/ITSM/ITSM.php +++ b/pandora_console/include/lib/ITSM/ITSM.php @@ -43,6 +43,9 @@ class ITSM $this->userLevelConf = (bool) $config['ITSM_user_level_conf']; $this->url = ($host ?? $config['ITSM_hostname']); + if (isset($config['ITSM_token']) === false) { + $config['ITSM_token'] = ''; + } $this->userBearer = ($token ?? $config['ITSM_token']); if ($this->userLevelConf === true) { diff --git a/pandora_console/include/lib/TacticalView/GeneralTacticalView.php b/pandora_console/include/lib/TacticalView/GeneralTacticalView.php index 06e27e4fd6..02f60f8252 100644 --- a/pandora_console/include/lib/TacticalView/GeneralTacticalView.php +++ b/pandora_console/include/lib/TacticalView/GeneralTacticalView.php @@ -144,9 +144,11 @@ class GeneralTacticalView { $js = ''; $output .= '
'; @@ -58,9 +66,11 @@ if ($files !== false) { } } -if ($files64 !== false) { - foreach ($files64 as $key => $file) { - $output .= ''; +if (isset($files64) === true) { + if ($files64 !== false) { + foreach ($files64 as $key => $file) { + $output .= ''; + } } } diff --git a/pandora_plugins/Exchange_mail/exchange_mail.py b/pandora_plugins/Exchange_mail/exchange_mail.py new file mode 100644 index 0000000000..65a6175da6 --- /dev/null +++ b/pandora_plugins/Exchange_mail/exchange_mail.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +EXCHANGE MAIL PLUGIN + +Author: Alejandro Sanchez Carrion +Copyright: Copyright 2024, PandoraFMS +Maintainer: Operations Department +Status: Production +Version: 1.0 +""" + +from exchangelib import Credentials,Configuration, Account, DELEGATE, OAUTH2, IMPERSONATION,Message, Mailbox +from exchangelib import OAuth2Credentials +from exchangelib.version import Version, EXCHANGE_O365 +from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter + +BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter + +import urllib3 +urllib3.disable_warnings() + +import pandoraPlugintools as ppt + +import argparse,sys,re,json,os,traceback +from datetime import datetime,timedelta,timezone + + + +__author__ = "Alejandro Sánchez Carrion" +__copyright__ = "Copyright 2022, PandoraFMS" +__maintainer__ = "Operations department" +__status__ = "Production" +__version__= '1.0' + +info = f""" +Pandora FMS Exchange Mail +Version = 1.0 +Description = This plugin can search for matches in your mail and find the number of matches, as well as list them. + +Manual execution + +./exchange_mail \ +--auth \ +--server \ +--smtp_address \ +--client_id \ +--tenant_id \ +--secret \ +[--user ] \ +[--password ] \ +[--subject ] \ +[--sender ] \ +[--date_start ] \ +[--date_end ] \ +[--mail_list ] \ +[--module_prefix ] \ +[--agent_prefix ] \ +[--group ] \ +[--interval ] \ +[--temporal ] \ +[--data_dir ] \ +[--transfer_mode ] \ +[--tentacle_client ] \ +[--tentacle_opts ] \ +[--tentacle_port ] \ +[--tentacle_address ] \ +[--log_file ] + + +there are three parameters with which to filter the mails + +subject +email +date + +You can use only one and filter from that or use the following combinations: + +subject +subject + sender +subject + sender + date +""" + +parser = argparse.ArgumentParser(description= info, formatter_class=argparse.RawTextHelpFormatter) + +parser.add_argument('--server' , help="Server name" , default = "outlook.office365.com" , type=str) +parser.add_argument('--smtp_address' , help="SMTP address" , required = True , type=str) + +parser.add_argument('--user' , help="User name" , default="" , type=str) +parser.add_argument('--password' , help="Password" , default="" , type=str) + +parser.add_argument('--client_id' , help="Client_id" , default="" , type=str) +parser.add_argument('--tenant_id' , help="Tenant_id" , default="" , type=str) +parser.add_argument('--secret' , help="Secret" , default="" , type=str) + + +parser.add_argument('--subject' , help="Select match in subjects" , default=None , type=str) +parser.add_argument('--sender' , help="Select coincidences from email" , default=None , type=str) +parser.add_argument('--date_start' , help="Search for matches from a certain date,Each date must be separated by a hyphen and in quotation marks, with the following format: 'year-month-day-hour-minute'. example: '2021-1-12-0-0'", default=None, type=str) +parser.add_argument('--date_end' , help="Search for matches from a certain date,Each date must be separated by a hyphen and in quotation marks, with the following format: 'year-month-day-hour-minute'. example: '2021-6-12-0-0'", default=None, type=str) +parser.add_argument('--mail_list' , help='List mail coincidences' , default=0 ,type=int ) + +parser.add_argument('--module_prefix' , help='Prefix for the modules. Example : meraki.' , default="" , type=str ) +parser.add_argument('--agent_prefix' , help='Prefix for the agents. Example : meraki.' , default="" , type=str ) + +parser.add_argument('--group' , help='PandoraFMS destination group (default exchange)' , default='' , type=str ) +parser.add_argument('--interval' , help='Agent monitoring interval' , default=300 , type=int ) +parser.add_argument('--temporal' , help='PandoraFMS temporal dir' , default='/tmp' , type=str ) +parser.add_argument('--data_dir' , help='PandoraFMS data dir ' , default='/var/spool/pandora/data_in/' , type=str ) +parser.add_argument('--transfer_mode' , help='Data transfer mode, local or tentacle' , default="tentacle" , type=str ) +parser.add_argument('--tentacle_client' , help='Tentacle client path, by default tentacle_client' , default="tentacle_client" , type=str ) +parser.add_argument('--tentacle_opts' , help='Additional tentacle options' , default="" , type=str ) +parser.add_argument('--tentacle_port' , help='Tentacle port' , default=41121 , type=int ) +parser.add_argument('--tentacle_address' , help='Tentacle adress' , default="127.0.0.1" , type=str ) + +parser.add_argument('--log_file' , help='Log file path' , default='/tmp/exchangemail_logfile.txt' , type=str ) + +parser.add_argument('--auth', choices=['basic', 'oauth'], help='Auth type', required=True) + +args = parser.parse_args() + +############### +## VARIABLES ## +############### + +server = args.server +smtp_address = args.smtp_address + +user = args.user +password = args.password + +client_id = args.client_id +tenant_id = args.tenant_id +secret = args.secret + +subject = args.subject +sender = args.sender +date_start = args.date_start +date_end = args.date_end +mail_list = args.mail_list + +module_prefix = args.module_prefix +agent_prefix = args.agent_prefix + +temporal = args.temporal +group = args.group +interval = args.interval +data_dir = args.data_dir +transfer_mode = args.transfer_mode + +tentacle_address = args.tentacle_address +tentacle_port = args.tentacle_port +tentacle_client = args.tentacle_client +tentacle_opts = args.tentacle_opts + +log_file = args.log_file + +############### +## FUNCTIONS ## +############### + +def Oauth_session(credentials): + """ + Creates an OAuth session with an Exchange server using the provided credentials. + + Args: + credentials (Credentials): Credentials object containing information for OAuth authentication. + + Returns: + Account: An Account object representing the OAuth session with the Exchange server. + """ + try: + config = Configuration(server=server,credentials=credentials, auth_type=OAUTH2,version=Version(build=EXCHANGE_O365),) + account = Account( + smtp_address, + credentials=credentials, + config=config, + autodiscover=False, + access_type=IMPERSONATION) + return account + except Exception as e: + print(0) + write_to_log(f"{type(e).__name__}: {e}", log_file) + sys.exit() + +def basic_session(credentials): + """ + Creates a basic session with an Exchange server using the provided credentials. + + Args: + credentials (Credentials): Credentials object containing information for authentication. + + Returns: + Account: An Account object representing the basic session with the Exchange server. + """ + try: + config = Configuration(server=server, credentials=credentials) + + account = Account( + primary_smtp_address=args.smtp_address, + autodiscover=False, + config=config, + access_type=DELEGATE + ) + return account + except Exception as e: + print(0) + write_to_log(f"{type(e).__name__}: {e}", log_file) + sys.exit() + +def create_module(name, module_type, description, value, unit=""): + """ + Creates a generic module based on a template. + + Args: + module_prefix (str): The prefix for the module name. + name_suffix (str): The suffix to be appended to the module name. + module_type (str): The type of the module. + description (str): The description of the module. + value: The value of the module. + unit (str, optional): The unit of measurement for the module. Defaults to "". + + Returns: + dict: A dictionary representing the generic module. + """ + return { + "name": f'{module_prefix}{name}', + "type": module_type, + "desc": description, + "value": value, + "unit": unit + } + +def create_agent(count,list_mail = None): + + """ + Creates an agent with specified parameters and transfers it to a target address. + + Args: + count (int): Number of mails matching the filter used in the run. + list_mail (str, optional): List of mails matching the filter used in the run. Default is None. + + Returns: + None + """ + + modules = [] + + modules.append(create_module(f"{module_prefix}.Coincidences_count", "generic_data", "Number of mails matching the filter used in the run", count)) + + if list_mail is not None : + + modules.append(create_module(f"{module_prefix}.Coincidences_list", "generic_data_string", "List of mails matching the filter used in the run", list_mail)) + + agent = { + "agent_name" : ppt.generate_md5(agent_prefix + smtp_address), + "agent_alias" : agent_prefix + smtp_address, + "parent_agent_name" : "", + "description" : "", + "version" : "", + "os_name" : "", + "os_version" : "", + "timestamp" : now(), + "address" : server, + "group" : group, + "interval" : interval, + "agent_mode" : "1" + } + + xml_content = ppt.print_agent(agent, modules) + xml_file = ppt.write_xml(xml_content, agent["agent_name"]) + ppt.transfer_xml( + xml_file, + transfer_mode=transfer_mode, + tentacle_ip=tentacle_address, + tentacle_port=tentacle_port + ) + write_to_log("Agent: " + agent_prefix + smtp_address + " getting mail data.", log_file) + +def parse_result(list_email,sep="")-> list: + + """ + Parses a list of email elements and converts them into a list of dictionaries. + + Args: + list_email (list): List of email elements to be parsed. + sep (str): Separator to join elements into a string. Default is an empty string. + + Returns: + list: A list of dictionaries, where each dictionary has a single key "value" containing the joined string. + """ + + result=[] + + for line in list_email: + str_line=sep.join(str(elem) for elem in line) + str_dict={"value":str_line} + result.append(str_dict) + + return result + +def now( + utimestamp: bool = False + ): + """ + Get the current time in the specified format or as a Unix timestamp. + + Args: + utimestamp (bool): Set to True to get the Unix timestamp (epoch time). + print_flag (bool): Set to True to print the time to standard output. + + Returns: + str: The current time in the desired format or as a Unix timestamp. + """ + + today = datetime.today() + + if utimestamp: + time = datetime.timestamp(today) + else: + time = today.strftime('%Y/%m/%d %H:%M:%S') + + return time + +def write_to_log(variable_content, log_file_path): + """ + Writes the content of a variable to a log file with timestamp. + + Args: + variable_content: Content of the variable to be logged. + log_file_path (str): Path to the log file. + """ + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + log_entry = f"{timestamp} - {variable_content}\n" + + try: + with open(log_file_path, 'a') as log_file: + log_file.write(log_entry) + except IOError as e: + print(f"Error writing to log file: {e}") + +if args.auth == 'basic': + credentials = Credentials(username=user, password=password) + account = basic_session(credentials) +elif args.auth == 'oauth': + credentials = OAuth2Credentials(client_id=client_id, client_secret=secret, tenant_id=tenant_id) + account = Oauth_session(credentials) +else: + print(0) + write_to_log(f"{type(e).__name__}: {e}", log_file) + sys.exit() + +try: + ## Only one parameter + if subject and sender==None and date_start==None and date_end == None: + filtered_items = account.inbox.filter(subject__contains=args.subject) + if subject==None and sender and date_start==None and date_end == None: + filtered_items = account.inbox.filter(sender__icontains=sender) + if subject==None and sender==None and date_start and date_end : + + date_start=date_start.split("-") + date_end=date_end.split("-") + filtered_items = account.inbox.filter(datetime_received__range=(datetime(int(date_start[0].strip()), int(date_start[1].strip()), int(date_start[2].strip()), int(date_start[3].strip()), int(date_start[4].strip())).replace(tzinfo=timezone.utc),datetime(int(date_end[0].strip()), int(date_end[1].strip()), int(date_end[2].strip()), int(date_end[3].strip()), int(date_end[4].strip())).replace(tzinfo=timezone.utc))) + + ## Subject + sender + if subject and sender and date_start==None and date_end==None : + filtered_items = account.inbox.filter(sender__icontains=sender,subject__contains=subject) + + ## All parameters + if subject and sender and date_start and date_end : + date_start=date_start.split("-") + date_end=date_end.split("-") + filtered_items = account.inbox.filter(datetime_received__range=(datetime(int(date_start[0].strip()), int(date_start[1].strip()), int(date_start[2].strip()), int(date_start[3].strip()), int(date_start[4].strip())).replace(tzinfo=timezone.utc),datetime(int(date_end[0].strip()), int(date_end[1].strip()), int(date_end[2].strip()), int(date_end[3].strip()), int(date_end[4].strip())).replace(tzinfo=timezone.utc)),sender__icontains=args.sender,subject__contains=args.subject) + + # List Number email coincidences + list_mail=[] + # Count number messages coincidences + count=0 + + for item in filtered_items: + + count=count+1 + + if mail_list != 0: + list_mail.append("("+str(item.datetime_received) + ") - "+str(item.subject)+" - "+str(item.sender)) + + #print(item.subject, item.sender, item.datetime_received) + + if mail_list!= 0: + list_mail = parse_result(list_mail) + create_agent(count,list_mail) + else: + create_agent(count) +except Exception as e: + print(0) + write_to_log(f"{type(e).__name__}: {e}", log_file) + sys.exit() + +print(1) diff --git a/pandora_plugins/web_check/web_check_lwp.pl b/pandora_plugins/web_check/web_check_lwp.pl new file mode 100644 index 0000000000..73b1c0a028 --- /dev/null +++ b/pandora_plugins/web_check/web_check_lwp.pl @@ -0,0 +1,24 @@ +use strict; +use warnings; + +use LWP::UserAgent (); +use Data::Dumper; + +die "Usage: $0 \n" unless @ARGV == 3; + +my ($URL, $username, $password) = @ARGV; + +my $ua = LWP::UserAgent->new(timeout => 10); +$ua->protocols_allowed( ['http', 'https'] ); +$ua->ssl_opts("verify_hostname" => 0); + +$ua->credentials($URL, "", $username, $password); + +my $response = $ua->get($URL); + +if ($response->is_success) { + print $response->decoded_content; +} +else { + die print(Dumper($response)); +} diff --git a/pandora_server/DEBIAN/control b/pandora_server/DEBIAN/control index 89e3bbbb8c..f9be42317e 100644 --- a/pandora_server/DEBIAN/control +++ b/pandora_server/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-server -Version: 7.0NG.775-240212 +Version: 7.0NG.775-240227 Architecture: all Priority: optional Section: admin diff --git a/pandora_server/DEBIAN/make_deb_package.sh b/pandora_server/DEBIAN/make_deb_package.sh index 0341fc9788..f16c410ee6 100644 --- a/pandora_server/DEBIAN/make_deb_package.sh +++ b/pandora_server/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.775-240212" +pandora_version="7.0NG.775-240227" package_cpan=0 package_pandora=1 diff --git a/pandora_server/conf/pandora_server.conf.new b/pandora_server/conf/pandora_server.conf.new index 1945cbd08f..f7d4df74aa 100644 --- a/pandora_server/conf/pandora_server.conf.new +++ b/pandora_server/conf/pandora_server.conf.new @@ -816,5 +816,8 @@ madeserver_autofit 7d # Model sensitivity. A lower value triggers less anomalies (PANDORA FMS ENTERPRISE ONLY). madeserver_sensitivity 0.1 +# If greater than 0, generate an event when more than the specified number of XML data files are queued for an agent. +too_many_xml 10 + # Encoding to use on mail subject (MIME-Header by default) -# mail_subject_encoding MIME-Header-ISO_2022_JP \ No newline at end of file +# mail_subject_encoding MIME-Header-ISO_2022_JP diff --git a/pandora_server/lib/PandoraFMS/Config.pm b/pandora_server/lib/PandoraFMS/Config.pm index 87ef38e8e5..6853324266 100644 --- a/pandora_server/lib/PandoraFMS/Config.pm +++ b/pandora_server/lib/PandoraFMS/Config.pm @@ -46,7 +46,7 @@ our @EXPORT = qw( # version: Defines actual version of Pandora Server for this module only my $pandora_version = "7.0NG.775"; -my $pandora_build = "240212"; +my $pandora_build = "240227"; our $VERSION = $pandora_version." ".$pandora_build; # Setup hash @@ -589,6 +589,8 @@ sub pandora_load_config { $pa_config->{"madeserver"} = 0; # 774. + $pa_config->{"too_many_xml"} = 10; # 776. + $pa_config->{"mail_subject_encoding"} = 'MIME-Header'; # 776. # Check for UID0 @@ -1417,6 +1419,9 @@ sub pandora_load_config { elsif ($parametro =~ m/^madeserver\s+([0-1])/i){ $pa_config->{'madeserver'}= clean_blank($1); } + elsif ($parametro =~ m/^too_many_xml\s+([0-9]*)/i){ + $pa_config->{'too_many_xml'}= clean_blank($1); + } } # end of loop for parameter # # The DB host was overridden by pandora_ha. diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm index 21ba802908..5d3d34f870 100644 --- a/pandora_server/lib/PandoraFMS/Core.pm +++ b/pandora_server/lib/PandoraFMS/Core.pm @@ -2428,7 +2428,7 @@ sub pandora_process_module ($$$$$$$$$;$) { } # Active ff interval - if ($module->{'module_ff_interval'} != 0) { + if ($module->{'module_ff_interval'} != 0 && $min_ff_event > 0 && $last_known_status != $status) { $current_interval = $module->{'module_ff_interval'}; } } @@ -7197,12 +7197,15 @@ sub pandora_disable_autodisable_agents ($$) { SELECT tm.id_agente, count(*) as sync_modules, ta.unknown_count FROM tagente_modulo tm JOIN tagente ta ON ta.id_agente = tm.id_agente + LEFT JOIN tagente_estado te ON tm.id_agente_modulo = te.id_agente_modulo WHERE ta.disabled = 0 + AND ta.modo=2 + AND te.estado != 4 + AND tm.delete_pending=0 AND NOT ((id_tipo_modulo >= 21 AND id_tipo_modulo <= 23) OR id_tipo_modulo = 100) GROUP BY tm.id_agente ) AS subquery - WHERE subquery.unknown_count >= subquery.sync_modules;'; - + WHERE subquery.unknown_count >= subquery.sync_modules;'; my @agents_autodisabled = get_db_rows ($dbh, $sql); return if ($#agents_autodisabled < 0); @@ -7767,12 +7770,12 @@ sub safe_mode($$$$$$) { # Going to critical. Disable the rest of the modules. if ($new_status == MODULE_CRITICAL) { logger($pa_config, "Enabling safe mode for agent " . $agent->{'nombre'}, 10); - db_do($dbh, 'UPDATE tagente_modulo SET disabled=1 WHERE id_agente=? AND id_agente_modulo!=?', $agent->{'id_agente'}, $module->{'id_agente_modulo'}); + db_do($dbh, 'UPDATE tagente_modulo SET disabled=1, disabled_by_safe_mode=1 WHERE id_agente=? AND id_agente_modulo!=? AND disabled=0', $agent->{'id_agente'}, $module->{'id_agente_modulo'}); } # Coming back from critical. Enable the rest of the modules. elsif ($known_status == MODULE_CRITICAL) { logger($pa_config, "Disabling safe mode for agent " . $agent->{'nombre'}, 10); - db_do($dbh, 'UPDATE tagente_modulo SET disabled=0 WHERE id_agente=? AND id_agente_modulo!=?', $agent->{'id_agente'}, $module->{'id_agente_modulo'}); + db_do($dbh, 'UPDATE tagente_modulo SET disabled=0, disabled_by_safe_mode=0 WHERE id_agente=? AND id_agente_modulo!=? AND disabled_by_safe_mode=1', $agent->{'id_agente'}, $module->{'id_agente_modulo'}); # Prevent the modules from becoming unknown! db_do ($dbh, 'UPDATE tagente_estado SET utimestamp = ? WHERE id_agente = ? AND id_agente_modulo!=?', time(), $agent->{'id_agente'}, $module->{'id_agente_modulo'}); @@ -7798,7 +7801,7 @@ sub pandora_safe_mode_modules_update { # If status is critical, disable the rest of the modules. if ($status == MODULE_CRITICAL) { logger($pa_config, "Update modules for safe mode agent with alias:" . $agent->{'alias'} . ".", 10); - db_do($dbh, 'UPDATE tagente_modulo SET disabled=1 WHERE id_agente=? AND id_agente_modulo!=?', $agent_id, $agent->{'safe_mode_module'}); + db_do($dbh, 'UPDATE tagente_modulo SET disabled=1, disabled_by_safe_mode=1 WHERE id_agente=? AND id_agente_modulo!=? AND disabled=0', $agent_id, $agent->{'safe_mode_module'}); } } diff --git a/pandora_server/lib/PandoraFMS/DataServer.pm b/pandora_server/lib/PandoraFMS/DataServer.pm index 6125a68e20..cb2c5afc4c 100644 --- a/pandora_server/lib/PandoraFMS/DataServer.pm +++ b/pandora_server/lib/PandoraFMS/DataServer.pm @@ -56,6 +56,7 @@ our @ISA = qw(PandoraFMS::ProducerConsumerServer); my @TaskQueue :shared; my %PendingTasks :shared; my %Agents :shared; +my %AgentCounts; my $Sem :shared; my $TaskSem :shared; my $AgentSem :shared; @@ -73,6 +74,7 @@ sub new ($$;$) { @TaskQueue = (); %PendingTasks = (); %Agents = (); + %AgentCounts = (); $Sem = Thread::Semaphore->new; $TaskSem = Thread::Semaphore->new (0); $AgentSem = Thread::Semaphore->new (1); @@ -142,6 +144,9 @@ sub data_producer ($) { opendir (DIR, $pa_config->{'incomingdir'}) || die "[FATAL] Cannot open Incoming data directory at " . $pa_config->{'incomingdir'} . ": $!"; + # Reset agent XML file counts + %AgentCounts = (); + # Do not read more than max_queue_files files my $file_count = 0; while (my $file = readdir (DIR)) { @@ -177,11 +182,21 @@ sub data_producer ($) { next if ($file !~ /^(.*)[\._]\d+\.data$/); my $agent_name = $1; + $AgentCounts{$agent_name} = defined($AgentCounts{$agent_name}) ? $AgentCounts{$agent_name} + 1 : 1; next if (agent_lock($pa_config, $dbh, $agent_name) == 0); push (@tasks, $file); } + # Generate an event if there are too many XML files for a given agent. + if ($pa_config->{'too_many_xml'} > 0) { + while (my ($agent_name, $xml_count) = each(%AgentCounts)) { + if ($xml_count > $pa_config->{'too_many_xml'}) { + pandora_timed_event(300, $pa_config, "More than " . $pa_config->{'too_many_xml'} . " XML files queued for agent $agent_name", 0, 0, 0, 0, 0, 'warning', 0, $dbh); + } + } + } + return @tasks; } @@ -200,6 +215,9 @@ sub data_producer_smart_queue ($) { opendir (DIR, $pa_config->{'incomingdir'}) || die "[FATAL] Cannot open Incoming data directory at " . $pa_config->{'incomingdir'} . ": $!"; + # Reset agent XML file counts + %AgentCounts = (); + # Do not read more than max_queue_files files my $smart_queue = {}; while (my $file = readdir (DIR)) { @@ -209,6 +227,9 @@ sub data_producer_smart_queue ($) { next if ($file !~ /^(.*)[\._]\d+\.data$/); my $agent_name = $1; + # Update per agent XML counts. + $AgentCounts{$agent_name} = defined($AgentCounts{$agent_name}) ? $AgentCounts{$agent_name} + 1 : 1; + # Queue a new file. if (!defined($smart_queue->{$agent_name})) { $smart_queue->{$agent_name} = $file; @@ -229,6 +250,15 @@ sub data_producer_smart_queue ($) { push (@tasks, $file); } + # Generate an event if there are too many XML files for a given agent. + if ($pa_config->{'too_many_xml'} > 0) { + while (my ($agent_name, $xml_count) = each(%AgentCounts)) { + if ($xml_count > $pa_config->{'too_many_xml'}) { + pandora_timed_event(300, $pa_config, "More than " . $pa_config->{'too_many_xml'} . " XML files queued for agent $agent_name", 0, 0, 0, 0, 0, 'warning', 0, $dbh); + } + } + } + return @tasks; } @@ -377,19 +407,7 @@ sub process_xml_data ($$$$$) { # Modify the timestamp with the timezone_offset logger($pa_config, "Applied a timezone offset of $timestamp to agent " . $data->{'agent_name'}, 10); - - # Calculate the start date to add the offset - my $utimestamp = 0; - eval { - if ($timestamp =~ /(\d+)[\/|\-](\d+)[\/|\-](\d+) +(\d+):(\d+):(\d+)/) { - $utimestamp = strftime("%s", $6, $5, $4, $3, $2 -1 , $1 - 1900); - } - }; - - # Apply the offset if there were no errors - if (! $@ && $utimestamp != 0) { - $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp + ($timezone_offset * 3600))); - } + $timestamp = apply_timezone_offset($timestamp, $timezone_offset); } # Check some variables @@ -637,6 +655,11 @@ sub process_xml_data ($$$$$) { # Single data if (! defined ($module_data->{'datalist'})) { my $data_timestamp = get_tag_value ($module_data, 'timestamp', $timestamp); + if ($pa_config->{'use_xml_timestamp'} eq '0' && defined($timestamp)) { + $data_timestamp = $timestamp; + } + $data_timestamp = apply_timezone_offset($data_timestamp, $timezone_offset); + process_module_data ($pa_config, $module_data, $server_id, $agent, $module_name, $module_type, $interval, $data_timestamp, $dbh, $new_agent); next; } @@ -654,10 +677,10 @@ sub process_xml_data ($$$$$) { $module_data->{'data'} = $data->{'value'}; my $data_timestamp = get_tag_value ($data, 'timestamp', $timestamp); - if ($pa_config->{'use_xml_timestamp'} eq '0' && defined($timestamp)) { $data_timestamp = $timestamp; } + $data_timestamp = apply_timezone_offset($data_timestamp, $timezone_offset); process_module_data ($pa_config, $module_data, $server_id, $agent, $module_name, $module_type, $interval, $data_timestamp, $dbh, $new_agent); diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 1e64879373..972f259bb5 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -477,7 +477,7 @@ sub exec_recon_app ($$$) { # No output message. if (!defined($output_json)) { - push(@summary, "The execution returned no output."); + push(@summary, "The execution returned no output. Is the server out of memory?"); next; } @@ -1118,6 +1118,30 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { return unless ($self->is_snmp_discovered($device)); my $community = $self->get_community($device); + my $snmp3_creds = undef; + if(defined($self->{'snmp3_auth_key'}{$device})) { + $snmp3_creds = $self->snmp3_credentials($self->{'snmp3_auth_key'}{$device}); + } + my $snmp3_params = { + 'custom_string_1' => '', + 'custom_string_2' => '', + 'custom_string_3' => '', + 'plugin_parameter' => '', + 'plugin_user' => '', + 'plugin_pass' => '' + }; + if(defined($snmp3_creds)) { + $community = $snmp3_creds->{'community'}; + $snmp3_params = { + 'custom_string_1' => $snmp3_creds->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_creds->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_creds->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_creds->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_creds->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_creds->{'snmp_auth_pass'} + }; + } + my @output = $self->snmp_get_value_array($device, $PandoraFMS::Recon::Base::IFINDEX); foreach my $if_index (@output) { next unless ($if_index =~ /^[0-9]+$/); @@ -1153,12 +1177,12 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { ), 'ip_target' => $device, 'tcp_send' => $self->{'task_data'}{'snmp_version'}, - 'custom_string_1' => $self->{'task_data'}{'snmp_privacy_method'}, - 'custom_string_2' => $self->{'task_data'}{'snmp_privacy_pass'}, - 'custom_string_3' => $self->{'task_data'}{'snmp_security_level'}, - 'plugin_parameter' => $self->{'task_data'}{'snmp_auth_method'}, - 'plugin_user' => $self->{'task_data'}{'snmp_auth_user'}, - 'plugin_pass' => $self->{'task_data'}{'snmp_auth_pass'}, + 'custom_string_1' => $snmp3_params->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_params->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_params->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_params->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_params->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_params->{'snmp_auth_pass'}, 'snmp_community' => $community, 'snmp_oid' => "$PandoraFMS::Recon::Base::IFOPERSTATUS.$if_index", 'unit' => '' @@ -1183,12 +1207,12 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { ), 'ip_target' => $device, 'tcp_send' => $self->{'task_data'}{'snmp_version'}, - 'custom_string_1' => $self->{'task_data'}{'snmp_privacy_method'}, - 'custom_string_2' => $self->{'task_data'}{'snmp_privacy_pass'}, - 'custom_string_3' => $self->{'task_data'}{'snmp_security_level'}, - 'plugin_parameter' => $self->{'task_data'}{'snmp_auth_method'}, - 'plugin_user' => $self->{'task_data'}{'snmp_auth_user'}, - 'plugin_pass' => $self->{'task_data'}{'snmp_auth_pass'}, + 'custom_string_1' => $snmp3_params->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_params->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_params->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_params->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_params->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_params->{'snmp_auth_pass'}, 'snmp_community' => $community, 'snmp_oid' => "$PandoraFMS::Recon::Base::IFHCINOCTECTS.$if_index", 'unit' => safe_input('bytes/s') @@ -1210,12 +1234,12 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { ), 'ip_target' => $device, 'tcp_send' => $self->{'task_data'}{'snmp_version'}, - 'custom_string_1' => $self->{'task_data'}{'snmp_privacy_method'}, - 'custom_string_2' => $self->{'task_data'}{'snmp_privacy_pass'}, - 'custom_string_3' => $self->{'task_data'}{'snmp_security_level'}, - 'plugin_parameter' => $self->{'task_data'}{'snmp_auth_method'}, - 'plugin_user' => $self->{'task_data'}{'snmp_auth_user'}, - 'plugin_pass' => $self->{'task_data'}{'snmp_auth_pass'}, + 'custom_string_1' => $snmp3_params->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_params->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_params->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_params->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_params->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_params->{'snmp_auth_pass'}, 'snmp_community' => $community, 'snmp_oid' => "$PandoraFMS::Recon::Base::IFINOCTECTS.$if_index", 'unit' => safe_input('bytes/s') @@ -1241,12 +1265,12 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { ), 'ip_target' => $device, 'tcp_send' => $self->{'task_data'}{'snmp_version'}, - 'custom_string_1' => $self->{'task_data'}{'snmp_privacy_method'}, - 'custom_string_2' => $self->{'task_data'}{'snmp_privacy_pass'}, - 'custom_string_3' => $self->{'task_data'}{'snmp_security_level'}, - 'plugin_parameter' => $self->{'task_data'}{'snmp_auth_method'}, - 'plugin_user' => $self->{'task_data'}{'snmp_auth_user'}, - 'plugin_pass' => $self->{'task_data'}{'snmp_auth_pass'}, + 'custom_string_1' => $snmp3_params->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_params->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_params->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_params->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_params->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_params->{'snmp_auth_pass'}, 'snmp_community' => $community, 'snmp_oid' => "$PandoraFMS::Recon::Base::IFHCOUTOCTECTS.$if_index", 'unit' => safe_input('bytes/s') @@ -1268,12 +1292,12 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { ), 'ip_target' => $device, 'tcp_send' => $self->{'task_data'}{'snmp_version'}, - 'custom_string_1' => $self->{'task_data'}{'snmp_privacy_method'}, - 'custom_string_2' => $self->{'task_data'}{'snmp_privacy_pass'}, - 'custom_string_3' => $self->{'task_data'}{'snmp_security_level'}, - 'plugin_parameter' => $self->{'task_data'}{'snmp_auth_method'}, - 'plugin_user' => $self->{'task_data'}{'snmp_auth_user'}, - 'plugin_pass' => $self->{'task_data'}{'snmp_auth_pass'}, + 'custom_string_1' => $snmp3_params->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_params->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_params->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_params->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_params->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_params->{'snmp_auth_pass'}, 'snmp_community' => $community, 'snmp_oid' => "$PandoraFMS::Recon::Base::IFOUTOCTECTS.$if_index", 'unit' => safe_input('bytes/s') @@ -1305,19 +1329,19 @@ sub PandoraFMS::Recon::Base::create_interface_modules($$) { # Interface index filter. $macros->{'5'}->{'value'} = $if_index; # SecurityName. - $macros->{'6'}->{'value'} = $self->{'task_data'}->{'snmp_auth_user'}; + $macros->{'6'}->{'value'} = $snmp3_params->{'snmp_auth_user'}; # SecurityContext. $macros->{'7'}->{'value'} = $community; # SecurityLevel. - $macros->{'8'}->{'value'} = $self->{'task_data'}->{'snmp_security_level'}; + $macros->{'8'}->{'value'} = $snmp3_params->{'snmp_security_level'}; # AuthProtocol. - $macros->{'9'}->{'value'} = $self->{'task_data'}->{'snmp_auth_method'}; + $macros->{'9'}->{'value'} = $snmp3_params->{'snmp_auth_method'}; # AuthKey. - $macros->{'10'}->{'value'} = $self->{'task_data'}->{'snmp_auth_pass'}; + $macros->{'10'}->{'value'} = $snmp3_params->{'snmp_auth_pass'}; # PrivProtocol. - $macros->{'11'}->{'value'} = $self->{'task_data'}->{'snmp_privacy_method'}; + $macros->{'11'}->{'value'} = $snmp3_params->{'snmp_privacy_method'}; # PrivKey. - $macros->{'12'}->{'value'} = $self->{'task_data'}->{'snmp_privacy_pass'}; + $macros->{'12'}->{'value'} = $snmp3_params->{'snmp_privacy_pass'}; # Hash identifier. $macros->{'13'}->{'value'} = PandoraFMS::Tools::generate_agent_name_hash($if_name, $device); # Get input usage. @@ -1429,6 +1453,7 @@ sub PandoraFMS::Recon::Base::create_wmi_modules { { 'ip_target' => $target, 'snmp_oid' => "SELECT LoadPercentage FROM Win32_Processor WHERE DeviceId=\'$cpu\'", + 'tcp_send' => $creds->{'extra_1'}, 'plugin_user' => $creds->{'username'}, 'plugin_pass' => $creds->{'password'}, 'tcp_port' => 1, @@ -1449,6 +1474,7 @@ sub PandoraFMS::Recon::Base::create_wmi_modules { { 'ip_target' => $target, 'snmp_oid' => "SELECT FreePhysicalMemory, TotalVisibleMemorySize FROM Win32_OperatingSystem", + 'tcp_send' => $creds->{'extra_1'}, 'plugin_user' => $creds->{'username'}, 'plugin_pass' => $creds->{'password'}, 'tcp_port' => 0, @@ -1469,6 +1495,7 @@ sub PandoraFMS::Recon::Base::create_wmi_modules { { 'ip_target' => $target, 'snmp_oid' => "SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID='$unit'", + 'tcp_send' => $creds->{'extra_1'}, 'plugin_user' => $creds->{'username'}, 'plugin_pass' => $creds->{'password'}, 'tcp_port' => 1, @@ -1510,14 +1537,7 @@ sub PandoraFMS::Recon::Base::create_network_profile_modules($$) { # 1. Retrieve template info. my $template = get_nc_profile_advanced($self->{'dbh'}, $t_id); - # 2. Verify Private Enterprise Number matches (PEN) - if (defined($template->{'pen'})) { - my @pens = split(',', $template->{'pen'}); - - next unless (is_in_array(\@pens, $self->get_pen($device))); - } - - # 3. Retrieve module list from target template. + # 2. Retrieve module list from target template. my @np_components = get_db_rows( $self->{'dbh'}, 'SELECT * FROM tnetwork_profile_component WHERE id_np = ?', @@ -1525,7 +1545,7 @@ sub PandoraFMS::Recon::Base::create_network_profile_modules($$) { ); foreach my $np_component (@np_components) { - # 4. Register each module (candidate). 'add_module' will test them. + # 3. Register each module (candidate). 'add_module' will test them. my $component = get_db_single_row( $self->{'dbh'}, 'SELECT * FROM tnetwork_component WHERE id_nc = ?', @@ -1543,18 +1563,45 @@ sub PandoraFMS::Recon::Base::create_network_profile_modules($$) { } $component->{'name'} = safe_output($component->{'name'}); - if ($component->{'type'} >= 15 && $component->{'type'} <= 18) { - $component->{'snmp_community'} = safe_output($self->get_community($device)); + # SNMP Modules + if ($self->is_snmp_discovered($device) && $component->{'type'} >= 15 && $component->{'type'} <= 18) { + my $snmp3_creds = undef; + my $community = safe_output($self->get_community($device)); + if(defined($self->{'snmp3_auth_key'}{$device})) { + $snmp3_creds = $self->snmp3_credentials($self->{'snmp3_auth_key'}{$device}); + } + my $snmp3_params = { + 'custom_string_1' => '', + 'custom_string_2' => '', + 'custom_string_3' => '', + 'plugin_parameter' => '', + 'plugin_user' => '', + 'plugin_pass' => '' + }; + if(defined($snmp3_creds)) { + $community = $snmp3_creds->{'community'}; + $snmp3_params = { + 'custom_string_1' => $snmp3_creds->{'snmp_privacy_method'}, + 'custom_string_2' => $snmp3_creds->{'snmp_privacy_pass'}, + 'custom_string_3' => $snmp3_creds->{'snmp_security_level'}, + 'plugin_parameter' => $snmp3_creds->{'snmp_auth_method'}, + 'plugin_user' => $snmp3_creds->{'snmp_auth_user'}, + 'plugin_pass' => $snmp3_creds->{'snmp_auth_pass'} + }; + } + + $component->{'snmp_community'} = $community; $component->{'tcp_send'} = $self->{'snmp_version'}; - $component->{'custom_string_1'} = $self->{'snmp_privacy_method'}; - $component->{'custom_string_2'} = $self->{'snmp_privacy_pass'}; - $component->{'custom_string_3'} = $self->{'snmp_security_level'}; - $component->{'plugin_parameter'} = $self->{'snmp_auth_method'}; - $component->{'plugin_user'} = $self->{'snmp_auth_user'}; - $component->{'plugin_pass'} = $self->{'snmp_auth_pass'}; + $component->{'custom_string_1'} = $snmp3_params->{'snmp_privacy_method'}; + $component->{'custom_string_2'} = $snmp3_params->{'snmp_privacy_pass'}; + $component->{'custom_string_3'} = $snmp3_params->{'snmp_security_level'}; + $component->{'plugin_parameter'} = $snmp3_params->{'snmp_auth_method'}; + $component->{'plugin_user'} = $snmp3_params->{'snmp_auth_user'}; + $component->{'plugin_pass'} = $snmp3_params->{'snmp_auth_pass'}; } - if ($component->{'type'} >= 34 && $component->{'type'} <= 37) { + # RCMD Modules + if ($self->rcmd_responds($device) && $component->{'type'} >= 34 && $component->{'type'} <= 37) { # Update module credentials. $component->{'custom_string_1'} = $self->rcmd_credentials_key($device); $component->{'custom_string_2'} = pandora_get_os_by_id( @@ -1563,9 +1610,18 @@ sub PandoraFMS::Recon::Base::create_network_profile_modules($$) { ); } + # WMI Modules + if ($self->wmi_responds($device) && $component->{'id_modulo'} == 6) { + my $key = $self->wmi_credentials_key($device); + my $creds = $self->call('get_credentials', $key); + $component->{'tcp_send'} = $creds->{'extra_1'}; + $component->{'plugin_user'} = $creds->{'username'}; + $component->{'plugin_pass'} = $creds->{'password'}; + } + $component->{'__module_component'} = 1; - # 3. Try to register module into monitoring list. + # 4. Try to register module into monitoring list. $self->call('add_module', $device, $component); } } @@ -1576,13 +1632,23 @@ sub PandoraFMS::Recon::Base::create_network_profile_modules($$) { # Retrieve a key from credential store. ################################################################################ sub PandoraFMS::Recon::Base::get_credentials { - my ($self, $key_index) = @_; + my ($self, $key_index, $product) = @_; - return credential_store_get_key( + my $cred = credential_store_get_key( $self->{'pa_config'}, $self->{'dbh'}, $key_index ); + + if(defined($product)) { + if($product eq $cred->{'product'}) { + return $cred; + } else { + return undef; + } + } + + return $cred; } ################################################################################ diff --git a/pandora_server/lib/PandoraFMS/PluginTools.pm b/pandora_server/lib/PandoraFMS/PluginTools.pm index 5cf159ff28..a621790a38 100644 --- a/pandora_server/lib/PandoraFMS/PluginTools.pm +++ b/pandora_server/lib/PandoraFMS/PluginTools.pm @@ -34,7 +34,7 @@ our @ISA = qw(Exporter); # version: Defines actual version of Pandora Server for this module only my $pandora_version = "7.0NG.775"; -my $pandora_build = "240212"; +my $pandora_build = "240227"; our $VERSION = $pandora_version." ".$pandora_build; our %EXPORT_TAGS = ( 'all' => [ qw() ] ); diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index f21f13de4f..a84149c4dc 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -1352,10 +1352,9 @@ sub snmp_responds_v122c($$) { sub snmp_responds_v3($$) { my ($self, $device) = @_; - my $command = $self->snmp_get_command($device, ".0"); - `$command`; + $self->snmp3_credentials_calculation($device); - if ($? == 0) { + if ($self->snmp3_credentials_calculation($device)) { $self->mark_discovered($device); return 1; } @@ -1363,6 +1362,81 @@ sub snmp_responds_v3($$) { return 0; } +################################################################################ +# Get SNMP3 credentials info in HASH +################################################################################ +sub snmp3_credentials { + my ($self, $key) = @_; + + my $cred = $self->call('get_credentials', $key, 'SNMP'); + return undef if !defined($cred); + return undef if ref($cred) ne 'HASH'; + + my $extra1 = {}; + eval { + local $SIG{__DIE__}; + $extra1 = p_decode_json($self->{'pa_config'}, $cred->{'extra_1'}); + }; + if ($@) { + $self->call('message', "[".$key."] Credentials ERROR JSON: $@", 10); + return undef; + } + + return undef if $extra1->{'version'} ne '3'; + + return { + 'snmp_security_level' => $extra1->{'securityLevelV3'}, + 'snmp_privacy_method' => $extra1->{'privacyMethodV3'}, + 'snmp_privacy_pass' => $extra1->{'privacyPassV3'}, + 'snmp_auth_method' => $extra1->{'authMethodV3'}, + 'snmp_auth_user' => $extra1->{'authUserV3'}, + 'snmp_auth_pass' => $extra1->{'authPassV3'}, + 'community' => $extra1->{'community'} + }; +} + +################################################################################ +# Calculate WMI credentials for target, 1 if calculated, undef if cannot +# connect to target. Credentials could be empty (-N) +################################################################################ +sub snmp3_credentials_calculation { + my ($self, $target) = @_; + + # Test all credentials selected. + foreach my $key_index (@{$self->{'auth_strings_array'}}) { + my $cred = snmp3_credentials($key_index); + next if !defined($cred); + next if ref($cred) ne 'HASH'; + + my $auth = ''; + if ($cred->{'community'}) { # Context + $auth .= " -N \'$cred->{'community'}\' "; + } + $auth .= " -l$cred->{'snmp_security_level'} "; + if ($cred->{'snmp_security_level'} ne "noAuthNoPriv") { + $auth .= " -u$cred->{'snmp_auth_user'} -a $cred->{'snmp_auth_method'} -A \'$cred->{'snmp_auth_pass'}\' "; + } + if ($cred->{'snmp_security_level'} eq "authPriv") { + $auth .= " -x$cred->{'snmp_privacy_method'} -X \'$cred->{'snmp_privacy_pass'}\' "; + } + + $self->{'snmp3_auth'}{$target} = $auth; + $self->{'snmp3_auth_key'}{$target} = $key_index; + + my $command = $self->snmp_get_command($target, ".0"); + `$command`; + + if ($? == 0) { + return 1; + } + } + + delete($self->{'snmp3_auth'}{$target}); + delete($self->{'snmp3_auth_key'}{$target}); + + return 0; +} + ################################################################################ # Parse the local ARP cache. ################################################################################ @@ -2198,16 +2272,7 @@ sub snmp_get_command { my $command = "snmpwalk -M$DEVNULL -r$self->{'snmp_checks'} -t$self->{'snmp_timeout'} -v$self->{'snmp_version'} -On -Oe "; if ($self->{'snmp_version'} eq "3") { - if ($self->{'community'}) { # Context - $command .= " -N \'$self->{'community'}\' "; - } - $command .= " -l$self->{'snmp_security_level'} "; - if ($self->{'snmp_security_level'} ne "noAuthNoPriv") { - $command .= " -u$self->{'snmp_auth_user'} -a $self->{'snmp_auth_method'} -A \'$self->{'snmp_auth_pass'}\' "; - } - if ($self->{'snmp_security_level'} eq "authPriv") { - $command .= " -x$self->{'snmp_privacy_method'} -X \'$self->{'snmp_privacy_pass'}\' "; - } + $command .= " $self->{'snmp3_auth'}{$device} "; } else { $command .= " -c\'$community\'$vlan "; } @@ -2353,7 +2418,8 @@ sub wmi_credentials_calculation { # Test all credentials selected. foreach my $key_index (@{$self->{'auth_strings_array'}}) { - my $cred = $self->call('get_credentials', $key_index); + my $cred = $self->call('get_credentials', $key_index, 'WMI'); + next if !defined($cred); next if ref($cred) ne 'HASH'; my $auth = $cred->{'username'}.'%'.$cred->{'password'}; @@ -2431,7 +2497,8 @@ sub rcmd_credentials_calculation { # Test all credentials selected. foreach my $key_index (@{$self->{'auth_strings_array'}}) { - my $cred = $self->call('get_credentials', $key_index); + my $cred = $self->call('get_credentials', $key_index, 'CUSTOM'); + next if !defined($cred); next if ref($cred) ne 'HASH'; $rcmd->clean_ssh_lib(); diff --git a/pandora_server/lib/PandoraFMS/Tools.pm b/pandora_server/lib/PandoraFMS/Tools.pm index 543ea45556..1c8bd087c2 100755 --- a/pandora_server/lib/PandoraFMS/Tools.pm +++ b/pandora_server/lib/PandoraFMS/Tools.pm @@ -182,6 +182,7 @@ our @EXPORT = qw( check_cron_element cron_check p_pretty_json + apply_timezone_offset ); # ID of the different servers @@ -716,19 +717,23 @@ sub credential_store_get_key($$$) { my $sql = 'SELECT * FROM tcredential_store WHERE identifier = ?'; my $key = PandoraFMS::DB::get_db_single_row($dbh, $sql, $identifier); - return { - 'username' => PandoraFMS::Core::pandora_output_password( - $pa_config, - $key->{'username'} - ), - 'password' => PandoraFMS::Core::pandora_output_password( - $pa_config, - $key->{'password'} - ), - 'extra_1' => $key->{'extra_1'}, - 'extra_2' => $key->{'extra_2'}, - }; + if(defined($key)) { + return { + 'product' => $key->{'product'}, + 'username' => PandoraFMS::Core::pandora_output_password( + $pa_config, + $key->{'username'} + ), + 'password' => PandoraFMS::Core::pandora_output_password( + $pa_config, + $key->{'password'} + ), + 'extra_1' => $key->{'extra_1'}, + 'extra_2' => $key->{'extra_2'}, + }; + } + return undef; } ################################################################################ @@ -2991,6 +2996,33 @@ sub p_pretty_json { return $output; } + +################################################################################ +# Apply a timezone offset to the given timestamp. +################################################################################ +sub apply_timezone_offset { + my ($timestamp, $timezone_offset) = @_; + + # Nothing to be done. + return $timestamp if (!defined($timezone_offset) || $timezone_offset == 0); + + # Convert the timestamp to seconds. + my $utimestamp = 0; + eval { + if ($timestamp =~ /(\d+)[\/|\-](\d+)[\/|\-](\d+) +(\d+):(\d+):(\d+)/) { + $utimestamp = strftime("%s", $6, $5, $4, $3, $2 -1 , $1 - 1900); + } + }; + + # Something went wrong. + return $timestamp if ($@); + + # Apply the offset and convert back to timestamp. + $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp + ($timezone_offset * 3600))); + + return $timestamp; +} + 1; __END__ diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 81c643ab67..99b49a7b32 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -7,7 +7,7 @@ %define debug_package %{nil} %define name pandorafms_server %define version 7.0NG.775 -%define release 240212 +%define release 240227 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index eaaa04c5dd..173fa201c2 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -4,7 +4,7 @@ %global __os_install_post %{nil} %define name pandorafms_server %define version 7.0NG.775 -%define release 240212 +%define release 240227 Summary: Pandora FMS Server Name: %{name} diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index c3b3e3f82c..31b4517e22 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -9,7 +9,7 @@ # ********************************************************************** PI_VERSION="7.0NG.775" -PI_BUILD="240212" +PI_BUILD="240227" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 7582caff5b..b1e26bd473 100755 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -38,7 +38,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.775 Build 240212"; +my $version = "7.0NG.775 Build 240227"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_ha.pl b/pandora_server/util/pandora_ha.pl index 829cf78505..28ae0df795 100755 --- a/pandora_server/util/pandora_ha.pl +++ b/pandora_server/util/pandora_ha.pl @@ -58,6 +58,9 @@ my $Restart = 0; # Controlled exit my $Running = 0; +# License +my $License; + ######################################################################## # Print the given message with a preceding timestamp. ######################################################################## @@ -359,6 +362,27 @@ sub ha_update_server($$) { } +############################################################################### +# Restart pandora server on demand. +############################################################################### +sub ha_restart_server($$) { + my ($config, $dbh) = @_; + my $OSNAME = $^O; + + my $current_license; + if (!defined($License)) { + $License = get_db_value($dbh, 'SELECT `value` FROM `tupdate_settings` WHERE `key` = "customer_key"'); + $current_license = $License; + } else { + $current_license = get_db_value($dbh, 'SELECT `value` FROM `tupdate_settings` WHERE `key` = "customer_key"'); + } + + if($License ne $current_license) { + ha_restart_pandora($config); + $License = $current_license; + } +} + ################################################################################ # Dump the list of known databases to disk. ################################################################################ @@ -418,16 +442,6 @@ sub ha_database_connect_pandora($) { # Select a new master database. my ($dbh, $utimestamp, $max_utimestamp) = (undef, undef, -1); - my @disabled_nodes = get_disabled_nodes($conf); - - # If there are disabled nodes ignore them from the HA_DB_Hosts. - if(scalar @disabled_nodes ne 0){ - @HA_DB_Hosts = grep { my $item = $_; !grep { $_ eq $item } @disabled_nodes } @HA_DB_Hosts; - - my $data = join(",", @disabled_nodes); - log_message($conf, 'LOG', "Ignoring disabled hosts: " . $data); - } - foreach my $ha_dbhost (@HA_DB_Hosts) { # Retry each database ha_connect_retries times. @@ -454,6 +468,13 @@ sub ha_database_connect_pandora($) { # No luck. Try the next database. next unless defined($dbh); + # Check if database is disabled. + if (defined(get_db_value($dbh, 'SELECT `id` FROM `tdatabase` WHERE `host` = "' . $ha_dbhost . '" AND disabled = 1'))) + { + log_message($conf, 'LOG', "Ignoring disabled host: " . $ha_dbhost); + db_disconnect($dbh); + next; + } eval { # Get the most recent utimestamp from the database. $utimestamp = get_db_value($dbh, 'SELECT UNIX_TIMESTAMP(MAX(keepalive)) FROM tserver'); @@ -518,36 +539,6 @@ sub ha_restart_pandora($) { `$config->{'pandora_service_cmd'} $control_command 2>/dev/null`; } -############################################################################### -# Get ip of the disabled nodes. -############################################################################### -sub get_disabled_nodes($) { - my ($conf) = @_; - - my $dbh = db_connect('mysql', - $conf->{'dbname'}, - $conf->{'dbhost'}, - $conf->{'dbport'}, - $conf->{'ha_dbuser'}, - $conf->{'ha_dbpass'}); - - my $disabled_nodes = get_db_value($dbh, "SELECT value FROM tconfig WHERE token = 'ha_disabled_nodes'"); - - if(!defined($disabled_nodes) || $disabled_nodes eq ""){ - $disabled_nodes = ','; - } - - my @disabled_nodes = split(',', $disabled_nodes); - - if(scalar @disabled_nodes ne 0){ - $disabled_nodes = join(",", @disabled_nodes); - @disabled_nodes = get_db_rows($dbh, "SELECT host FROM tdatabase WHERE id IN ($disabled_nodes)"); - @disabled_nodes = map { $_->{host} } @disabled_nodes; - } - - return @disabled_nodes; -} - ############################################################################### # Main (Pacemaker) ############################################################################### @@ -691,6 +682,9 @@ sub ha_main_pandora($) { # Check if there are updates pending. ha_update_server($conf, $dbh); + # Check restart server on demand. + ha_restart_server($conf, $dbh); + # Keep pandora running ha_keep_pandora_running($conf, $dbh); @@ -716,6 +710,9 @@ sub ha_main_pandora($) { # Execute resync actions. enterprise_hook('pandoraha_resync_dbs', [$conf, $dbh, $DB_Host, \@HA_DB_Hosts]); + # Update and push HA databases info to Metaconsole or nodes. + enterprise_hook('pandoraha_update_and_push_databases_info', [$conf, $dbh]); + # Synchronize nodes. enterprise_hook('pandoraha_sync_node', [$conf, $dbh]); }; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index bdd263b1a8..3200b71f46 100755 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.775 Build 240212"; +my $version = "7.0NG.775 Build 240227"; # save program name for logging my $progname = basename($0); @@ -5398,7 +5398,7 @@ sub cli_get_agent_status() { ############################################################################## sub cli_get_agents_id_name_by_alias() { - my $agent_alias = @ARGV[2]; + my $agent_alias = safe_input(@ARGV[2]); my $strict = @ARGV[3]; my @agents; my $where_value; @@ -5418,14 +5418,13 @@ sub cli_get_agents_id_name_by_alias() { print "[ERROR] No agents retrieved.\n\n"; } else { if(is_metaconsole($conf) == 1) { - print "alias, id_agente, id_tagente, id_server, server_name\n"; + print "id_agente, alias, id_tagente, id_server, server_name\n"; foreach my $agent (@agents) { - - print safe_output($agent->{'alias'}).", ".$agent->{'id_agente'}.", ".$agent->{'id_tagente'}.", ".$agent->{'id_server'}.", ".$agent->{'server_name'}."\n"; + print $agent->{'id_agente'}.", ".safe_output($agent->{'alias'}).", ".$agent->{'id_tagente'}.", ".$agent->{'id_server'}.", ".$agent->{'server_name'}."\n"; } } else { - print "alias, id_agente\n"; + print "id_agente, alias\n"; foreach my $agent (@agents) { print $agent->{'id_agente'}.",".safe_output($agent->{'alias'})."\n";