diff --git a/pandora_agents/pc/AIX/pandora_agent.conf b/pandora_agents/pc/AIX/pandora_agent.conf index 3045e6d120..a22cebc516 100644 --- a/pandora_agents/pc/AIX/pandora_agent.conf +++ b/pandora_agents/pc/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, AIX version +# Version 7.0NG.714, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/FreeBSD/pandora_agent.conf b/pandora_agents/pc/FreeBSD/pandora_agent.conf index 95c66d2b2f..18e8a21aad 100644 --- a/pandora_agents/pc/FreeBSD/pandora_agent.conf +++ b/pandora_agents/pc/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, FreeBSD Version +# Version 7.0NG.714, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/HP-UX/pandora_agent.conf b/pandora_agents/pc/HP-UX/pandora_agent.conf index e45185794c..19c970f98a 100644 --- a/pandora_agents/pc/HP-UX/pandora_agent.conf +++ b/pandora_agents/pc/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, HP-UX Version +# Version 7.0NG.714, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Linux/pandora_agent.conf b/pandora_agents/pc/Linux/pandora_agent.conf index cf0cee7960..c777a2e7fb 100644 --- a/pandora_agents/pc/Linux/pandora_agent.conf +++ b/pandora_agents/pc/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, GNU/Linux +# Version 7.0NG.714, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/NT4/pandora_agent.conf b/pandora_agents/pc/NT4/pandora_agent.conf index d072cce2b4..749548f2c0 100644 --- a/pandora_agents/pc/NT4/pandora_agent.conf +++ b/pandora_agents/pc/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, GNU/Linux +# Version 7.0NG.714, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/SunOS/pandora_agent.conf b/pandora_agents/pc/SunOS/pandora_agent.conf index c11526deed..bb83684a4d 100644 --- a/pandora_agents/pc/SunOS/pandora_agent.conf +++ b/pandora_agents/pc/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, Solaris Version +# Version 7.0NG.714, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Win32/pandora_agent.conf b/pandora_agents/pc/Win32/pandora_agent.conf index c70a49cdfb..49c1784938 100644 --- a/pandora_agents/pc/Win32/pandora_agent.conf +++ b/pandora_agents/pc/Win32/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2010 Artica Soluciones Tecnologicas -# Version 7.0NG.712 +# Version 7.0NG.714 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/shellscript/aix/pandora_agent.conf b/pandora_agents/shellscript/aix/pandora_agent.conf index 639b2e8911..4387ba2911 100644 --- a/pandora_agents/shellscript/aix/pandora_agent.conf +++ b/pandora_agents/shellscript/aix/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.712, AIX version +# Version 7.0NG.714, AIX version # General Parameters # ================== diff --git a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf index 98ba116947..aa89be6fcc 100644 --- a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf +++ b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.712 +# Version 7.0NG.714 # FreeBSD/IPSO version # Licenced under GPL licence, 2003-2007 Sancho Lerena diff --git a/pandora_agents/shellscript/hp-ux/pandora_agent.conf b/pandora_agents/shellscript/hp-ux/pandora_agent.conf index e29d608225..12bcbc5beb 100644 --- a/pandora_agents/shellscript/hp-ux/pandora_agent.conf +++ b/pandora_agents/shellscript/hp-ux/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.712, HPUX Version +# Version 7.0NG.714, HPUX Version # General Parameters # ================== diff --git a/pandora_agents/shellscript/linux/pandora_agent.conf b/pandora_agents/shellscript/linux/pandora_agent.conf index a021f7a477..1038178d4b 100644 --- a/pandora_agents/shellscript/linux/pandora_agent.conf +++ b/pandora_agents/shellscript/linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712 +# Version 7.0NG.714 # Licensed under GPL license v2, # (c) 2003-2010 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/mac_osx/pandora_agent.conf b/pandora_agents/shellscript/mac_osx/pandora_agent.conf index ffbc3657c2..da27975054 100644 --- a/pandora_agents/shellscript/mac_osx/pandora_agent.conf +++ b/pandora_agents/shellscript/mac_osx/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712 +# Version 7.0NG.714 # Licensed under GPL license v2, # (c) 2003-2009 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/openWRT/pandora_agent.conf b/pandora_agents/shellscript/openWRT/pandora_agent.conf index f0a7023390..06f42c5dba 100644 --- a/pandora_agents/shellscript/openWRT/pandora_agent.conf +++ b/pandora_agents/shellscript/openWRT/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712 +# Version 7.0NG.714 # Licensed under GPL license v2, # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/solaris/pandora_agent.conf b/pandora_agents/shellscript/solaris/pandora_agent.conf index 39f27650ac..2c75ad952e 100644 --- a/pandora_agents/shellscript/solaris/pandora_agent.conf +++ b/pandora_agents/shellscript/solaris/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.712, Solaris version +# Version 7.0NG.714, Solaris version # General Parameters # ================== diff --git a/pandora_agents/unix/AIX/pandora_agent.conf b/pandora_agents/unix/AIX/pandora_agent.conf index 4fc8c757ba..d80b2d00e2 100644 --- a/pandora_agents/unix/AIX/pandora_agent.conf +++ b/pandora_agents/unix/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, AIX version +# Version 7.0NG.714, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -58,6 +58,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # Server password (Tentacle or FTP). Leave empty for no password (default). # server_pwd mypassword diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 2469475802..d1bb3b69a5 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.712-170908 +Version: 7.0NG.714-171030 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 fa27849ada..f72ddc5b1b 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.712-170908" +pandora_version="7.0NG.714-171030" 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/Darwin/pandora_agent.conf b/pandora_agents/unix/Darwin/pandora_agent.conf index 41c6747052..723b17232c 100644 --- a/pandora_agents/unix/Darwin/pandora_agent.conf +++ b/pandora_agents/unix/Darwin/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, GNU/Linux +# Version 7.0NG.714, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2012 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -88,6 +88,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # Server password (Tentacle or FTP). Leave empty for no password (default). #server_pwd mypassword diff --git a/pandora_agents/unix/FreeBSD/pandora_agent.conf b/pandora_agents/unix/FreeBSD/pandora_agent.conf index 29d6e893b7..8a8ecd3451 100644 --- a/pandora_agents/unix/FreeBSD/pandora_agent.conf +++ b/pandora_agents/unix/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, FreeBSD Version +# Version 7.0NG.714, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2016 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -98,6 +98,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # timeout in seconds for file transfer programs execution (30 by default) #transfer_timeout 30 diff --git a/pandora_agents/unix/HP-UX/pandora_agent.conf b/pandora_agents/unix/HP-UX/pandora_agent.conf index 9db22b3b47..f31d7e6cd0 100644 --- a/pandora_agents/unix/HP-UX/pandora_agent.conf +++ b/pandora_agents/unix/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, HP-UX Version +# Version 7.0NG.714, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -60,6 +60,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # Server password (Tentacle or FTP). Leave empty for no password (default). # server_pwd mypassword diff --git a/pandora_agents/unix/Linux/pandora_agent.conf b/pandora_agents/unix/Linux/pandora_agent.conf index fcfa94b429..59ea7ed59d 100644 --- a/pandora_agents/unix/Linux/pandora_agent.conf +++ b/pandora_agents/unix/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, GNU/Linux +# Version 7.0NG.714, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2014 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -104,6 +104,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # timeout in seconds for file transfer programs execution (30 by default) #transfer_timeout 30 diff --git a/pandora_agents/unix/NT4/pandora_agent.conf b/pandora_agents/unix/NT4/pandora_agent.conf index 29e9d9e9b2..ee6b7bb18d 100644 --- a/pandora_agents/unix/NT4/pandora_agent.conf +++ b/pandora_agents/unix/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, GNU/Linux +# Version 7.0NG.714, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/NetBSD/pandora_agent.conf b/pandora_agents/unix/NetBSD/pandora_agent.conf index 4f89baee8b..aa64beba39 100644 --- a/pandora_agents/unix/NetBSD/pandora_agent.conf +++ b/pandora_agents/unix/NetBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, NetBSD Version +# Version 7.0NG.714, NetBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -66,6 +66,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # timeout in seconds for file transfer programs execution (30 by default) #transfer_timeout 30 diff --git a/pandora_agents/unix/SunOS/pandora_agent.conf b/pandora_agents/unix/SunOS/pandora_agent.conf index 94bc194a05..3dada142de 100644 --- a/pandora_agents/unix/SunOS/pandora_agent.conf +++ b/pandora_agents/unix/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.712, Solaris Version +# Version 7.0NG.714, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -60,6 +60,9 @@ server_port 41121 # Transfer mode: tentacle, ftp, ssh or local transfer_mode tentacle +# Transfer mode user: Owner of files copied on local transfer mode (default apache) +#transfer_mode_user apache + # timeout in seconds for file transfer programs execution (30 by default) #transfer_timeout 30 diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 18bc995e59..74a106b2c5 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -40,8 +40,8 @@ my $Sem = undef; # Semaphore used to control the number of threads my $ThreadSem = undef; -use constant AGENT_VERSION => '7.0NG.712'; -use constant AGENT_BUILD => '170908'; +use constant AGENT_VERSION => '7.0NG.714'; +use constant AGENT_BUILD => '171030'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; @@ -128,6 +128,9 @@ my @BrokerPid; my %DefaultConf = ( 'server_ip' => 'localhost', 'server_path' => '/var/spool/pandora/data_in', + 'server_path_md5' => 'md5', #undocumented + 'server_path_conf' => 'conf', #undocumented + 'server_path_zip' => 'collections', #undocumented 'logfile' =>'/var/log/pandora/pandora_agent.log', 'logsize' => DEFAULT_MAX_LOG_SIZE, 'logrotate' => DEFAULT_LOG_ROTATE, @@ -146,6 +149,7 @@ my %DefaultConf = ( 'encoding' => 'UTF-8', 'server_port' => 41121, 'transfer_mode' => 'tentacle', + 'transfer_mode_user' => 'apache', 'transfer_timeout' => 30, 'server_user' => 'pandora', 'server_pwd' => '', @@ -906,13 +910,17 @@ sub fix_directory ($) { ################################################################################ # Sends a file to the server. ################################################################################ -#sub send_file ($;$$$) { sub send_file { - my ($file, $secondary, $rc_primary, $flag_always) = @_; + my ($file, $secondary, $rc_primary, $flag_always, $relative) = @_; + my $output; my $pid = fork(); return 1 unless defined $pid; + # Fix remote dir to some transfer mode + my $remote_dir = $Conf{'server_path'} . "/"; + $remote_dir .= fix_directory($relative) . '/' if defined($relative); + if ($pid == 0) { # execute the transfer program by child process. eval { @@ -935,7 +943,7 @@ sub send_file { quit FEOF1` } elsif ($Conf{'transfer_mode'} eq 'local') { - $output = `cp "$file" "$Conf{'server_path'}/" 2>&1 >$DevNull`; + $output = `cp -p "$file" "$remote_dir" 2>&1 >$DevNull`; } alarm (0); }; @@ -966,7 +974,7 @@ sub send_file { $rc_primary = 1; } swap_servers (); - $rc = send_file ($file, undef, $rc_primary); + $rc = send_file ($file, undef, $rc_primary, undef, $relative); swap_servers (); return $rc; @@ -1024,7 +1032,7 @@ sub send_file { return $rc unless ($Conf{'secondary_mode'} eq 'always' || ($Conf{'secondary_mode'} eq 'on_error' && $rc != 0)); swap_servers (); - $rc = send_file ($file); + $rc = send_file ($file, undef, undef, undef, $relative); swap_servers (); return $rc; } @@ -1075,12 +1083,16 @@ sub swap_servers () { ################################################################################ # Receive a file from the server. ################################################################################ -sub recv_file ($) { - my $file = shift; +sub recv_file { + my ($file, $relative) = @_; my $output; - + my $pid = fork(); - return 1 unless defined $pid; + return 1 unless defined $pid; + + # Fix remote dir to some transfer mode + my $remote_dir = $Conf{'server_path'}; + $remote_dir .= "/" . fix_directory($relative) if defined($relative); if ($pid == 0) { # execute the transfer program by child process. @@ -1104,7 +1116,7 @@ sub recv_file ($) { quit FEOF1` } elsif ($Conf{'transfer_mode'} eq 'local') { - $output = `cp $Conf{'server_path'}/$file $Conf{'temporal'} 2>&1 >$DevNull`; + $output = `cp "$remote_dir/$file" $Conf{'temporal'} 2>&1 >$DevNull`; } alarm (0); }; @@ -1148,14 +1160,19 @@ sub check_remote_config () { } # Get the remote MD5 file - if (recv_file ($RemoteMD5File) != 0) { + if (recv_file ($RemoteMD5File, $Conf{'server_path_md5'}) != 0) { + log_message ('remote config', 'Uploading configuration for the first time.'); open (MD5_FILE, "> $Conf{'temporal'}/$RemoteMD5File") || error ("Could not open file '$ConfDir/$RemoteMD5File' for writing: $!."); print MD5_FILE $conf_md5; close (MD5_FILE); copy ("$ConfDir/$ConfFile", "$Conf{'temporal'}/$RemoteConfFile"); - send_file ("$Conf{'temporal'}/$RemoteConfFile"); - send_file ("$Conf{'temporal'}/$RemoteMD5File"); - log_message ('remote config', 'Uploading configuration for the first time.'); + if ($Conf{'transfer_mode'} eq 'local') { + my (undef, undef, $uid, $gid) = getpwnam($Conf{'transfer_mode_user'}); + chown ($uid, $gid, "$Conf{'temporal'}/$RemoteMD5File"); + chown ($uid, $gid, "$Conf{'temporal'}/$RemoteConfFile"); + } + send_file ("$Conf{'temporal'}/$RemoteConfFile", undef, undef, undef, $Conf{'server_path_conf'}); + send_file ("$Conf{'temporal'}/$RemoteMD5File", undef, undef, undef, $Conf{'server_path_md5'}); unlink ("$Conf{'temporal'}/$RemoteConfFile"); unlink ("$Conf{'temporal'}/$RemoteMD5File"); return; @@ -1169,7 +1186,7 @@ sub check_remote_config () { return if ($remote_conf_md5 eq $conf_md5); # Get the new configuration file - return if (recv_file ($RemoteConfFile) != 0); + return if (recv_file ($RemoteConfFile, $Conf{'server_path_conf'}) != 0); log_message ('remote config', 'Configuration has changed!'); # Save the new configuration @@ -1255,7 +1272,7 @@ sub check_collections () { # Get remote md5 error ("File '$Conf{'temporal'}/$collection_md5_file' already exists as a symlink and could not be removed: $!.") if (-l "$Conf{'temporal'}/$collection_md5_file" && !unlink("$Conf{'temporal'}/$collection_md5_file")); - next unless (recv_file ($collection_md5_file) == 0); + next unless (recv_file ($collection_md5_file, $Conf{'server_path_md5'}) == 0); open (MD5_FILE, "< $Conf{'temporal'}/$collection_md5_file") || error ("Could not open file '$Conf{'temporal'}/$collection_md5_file' for reading: $!."); my $remote_collection_md5 = ; close (MD5_FILE); @@ -1273,7 +1290,7 @@ sub check_collections () { next if ($local_collection_md5 eq $remote_collection_md5); # Download and unzip - next unless (recv_file ($collection_file) == 0); + next unless (recv_file ($collection_file, $Conf{'server_path_zip'}) == 0); rmrf ("$ConfDir/collections/$collection"); `unzip -d "$ConfDir/collections/$collection" "$Conf{'temporal'}/$collection_file" 2>$DevNull`; unlink ("$Conf{'temporal'}/$collection_file"); @@ -1346,7 +1363,7 @@ sub md5 { # Append bit /* bit, not byte */ length of unpadded message as 64-bit # little-endian integer to message. $msg .= unpack ("B32", pack ("V", $bit_len)); - $msg .= unpack ("B32", pack ("V", $bit_len >> 32)); + $msg .= unpack ("B32", pack ("V", ($bit_len >> 16) >> 16)); # Process the message in successive 512-bit chunks. for (my $i = 0; $i < length ($msg); $i += 512) { @@ -1562,6 +1579,9 @@ sub guess_os_version ($) { # AIX } elsif ($os eq 'aix') { $os_version = "$2.$1" if (`uname -rv` =~ /\s*(\d)\s+(\d)\s*/); + # Darwin + } elsif ($os eq 'darwin') { + $os_version = `defaults read loginwindow SystemVersionStampAsString`; # Windows } elsif ($os =~ /win/i) { $os_version = `ver`; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 71c275798f..32e20ed339 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.712 -%define release 170908 +%define version 7.0NG.714 +%define release 171030 Summary: Pandora FMS Linux agent, PERL version Name: %{name} @@ -24,7 +24,7 @@ Requires(preun): chkconfig /bin/rm /usr/sbin/userdel Requires: fileutils textutils unzip Requires: util-linux procps grep Requires: /sbin/ip /bin/awk -Requires: perl perl(Sys::Syslog) perl(IO::Socket::SSL) +Requires: perl perl(Sys::Syslog) # Required by plugins #Requires: sh-utils sed passwd net-tools rpm AutoReq: 0 diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 6ab308fc5c..b77e5efb51 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.712 -%define release 170908 +%define version 7.0NG.714 +%define release 171030 Summary: Pandora FMS Linux agent, PERL version Name: %{name} @@ -67,6 +67,7 @@ then fi %post +mkdir -p /var/log/pandora chown pandora:root /var/log/pandora if [ ! -d /etc/pandora ] ; then mkdir -p /etc/pandora @@ -91,6 +92,9 @@ if [ ! -e /etc/pandora/collections ]; then fi cp -aRf /usr/share/pandora_agent/pandora_agent_logrotate /etc/logrotate.d/pandora_agent +# Enable the service on SystemD +systemctl enable pandora_agent_daemon.service + mkdir -p /var/spool/pandora/data_out chkconfig pandora_agent_daemon on diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index d65123bfdd..6ba18c1b43 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -9,8 +9,8 @@ # Please see http://www.pandorafms.org. This code is licensed under GPL 2.0 license. # ********************************************************************** -PI_VERSION="7.0NG.712" -PI_BUILD="170908" +PI_VERSION="7.0NG.714" +PI_BUILD="171030" OS_NAME=`uname -s` FORCE=0 diff --git a/pandora_agents/unix/plugins/route_parser b/pandora_agents/unix/plugins/route_parser new file mode 100644 index 0000000000..0c5c5c7fae Binary files /dev/null and b/pandora_agents/unix/plugins/route_parser differ diff --git a/pandora_agents/win32/Makefile.am b/pandora_agents/win32/Makefile.am index 6e47cafcc1..d41c722ced 100644 --- a/pandora_agents/win32/Makefile.am +++ b/pandora_agents/win32/Makefile.am @@ -3,7 +3,7 @@ if DEBUG PandoraAgent_SOURCES = misc/pandora_file.cc modules/pandora_data.cc modules/pandora_module_factory.cc modules/pandora_module.cc modules/pandora_module_list.cc modules/pandora_module_plugin.cc modules/pandora_module_inventory.cc modules/pandora_module_freememory.cc modules/pandora_module_exec.cc modules/pandora_module_perfcounter.cc modules/pandora_module_proc.cc modules/pandora_module_tcpcheck.cc modules/pandora_module_freememory_percent.cc modules/pandora_module_freedisk.cc modules/pandora_module_freedisk_percent.cc modules/pandora_module_logevent.cc modules/pandora_module_service.cc modules/pandora_module_cpuusage.cc modules/pandora_module_wmiquery.cc modules/pandora_module_regexp.cc modules/pandora_module_ping.cc modules/pandora_module_snmpget.cc udp_server/udp_server.cc main.cc pandora_strutils.cc pandora.cc windows_service.cc pandora_agent_conf.cc windows/pandora_windows_info.cc windows/pandora_wmi.cc pandora_windows_service.cc misc/md5.c misc/sha256.cc windows/wmi/disphelper.c ssh/libssh2/channel.c ssh/libssh2/mac.c ssh/libssh2/session.c ssh/libssh2/comp.c ssh/libssh2/misc.c ssh/libssh2/sftp.c ssh/libssh2/crypt.c ssh/libssh2/packet.c ssh/libssh2/userauth.c ssh/libssh2/hostkey.c ssh/libssh2/publickey.c ssh/libssh2/kex.c ssh/libssh2/scp.c ssh/pandora_ssh_client.cc ssh/pandora_ssh_test.cc ftp/pandora_ftp_client.cc ftp/pandora_ftp_test.cc debug_new.cpp PandoraAgent_CXXFLAGS=-g -O0 else -PandoraAgent_SOURCES = misc/pandora_file.cc modules/pandora_data.cc modules/pandora_module_factory.cc modules/pandora_module.cc modules/pandora_module_list.cc modules/pandora_module_plugin.cc modules/pandora_module_inventory.cc modules/pandora_module_freememory.cc modules/pandora_module_exec.cc modules/pandora_module_perfcounter.cc modules/pandora_module_proc.cc modules/pandora_module_tcpcheck.cc modules/pandora_module_freememory_percent.cc modules/pandora_module_freedisk.cc modules/pandora_module_freedisk_percent.cc modules/pandora_module_logevent.cc modules/pandora_module_service.cc modules/pandora_module_cpuusage.cc modules/pandora_module_wmiquery.cc modules/pandora_module_regexp.cc modules/pandora_module_ping.cc modules/pandora_module_snmpget.cc udp_server/udp_server.cc main.cc pandora_strutils.cc pandora.cc windows_service.cc pandora_agent_conf.cc windows/pandora_windows_info.cc windows/pandora_wmi.cc pandora_windows_service.cc misc/md5.c misc/sha256.cc windows/wmi/disphelper.c ssh/libssh2/channel.c ssh/libssh2/mac.c ssh/libssh2/session.c ssh/libssh2/comp.c ssh/libssh2/misc.c ssh/libssh2/sftp.c ssh/libssh2/crypt.c ssh/libssh2/packet.c ssh/libssh2/userauth.c ssh/libssh2/hostkey.c ssh/libssh2/publickey.c ssh/libssh2/kex.c ssh/libssh2/scp.c ssh/pandora_ssh_client.cc ssh/pandora_ssh_test.cc ftp/pandora_ftp_client.cc ftp/pandora_ftp_test.cc +PandoraAgent_SOURCES = misc/pandora_file.cc modules/pandora_data.cc modules/pandora_module_factory.cc modules/pandora_module.cc modules/pandora_module_list.cc modules/pandora_module_plugin.cc modules/pandora_module_inventory.cc modules/pandora_module_freememory.cc modules/pandora_module_exec.cc modules/pandora_module_perfcounter.cc modules/pandora_module_proc.cc modules/pandora_module_tcpcheck.cc modules/pandora_module_freememory_percent.cc modules/pandora_module_freedisk.cc modules/pandora_module_freedisk_percent.cc modules/pandora_module_logevent.cc modules/pandora_module_logchannel.cc modules/pandora_module_service.cc modules/pandora_module_cpuusage.cc modules/pandora_module_wmiquery.cc modules/pandora_module_regexp.cc modules/pandora_module_ping.cc modules/pandora_module_snmpget.cc udp_server/udp_server.cc main.cc pandora_strutils.cc pandora.cc windows_service.cc pandora_agent_conf.cc windows/pandora_windows_info.cc windows/pandora_wmi.cc pandora_windows_service.cc misc/md5.c misc/sha256.cc windows/wmi/disphelper.c ssh/libssh2/channel.c ssh/libssh2/mac.c ssh/libssh2/session.c ssh/libssh2/comp.c ssh/libssh2/misc.c ssh/libssh2/sftp.c ssh/libssh2/crypt.c ssh/libssh2/packet.c ssh/libssh2/userauth.c ssh/libssh2/hostkey.c ssh/libssh2/publickey.c ssh/libssh2/kex.c ssh/libssh2/scp.c ssh/pandora_ssh_client.cc ssh/pandora_ssh_test.cc ftp/pandora_ftp_client.cc ftp/pandora_ftp_test.cc PandoraAgent_CXXFLAGS=-O2 endif diff --git a/pandora_agents/win32/bin/pandora_agent.conf b/pandora_agents/win32/bin/pandora_agent.conf index 6c3e9e7eb6..c8c32e84d0 100644 --- a/pandora_agents/win32/bin/pandora_agent.conf +++ b/pandora_agents/win32/bin/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2014 Artica Soluciones Tecnologicas -# Version 7.0NG.712 +# Version 7.0NG.714 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/win32/bin/util/mtr.exe b/pandora_agents/win32/bin/util/mtr.exe new file mode 100644 index 0000000000..3646ca89aa Binary files /dev/null and b/pandora_agents/win32/bin/util/mtr.exe differ diff --git a/pandora_agents/win32/bin/util/route_parser.exe b/pandora_agents/win32/bin/util/route_parser.exe new file mode 100644 index 0000000000..4da75a272a Binary files /dev/null and b/pandora_agents/win32/bin/util/route_parser.exe differ diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index f2eb7a424c..c57d869256 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -3,7 +3,7 @@ AllowLanguageSelection {Yes} AppName -{Pandora FMS Windows Agent v7.0NG.712} +{Pandora FMS Windows Agent v7.0NG.714} ApplicationID {17E3D2CF-CA02-406B-8A80-9D31C17BD08F} @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{170908} +{171030} ViewReadme {Yes} diff --git a/pandora_agents/win32/modules/pandora_module.cc b/pandora_agents/win32/modules/pandora_module.cc index 296f42f2ea..99b0d47f88 100644 --- a/pandora_agents/win32/modules/pandora_module.cc +++ b/pandora_agents/win32/modules/pandora_module.cc @@ -248,7 +248,9 @@ Pandora_Module::parseModuleKindFromString (string kind) { } else if (kind == module_inventory_str) { return MODULE_INVENTORY; } else if (kind == module_logevent_str) { - return MODULE_LOGEVENT; + return MODULE_LOGEVENT; + } else if (kind == module_logchannel_str) { + return MODULE_LOGCHANNEL; } else if (kind == module_wmiquery_str) { return MODULE_WMIQUERY; } else if (kind == module_perfcounter_str) { diff --git a/pandora_agents/win32/modules/pandora_module.h b/pandora_agents/win32/modules/pandora_module.h index b2606d2442..2fbeb52e41 100644 --- a/pandora_agents/win32/modules/pandora_module.h +++ b/pandora_agents/win32/modules/pandora_module.h @@ -86,6 +86,7 @@ namespace Pandora_Modules { MODULE_FREEMEMORY_PERCENT, /**< The module checks the amount of * freememory in the system */ MODULE_LOGEVENT, /**< The module checks for log events */ + MODULE_LOGCHANNEL, /**< The module checks for log events on channel using XML functions*/ MODULE_WMIQUERY, /**< The module runs WQL queries */ MODULE_PERFCOUNTER, /**< The module reads performance counters */ MODULE_TCPCHECK, /**< The module checks whether a tcp port is open */ @@ -126,6 +127,7 @@ namespace Pandora_Modules { const string module_cpuusage_str = "module_cpuusage"; const string module_inventory_str = "module_inventory"; const string module_logevent_str = "module_logevent"; + const string module_logchannel_str = "module_logchannel"; const string module_wmiquery_str = "module_wmiquery"; const string module_perfcounter_str = "module_perfcounter"; const string module_tcpcheck_str = "module_tcpcheck"; diff --git a/pandora_agents/win32/modules/pandora_module_factory.cc b/pandora_agents/win32/modules/pandora_module_factory.cc index db33c1315a..90c82d5457 100644 --- a/pandora_agents/win32/modules/pandora_module_factory.cc +++ b/pandora_agents/win32/modules/pandora_module_factory.cc @@ -31,6 +31,7 @@ #include "pandora_module_cpuusage.h" #include "pandora_module_inventory.h" #include "pandora_module_logevent.h" +#include "pandora_module_logchannel.h" #include "pandora_module_wmiquery.h" #include "pandora_module_perfcounter.h" #include "pandora_module_tcpcheck.h" @@ -69,6 +70,7 @@ using namespace Pandora_Strutils; #define TOKEN_MIN_FF_EVENT ("module_min_ff_event ") #define TOKEN_DESCRIPTION ("module_description ") #define TOKEN_LOGEVENT ("module_logevent") +#define TOKEN_LOGCHANNEL ("module_logchannel") #define TOKEN_SOURCE ("module_source ") #define TOKEN_EVENTTYPE ("module_eventtype ") #define TOKEN_EVENTCODE ("module_eventcode ") @@ -121,6 +123,7 @@ using namespace Pandora_Strutils; #define TOKEN_MACRO ("module_macro") #define TOKEN_NATIVE_ENCODING ("module_native_encoding") #define TOKEN_ALERT_TEMPLATE ("module_alert_template") +#define TOKEN_USER_SESSION ("module_user_session ") string parseLine (string line, string token) { @@ -157,8 +160,9 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { string module_freedisk_percent, module_freememory_percent; string module_dsn, module_freememory; string module_logevent, module_source, module_eventtype, module_eventcode; + string module_logchannel; string module_pattern, module_application, module_async; - string module_watchdog, module_start_command; + string module_watchdog, module_start_command, module_user_session; string module_wmiquery, module_wmicolumn; string module_retries, module_startdelay, module_retrydelay; string module_perfcounter, module_tcpcheck; @@ -195,6 +199,7 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_proc = ""; module_service = ""; module_logevent = ""; + module_logchannel = ""; module_source = ""; module_eventtype = ""; module_eventcode = ""; @@ -253,6 +258,7 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_ff_interval = ""; module_native_encoding = ""; module_alert_template = ""; + module_user_session = ""; macro = ""; stringtok (tokens, definition, "\n"); @@ -342,6 +348,9 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { if (module_logevent == "") { module_logevent = parseLine (line, TOKEN_LOGEVENT); } + if (module_logchannel == "") { + module_logchannel = parseLine (line, TOKEN_LOGCHANNEL); + } if (module_source == "") { module_source = parseLine (line, TOKEN_SOURCE); } @@ -507,6 +516,10 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { if (module_alert_template == "") { module_alert_template = parseLine (line, TOKEN_ALERT_TEMPLATE); module_alert_template.erase (0,1); + } + + if (module_user_session == "") { + module_user_session = parseLine (line, TOKEN_USER_SESSION); } if (macro == "") { @@ -724,6 +737,13 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { } } + if (module_logchannel != "") { + pos_macro = module_logchannel.find(macro_name); + if (pos_macro != string::npos){ + module_logchannel.replace(pos_macro, macro_name.size(), macro_value); + } + } + if (module_source != "") { pos_macro = module_source.find(macro_name); if (pos_macro != string::npos){ @@ -1085,6 +1105,13 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_alert_template.replace(pos_macro, macro_name.size(), macro_value); } } + + if (module_user_session != "") { + pos_macro = module_user_session.find(macro_name); + if (pos_macro != string::npos){ + module_user_session.replace(pos_macro, macro_name.size(), macro_value); + } + } } } } @@ -1121,6 +1148,7 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_proc->setRetries (atoi(module_retries.c_str ())); module_proc->setStartDelay (atoi(module_startdelay.c_str ())); module_proc->setRetryDelay (atoi(module_retrydelay.c_str ())); + module_proc->setUserSession (is_enabled(module_user_session)); } } } else if (module_service != "") { @@ -1142,7 +1170,7 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { try { char buffer[100]; unsigned long memory = Pandora_Wmi::getDiskFreeSpace(module_freedisk_percent); - if (sprintf(buffer, "Free memory %s %dMB", + if (sprintf(buffer, "Free space on drive %s %dMB", module_freedisk_percent.c_str(), memory) > 0) { module->setDescription(buffer); } @@ -1173,6 +1201,13 @@ Pandora_Module_Factory::getModuleFromDefinition (string definition) { module_eventcode, module_pattern, module_application); + } + else if (module_logchannel != "") { + module = new Pandora_Module_Logchannel (module_name, + module_source, + module_eventtype, + module_eventcode, + module_pattern); } else if (module_wmiquery != "") { module = new Pandora_Module_WMIQuery (module_name, module_wmiquery, module_wmicolumn); diff --git a/pandora_agents/win32/modules/pandora_module_list.cc b/pandora_agents/win32/modules/pandora_module_list.cc index 516b2296c8..305ee901d7 100644 --- a/pandora_agents/win32/modules/pandora_module_list.cc +++ b/pandora_agents/win32/modules/pandora_module_list.cc @@ -30,12 +30,13 @@ #include "pandora_module_cpuusage.h" #include "pandora_module_inventory.h" #include "pandora_module_logevent.h" +#include "pandora_module_logchannel.h" #include "pandora_module_wmiquery.h" #include "pandora_module_perfcounter.h" #include "pandora_module_tcpcheck.h" #include "pandora_module_regexp.h" #include "pandora_module_plugin.h" -#include "pandora_module_ping.h" +#include "pandora_module_ping.h" #include "pandora_module_snmpget.h" #include @@ -226,12 +227,13 @@ Pandora_Modules::Pandora_Module_List::parseModuleDefinition (string definition) Pandora_Module_Freememory *module_freememory; Pandora_Module_Freememory_Percent *module_freememory_percent; Pandora_Module_Logevent *module_logevent; + Pandora_Module_Logchannel *module_logchannel; Pandora_Module_WMIQuery *module_wmiquery; Pandora_Module_Perfcounter *module_perfcounter; Pandora_Module_Tcpcheck *module_tcpcheck; Pandora_Module_Regexp *module_regexp; Pandora_Module_Plugin *module_plugin; - Pandora_Module_Ping *module_ping; + Pandora_Module_Ping *module_ping; Pandora_Module_SNMPGet *module_snmpget; module = Pandora_Module_Factory::getModuleFromDefinition (definition); @@ -288,6 +290,10 @@ Pandora_Modules::Pandora_Module_List::parseModuleDefinition (string definition) module_logevent = (Pandora_Module_Logevent *) module; modules->push_back (module_logevent); break; + case MODULE_LOGCHANNEL: + module_logchannel = (Pandora_Module_Logchannel *) module; + modules->push_back (module_logchannel); + break; case MODULE_WMIQUERY: module_wmiquery = (Pandora_Module_WMIQuery *) module; modules->push_back (module_wmiquery); @@ -315,7 +321,7 @@ Pandora_Modules::Pandora_Module_List::parseModuleDefinition (string definition) case MODULE_SNMPGET: module_snmpget = (Pandora_Module_SNMPGet *) module; modules->push_back (module_snmpget); - break; + break; default: break; } diff --git a/pandora_agents/win32/modules/pandora_module_logchannel.cc b/pandora_agents/win32/modules/pandora_module_logchannel.cc new file mode 100755 index 0000000000..2c7c056565 --- /dev/null +++ b/pandora_agents/win32/modules/pandora_module_logchannel.cc @@ -0,0 +1,582 @@ +/* Pandora logchannel module. This module checks for log events that match a given + pattern using XML functions provided by wevtapi. + + Copyright (C) 2017 Artica ST. + Written by Fermin Hernandez. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include +#include +#include +#include + +#include "pandora_module_logchannel.h" +#include "../windows/pandora_wmi.h" +#include "../pandora_windows_service.h" +#include "pandora_module_logchannel.h" +#include "pandora_strutils.h" + +using namespace Pandora; +using namespace Pandora_Modules; +using namespace Pandora_Strutils; + +// Pointers to Wevtapi.dll functions +static HINSTANCE WINEVENT = NULL; +static EvtQueryT EvtQueryF = NULL; +static EvtNextT EvtNextF = NULL; +static EvtSeekT EvtSeekF = NULL; +static EvtCreateRenderContextT EvtCreateRenderContextF = NULL; +static EvtRenderT EvtRenderF = NULL; +static EvtCloseT EvtCloseF = NULL; +static EvtFormatMessageT EvtFormatMessageF = NULL; +static EvtOpenPublisherMetadataT EvtOpenPublisherMetadataF = NULL; +static EvtCreateBookmarkT EvtCreateBookmarkF = NULL; +static EvtUpdateBookmarkT EvtUpdateBookmarkF = NULL; + +/** + * Creates a Pandora_Module_Logchannel object. + * + * @param name Module name. + * @param service_name Service internal name to check. + */ +Pandora_Module_Logchannel::Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern) + : Pandora_Module (name) { + int i; + vector query; + vector::iterator query_it; + string upper_type = type; + + // Convert the type string to uppercase + for (i = 0; i < type.length(); i++) { + upper_type[i] = toupper(type[i]); + } + + // Set the type filter + int type_number = -1; + if (upper_type.compare("ERROR") == 0) { + type_number = EVENTLOG_ERROR_TYPE; + } else if (upper_type.compare("WARNING") == 0) { + type_number = EVENTLOG_WARNING_TYPE; + } else if (upper_type.compare("INFORMATION") == 0) { + type_number = EVENTLOG_INFORMATION_TYPE; + } else if (upper_type.compare("AUDIT SUCCESS") == 0) { + type_number = EVENTLOG_AUDIT_SUCCESS; + } else if (upper_type.compare("AUDIT FAILURE") == 0) { + type_number = EVENTLOG_AUDIT_FAILURE; + } + // Append type to log query + if (type_number != -1) { + wstringstream ss; + ss << L"*[System[Level='" << type_number << L"']]"; + query.push_back(ss.str()); + } + + // Set the id + int id_number = strtoul (id.c_str (), NULL, 0); + if (id_number != 0) { + wstringstream ss; + ss << L"*[System[EventID='" << id_number << L"']]"; + query.push_back(ss.str()); + } + + // Fill the filter + if (query.size() == 0) { + this->filter = L"*"; + } else { + int i = 0; + // Add filters with and + wstring item_query; + while (query.size() > 1) { + item_query = query.back(); + query.pop_back(); + this->filter += item_query + L" and "; + } + // Append the last value without the and + item_query = query.back(); + this->filter += item_query; + } + + this->source = source; + this->pattern = pattern; + if (! pattern.empty ()) { + // Compile the regular expression + if (regcomp (&this->regexp, pattern.c_str (), REG_EXTENDED) != 0) { + pandoraLog ("Invalid regular expression %s", pattern.c_str ()); + } + } + this->bookmark_xml = L""; + this->setKind (module_logchannel_str); + + // Load Wevtapi.dll and some functions + if (WINEVENT == NULL) { + WINEVENT = LoadLibrary("Wevtapi.dll"); + if (WINEVENT == NULL) { + + // Log to the bedug log, since this is not an error + pandoraLog ("Library Wevtapi.dll not available"); + return; + } + + EvtQueryF = (EvtQueryT) GetProcAddress (WINEVENT, "EvtQuery"); + if (EvtQueryF == NULL) { + pandoraLog ("Error loading function EvtQuery from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtNextF = (EvtNextT) GetProcAddress (WINEVENT, "EvtNext"); + if (EvtNextF == NULL) { + pandoraLog ("Error loading function EvtNext from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtSeekF = (EvtSeekT) GetProcAddress (WINEVENT, "EvtSeek"); + if (EvtSeekF == NULL) { + pandoraLog ("Error loading function EvtSeek from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtCreateRenderContextF = (EvtCreateRenderContextT) GetProcAddress (WINEVENT, "EvtCreateRenderContext"); + if (EvtCreateRenderContextF == NULL) { + pandoraLog ("Error loading function EvtCreateRenderContext from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtRenderF = (EvtRenderT) GetProcAddress (WINEVENT, "EvtRender"); + if (EvtRenderF == NULL) { + pandoraLog ("Error loading function EvtRender from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtCloseF = (EvtCloseT) GetProcAddress (WINEVENT, "EvtClose"); + if (EvtCloseF == NULL) { + pandoraLog ("Error loading function EvtClose from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtFormatMessageF = (EvtFormatMessageT) GetProcAddress (WINEVENT, "EvtFormatMessage"); + if (EvtFormatMessageF == NULL) { + pandoraLog ("Error loading function EvtFormatMessage from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtOpenPublisherMetadataF = (EvtOpenPublisherMetadataT) GetProcAddress (WINEVENT, "EvtOpenPublisherMetadata"); + if (EvtOpenPublisherMetadataF == NULL) { + pandoraLog ("Error loading function EvtOpenPublisherMetadata from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtCreateBookmarkF = (EvtCreateBookmarkT) GetProcAddress (WINEVENT, "EvtCreateBookmark"); + if (EvtCreateBookmarkF == NULL) { + pandoraLog ("Error loading function EvtCreateBookmark from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + EvtUpdateBookmarkF = (EvtUpdateBookmarkT) GetProcAddress (WINEVENT, "EvtUpdateBookmark"); + if (EvtUpdateBookmarkF == NULL) { + pandoraLog ("Error loading function EvtUpdateBookmark from Wevtapi.dll"); + FreeLibrary (WINEVENT); + WINEVENT = NULL; + return; + } + } +} + +void +Pandora_Module_Logchannel::run () { + list event_list; + list::iterator event; + SYSTEMTIME system_time; + + // Run + try { + Pandora_Module::run (); + } catch (Interval_Not_Fulfilled e) { + return; + } + + // Initialize log event query + this->initializeLogChannel(); + + // Read events on a list + this->getLogEvents (event_list); + + // Return if no data stored on list + if (event_list.size () < 1) return; + + for (event = event_list.begin (); event != event_list.end(); ++event) { + // Store the data + this->setOutput (event->message, &(event->timestamp)); + } +} + +/** + * Fill the first bookmark of events. + */ +void +Pandora_Module_Logchannel::initializeLogChannel () { + EVT_HANDLE hEvents[1]; + EVT_HANDLE hResults; + EVT_HANDLE hBookmark; + DWORD dwReturned = 0; + + // Check whether the first bookmark is set + if (!this->bookmark_xml.empty()) return; + + // Open the event log with a query + hResults = EvtQueryF ( + NULL, + strAnsiToUnicode (this->source.c_str()).c_str(), + this->filter.c_str(), + EvtOpenChannelPath | EvtQueryForwardDirection + ); + if (hResults == NULL) { + pandoraDebug ("Could not open event log channel. Error: '%d'", GetLastError()); + return; + } + + // Put the events on the last event + if (!EvtSeekF(hResults, 0, NULL, 0, EvtSeekRelativeToLast)) { + pandoraDebug("Cannot positionate the event at first. 'Error %d'.", GetLastError()); + EvtCloseF(hResults); + return; + } + // Read next event to positionate the bookmark + if (!EvtNextF(hResults, 1, hEvents, INFINITE, 0, &dwReturned)) { + if (GetLastError() != ERROR_NO_MORE_ITEMS) { + pandoraDebug ("EvtNext (initializeLogChannel) error: %d", GetLastError()); + EvtCloseF(hResults); + return; + } + } + // If no events read, do not use bookmark to read all events + if (dwReturned == 0) { + pandoraDebug("No events found positionating bookmark."); + EvtCloseF(hResults); + return; + } + // Create the bookmar + pandoraDebug("Creating bookmark to channel %s", this->source.c_str()); + hBookmark = EvtCreateBookmarkF(NULL); + if (hBookmark == NULL) { + pandoraDebug("EvtCreateBookmark (initializeLogChannel) failed %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hEvents[0]); + return; + } + if (!EvtUpdateBookmarkF(hBookmark, hEvents[0])) { + pandoraDebug("EvtUpdateBookmarkF (initializeLogChannel) failed %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hEvents[0]); + EvtCloseF(hBookmark); + return; + } + // Save the bookmark like an XML. + this->updateBookmarkXML(hBookmark); + + // Clean tasks + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); +} + +/** + * Update the bookmark XML. Returns false if fails + */ +bool +Pandora_Module_Logchannel::updateBookmarkXML (EVT_HANDLE hBookmark) { + LPWSTR pBookmarkXml = NULL; + DWORD dwBufferSize = 0; + DWORD dwBufferUsed = 0; + DWORD dwPropertyCount = 0; + DWORD status = 0; + + if (!EvtRenderF(NULL, hBookmark, EvtRenderBookmark, dwBufferSize, pBookmarkXml, &dwBufferUsed, &dwPropertyCount)){ + if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError())){ + dwBufferSize = dwBufferUsed; + pBookmarkXml = (LPWSTR)malloc(dwBufferSize); + if (pBookmarkXml){ + EvtRenderF(NULL, hBookmark, EvtRenderBookmark, dwBufferSize, pBookmarkXml, &dwBufferUsed, &dwPropertyCount); + } + else{ + pandoraDebug("Error loading the bookmark. Cannot load enough memory"); + this->cleanBookmark(); + free(pBookmarkXml); + return false; + } + } + if (ERROR_SUCCESS != (status = GetLastError())){ + pandoraDebug("EvtRender (updateBookmarkXML) failed with %d\n", GetLastError()); + this->cleanBookmark(); + free(pBookmarkXml); + return false; + } + } + this->bookmark_xml = pBookmarkXml; + free(pBookmarkXml); + return true; +} + +/** + * Clean the bookmark XML. + */ +void +Pandora_Module_Logchannel::cleanBookmark () { + this->bookmark_xml = L""; +} + +/** + * Reads available events from the event log. + */ +void +Pandora_Module_Logchannel::getLogEvents (list &event_list) { + EVT_HANDLE hResults = NULL; + EVT_HANDLE hBookmark = NULL; + EVT_HANDLE hEvents[1]; + EVT_HANDLE hContext = NULL; + PEVT_VARIANT pRenderedValues = NULL; + EVT_HANDLE hProviderMetadata = NULL; + LPWSTR pwsMessage = NULL; + LPWSTR ppValues[] = {L"Event/System/Provider/@Name", L"Event/System/TimeCreated/@SystemTime"}; + DWORD count = sizeof(ppValues)/sizeof(LPWSTR); + DWORD dwReturned = 0; + DWORD dwBufferSize = 0; + DWORD dwBufferUsed = 0; + DWORD dwPropertyCount = 0; + DWORD status = ERROR_SUCCESS; + SYSTEMTIME eventTime; + FILETIME lft, ft; + bool update_bookmark = false; + + // An empty bookmark XML means that log cannot be open + if (this->bookmark_xml.empty()) return; + + // Open the event log with a query + hResults = EvtQueryF ( + NULL, + strAnsiToUnicode (this->source.c_str()).c_str(), + this->filter.c_str(), + EvtOpenChannelPath | EvtQueryForwardDirection + ); + if (hResults == NULL) { + pandoraDebug ("Could not open event log channel '%s'. Error: '%d'", this->source.c_str(), GetLastError()); + EvtCloseF(hResults); + this->cleanBookmark(); + return; + } + + // Seek on the bookmark + hBookmark = EvtCreateBookmarkF(this->bookmark_xml.c_str()); + if (hBookmark == NULL) { + pandoraDebug("Cannot read the string bookmark. Error: %d.", GetLastError()); + EvtCloseF(hResults); + this->cleanBookmark(); + return; + } + if (!EvtSeekF(hResults, 1, hBookmark, 0, EvtSeekRelativeToBookmark)) { + pandoraDebug("Cannot positionate the event at bookmark. Error %d.", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + this->cleanBookmark(); + return; + } + + // Read events one by one + hEvents[0] = NULL; + while (EvtNextF(hResults, 1, hEvents, INFINITE, 0, &dwReturned)) { + hContext = EvtCreateRenderContextF(count, (LPCWSTR*)ppValues, EvtRenderContextValues); + if (NULL == hContext) { + pandoraDebug ("EvtCreateRenderContext error: %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + this->cleanBookmark(); + return; + } + + // Reinitialize the buffers + dwBufferSize = 0; + dwBufferUsed = 0; + if (! EvtRenderF(hContext, hEvents[0], EvtRenderEventValues, dwBufferSize, pRenderedValues, &dwBufferUsed, &dwPropertyCount)) { + if ((status = GetLastError()) == ERROR_INSUFFICIENT_BUFFER) { + dwBufferSize = dwBufferUsed; + pRenderedValues = (PEVT_VARIANT)malloc(dwBufferSize); + if (pRenderedValues) { + EvtRenderF(hContext, hEvents[0], EvtRenderEventValues, dwBufferSize, pRenderedValues, &dwBufferUsed, &dwPropertyCount); + } + else { + pandoraDebug ("EvtRender error: %d", status); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + EvtCloseF(hContext); + this->cleanBookmark(); + return; + } + } + + if ((status = GetLastError()) != ERROR_SUCCESS) { + pandoraDebug ("EvtRender error getting buffer size: %d", status); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + EvtCloseF(hContext); + this->cleanBookmark(); + return; + } + } + + // Get the SYSTEMTIME of log + ULONGLONG ullTimeStamp = pRenderedValues[1].FileTimeVal; + ft.dwHighDateTime = (DWORD)((ullTimeStamp >> 32) & 0xFFFFFFFF); + ft.dwLowDateTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF); + // Time format conversions + if (!FileTimeToLocalFileTime(&ft, &lft)){ + pandoraDebug("UTC FILETIME to LOCAL FILETIME error: %d.", GetLastError()); + } else if (!FileTimeToSystemTime(&lft, &eventTime)){ + pandoraDebug("FILETIME to SYSTEMTIME error: %d.", GetLastError()); + } + + // Get the handle to the provider's metadata that contains the message strings + hProviderMetadata = EvtOpenPublisherMetadataF(NULL, pRenderedValues[0].StringVal, NULL, 0, 0); + if (hProviderMetadata == NULL) { + pandoraDebug ("EvtOpenPublisherMetadata error: %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + EvtCloseF(hContext); + free(pRenderedValues); + this->cleanBookmark(); + return; + } + + // Read the event message + pwsMessage = GetMessageString(hProviderMetadata, hEvents[0], EvtFormatMessageEvent); + if (pwsMessage == NULL) { + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + EvtCloseF(hContext); + free(pRenderedValues); + EvtCloseF(hProviderMetadata); + this->cleanBookmark(); + return; + } + + // Check the regex and save the message if pass the regex + if (this->pattern.empty () || regexec (&this->regexp, strUnicodeToAnsi(pwsMessage).c_str (), 0, NULL, 0) == 0){ + // Save the event message + LogChannelList event_item; + event_item.message = strUnicodeToAnsi(pwsMessage); + event_item.timestamp= eventTime; + event_list.push_back (event_item); + } + + // Clean up some used vars + EvtCloseF(hContext); + free(pRenderedValues); + EvtCloseF(hProviderMetadata); + free(pwsMessage); + + // Update the bookmark + if (!EvtUpdateBookmarkF(hBookmark, hEvents[0])) { + pandoraDebug("EvtUpdateBookmarkF (getLogEvents) failed %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + EvtCloseF(hEvents[0]); + this->cleanBookmark(); + return; + } + + // Cleanup current event and read the next log + EvtCloseF(hEvents[0]); + hEvents[0] = NULL; + + // Information token to update bookmark + update_bookmark = true; + } + status = GetLastError(); + if (status != ERROR_NO_MORE_ITEMS) { + pandoraDebug ("EvtNext getLogEvents error: %d", GetLastError()); + EvtCloseF(hResults); + EvtCloseF(hBookmark); + this->cleanBookmark(); + return; + } + + // Update bookmark if there is new events + if (update_bookmark) this->updateBookmarkXML(hBookmark); + + // Clean handlers + EvtCloseF(hResults); + EvtCloseF(hBookmark); +} + +// Gets the specified message string from the event. If the event does not +// contain the specified message, the function returns NULL. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/dd996923(v=vs.85).aspx +LPWSTR +Pandora_Module_Logchannel::GetMessageString(EVT_HANDLE hMetadata, EVT_HANDLE hEvent, EVT_FORMAT_MESSAGE_FLAGS FormatId) { + LPWSTR pBuffer = NULL; + DWORD dwBufferSize = 0; + DWORD dwBufferUsed = 0; + DWORD status = 0; + + if (!EvtFormatMessageF(hMetadata, hEvent, 0, 0, NULL, FormatId, dwBufferSize, pBuffer, &dwBufferUsed)) { + status = GetLastError(); + if (ERROR_INSUFFICIENT_BUFFER == status) { + // An event can contain one or more keywords. The function returns keywords + // as a list of keyword strings. To process the list, you need to know the + // size of the buffer, so you know when you have read the last string, or you + // can terminate the list of strings with a second null terminator character + // as this example does. + if ((EvtFormatMessageKeyword == FormatId)) { + pBuffer[dwBufferSize-1] = L'\0'; + } + else { + dwBufferSize = dwBufferUsed; + } + pBuffer = (LPWSTR)malloc(dwBufferSize * sizeof(WCHAR)); + + if (pBuffer) { + EvtFormatMessageF(hMetadata, hEvent, 0, 0, NULL, FormatId, dwBufferSize, pBuffer, &dwBufferUsed); + + // Add the second null terminator character. + if ((EvtFormatMessageKeyword == FormatId)) { + pBuffer[dwBufferUsed-1] = L'\0'; + } + } + else { + return NULL; + } + } + else { + pandoraDebug ("EvtFormatMessage error: %d", status); + return NULL; + } + } + + return pBuffer; +} \ No newline at end of file diff --git a/pandora_agents/win32/modules/pandora_module_logchannel.h b/pandora_agents/win32/modules/pandora_module_logchannel.h new file mode 100755 index 0000000000..14617037c6 --- /dev/null +++ b/pandora_agents/win32/modules/pandora_module_logchannel.h @@ -0,0 +1,76 @@ +/* Pandora logchannel module. This module checks for log events that match a given + pattern using XML functions provided by wevtapi. + + Copyright (C) 2017 Artica ST. + Written by Fermin Hernandez. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#ifndef __PANDORA_MODULE_LOGCHANNEL_H__ +#define __PANDORA_MODULE_LOGCHANNEL_H__ + +#include "pandora_module.h" +#include "boost/regex.h" +#include "../windows/winevt.h" + +// Log event read buffer size +#define BUFFER_SIZE 1024 + +// Types for pointers to Wevtapi.dll functions +typedef EVT_HANDLE WINAPI (*EvtQueryT) (EVT_HANDLE Session, LPCWSTR Path, LPCWSTR Query, DWORD Flags); +typedef WINBOOL WINAPI (*EvtNextT) (EVT_HANDLE ResultSet, DWORD EventArraySize, EVT_HANDLE* EventArray, DWORD Timeout, DWORD Flags, PDWORD Returned); +typedef WINBOOL WINAPI (*EvtSeekT) (EVT_HANDLE ResultSet, LONGLONG Position, EVT_HANDLE Bookmark, DWORD Timeout, DWORD Flags); +typedef EVT_HANDLE WINAPI (*EvtCreateRenderContextT) (DWORD ValuePathsCount, LPCWSTR *ValuePaths, DWORD Flags); +typedef WINBOOL WINAPI (*EvtRenderT) (EVT_HANDLE Context, EVT_HANDLE Fragment, DWORD Flags, DWORD BufferSize, PVOID Buffer, PDWORD BufferUsed, PDWORD PropertyCount); +typedef WINBOOL WINAPI (*EvtCloseT) (EVT_HANDLE Object); +typedef WINBOOL WINAPI (*EvtFormatMessageT) (EVT_HANDLE PublisherMetadata, EVT_HANDLE Event, DWORD MessageId, DWORD ValueCount, PEVT_VARIANT Values, DWORD Flags, DWORD BufferSize, LPWSTR Buffer, PDWORD BufferUsed); +typedef EVT_HANDLE WINAPI (*EvtOpenPublisherMetadataT) (EVT_HANDLE Session, LPCWSTR PublisherIdentity, LPCWSTR LogFilePath, LCID Locale, DWORD Flags); +typedef EVT_HANDLE WINAPI (*EvtCreateBookmarkT) (LPCWSTR BookmarkXml); +typedef WINBOOL WINAPI (*EvtUpdateBookmarkT) (EVT_HANDLE Bookmark, EVT_HANDLE Event); + +namespace Pandora_Modules { + + /** + * This module checks for log events that match a given + * pattern. Events can be filtered by source and type. + */ + + class Pandora_Module_Logchannel : public Pandora_Module { + struct LogChannelList { + string message; + SYSTEMTIME timestamp; + }; + private: + regex_t regexp; + string source; + string pattern; + wstring filter; + wstring bookmark_xml; + HANDLE messages_dll; + + void initializeLogChannel (); + bool updateBookmarkXML (EVT_HANDLE hBookmark); + void getLogEvents (list &event_list); + void cleanBookmark (); + LPWSTR GetMessageString(EVT_HANDLE hMetadata, EVT_HANDLE hEvent, EVT_FORMAT_MESSAGE_FLAGS FormatId); + + public: + Pandora_Module_Logchannel (string name, string source, string type, string id, string pattern); + void run (); + }; +} + +#endif diff --git a/pandora_agents/win32/modules/pandora_module_logevent.cc b/pandora_agents/win32/modules/pandora_module_logevent.cc index 5a2926b202..2230504ebd 100755 --- a/pandora_agents/win32/modules/pandora_module_logevent.cc +++ b/pandora_agents/win32/modules/pandora_module_logevent.cc @@ -169,7 +169,7 @@ Pandora_Module_Logevent::run () { this->openLogEvent(); // Read events - this->getLogEvents (event_list, 0); + this->getLogEvents (event_list); // No data if (event_list.size () < 1) { @@ -215,7 +215,7 @@ Pandora_Module_Logevent::openLogEvent () { if (this->first_run == 1) { this->first_run = 0; if (Pandora::getPandoraDebug() == false) { - this->getLogEvents (event_list, 1); + this->seekAtTop (event_list); } } @@ -237,11 +237,86 @@ Pandora_Module_Logevent::closeLogEvent () { this->log_event = NULL; } +/** + * Puts the event handler on top of event list + * avoiding the use of EVENTLOG_SEEK_READ because it is buggy + */ +int +Pandora_Module_Logevent::seekAtTop (list &event_list) { + BYTE *buffer = NULL, *new_buffer = NULL; + DWORD to_read, read, needed; + EVENTLOGRECORD *pevlr = NULL; + bool rc = false; + DWORD last_error; + DWORD direction = EVENTLOG_BACKWARDS_READ; + + if (this->log_event == NULL) { + return -1; + } + + // Initialize the event record buffer + to_read = BUFFER_SIZE; + buffer = (BYTE *) malloc (sizeof (BYTE) * BUFFER_SIZE); + if (buffer == NULL) { + return -1; + } + pevlr = (EVENTLOGRECORD *) buffer; + + // Read events + while (1) { + + rc = ReadEventLog (this->log_event, direction | EVENTLOG_SEQUENTIAL_READ, 0, pevlr, to_read, &read, &needed); + direction = EVENTLOG_FORWARDS_READ; + if (!rc) { + + // Get error details + last_error = GetLastError(); + + // Not enough space in the buffer + if(last_error == ERROR_INSUFFICIENT_BUFFER) { + + // Initialize the new event record buffer + to_read = needed; + new_buffer = (BYTE *) realloc (buffer, sizeof (BYTE) * needed); + if (new_buffer == NULL) { + free ((void *) buffer); + return -1; + } + + buffer = new_buffer; + pevlr = (EVENTLOGRECORD *) buffer; + + // Try to read the event again + continue; + // File corrupted or cleared + } else if (last_error == ERROR_EVENTLOG_FILE_CORRUPT || last_error == ERROR_EVENTLOG_FILE_CHANGED) { + closeLogEvent (); + free ((void *) buffer); + return -1; + } + // Unknown error + else { + free ((void *) buffer); + return -1; + } + } + + // No more events + if (read == 0) { + free ((void *) buffer); + return 0; + } + } + + free ((void *) buffer); + return 0; +} + /** * Reads available events from the event log. */ int -Pandora_Module_Logevent::getLogEvents (list &event_list, unsigned char discard) { +Pandora_Module_Logevent::getLogEvents (list &event_list) { char message[BUFFER_SIZE], timestamp[TIMESTAMP_LEN + 1]; struct tm *time_info = NULL; time_t epoch; @@ -313,11 +388,6 @@ Pandora_Module_Logevent::getLogEvents (list &event_list, unsigned char d free ((void *) buffer); return 0; } - - // Discard existing events - if (discard == 1) { - continue; - } // Process read events while (read > 0) { diff --git a/pandora_agents/win32/modules/pandora_module_logevent.h b/pandora_agents/win32/modules/pandora_module_logevent.h index 8f33671775..3615a0ee5a 100755 --- a/pandora_agents/win32/modules/pandora_module_logevent.h +++ b/pandora_agents/win32/modules/pandora_module_logevent.h @@ -69,7 +69,8 @@ namespace Pandora_Modules { HANDLE openLogEvent (); void closeLogEvent (); - int getLogEvents (list &event_list, unsigned char discard); + int getLogEvents (list &event_list); + int seekAtTop (list &event_list); void timestampToSystemtime (string timestamp, SYSTEMTIME *system_time); void getEventDescription (PEVENTLOGRECORD pevlr, char *message, DWORD flags); string getEventDescriptionXPATH (PEVENTLOGRECORD pevlr); diff --git a/pandora_agents/win32/modules/pandora_module_proc.cc b/pandora_agents/win32/modules/pandora_module_proc.cc index e8eed1f97d..1c06e1001d 100644 --- a/pandora_agents/win32/modules/pandora_module_proc.cc +++ b/pandora_agents/win32/modules/pandora_module_proc.cc @@ -48,6 +48,7 @@ Pandora_Module_Proc::Pandora_Module_Proc (string name, string process_name) this->setKind (module_proc_str); this->watchdog = false; + this->user_session = false; this->start_command = ""; this->retries = 3; this->start_delay = 5000; @@ -95,6 +96,11 @@ Pandora_Module_Proc::getRetryDelay () const { return this->retry_delay; } +bool +Pandora_Module_Proc::getUserSession () const { + return this->user_session; +} + void Pandora_Module_Proc::setWatchdog (bool watchdog) { this->watchdog = watchdog; @@ -131,6 +137,11 @@ Pandora_Module_Proc::setRetryDelay (int mseconds) { this->retry_delay = mseconds; } +void +Pandora_Module_Proc::setUserSession (bool usession) { + this->user_session = usession; +} + void async_run (Pandora_Module_Proc *module) { HANDLE *processes = NULL; @@ -156,7 +167,7 @@ async_run (Pandora_Module_Proc *module) { } Sleep (module->getRetryDelay ()); - Pandora_Wmi::runProgram (module->getStartCommand ()); + Pandora_Wmi::runProgram (module->getStartCommand (), NULL, module->getUserSession()); Sleep (module->getStartDelay ()); counter++; continue; diff --git a/pandora_agents/win32/modules/pandora_module_proc.h b/pandora_agents/win32/modules/pandora_module_proc.h index edab85cb88..0286efcf5c 100644 --- a/pandora_agents/win32/modules/pandora_module_proc.h +++ b/pandora_agents/win32/modules/pandora_module_proc.h @@ -32,6 +32,7 @@ namespace Pandora_Modules { string process_name; HANDLE thread; bool watchdog; + bool user_session; string start_command; int retries; int start_delay; @@ -46,12 +47,14 @@ namespace Pandora_Modules { int getRetries () const; int getStartDelay () const; int getRetryDelay () const; + bool getUserSession () const; void setWatchdog (bool watchdog); void setStartCommand (string command); void setRetries (int retries); void setStartDelay (int mseconds); void setRetryDelay (int mseconds); + void setUserSession (bool usession); void run (); }; diff --git a/pandora_agents/win32/modules/pandora_module_service.cc b/pandora_agents/win32/modules/pandora_module_service.cc index bf82120aa8..11abf8b2fa 100644 --- a/pandora_agents/win32/modules/pandora_module_service.cc +++ b/pandora_agents/win32/modules/pandora_module_service.cc @@ -20,12 +20,12 @@ */ #include "pandora_module_service.h" -#include "pandora_module_list.h" #include "../windows/pandora_wmi.h" #include "../pandora_strutils.h" #include "../pandora_windows_service.h" #include #include +#include using namespace Pandora; using namespace Pandora_Modules; @@ -83,8 +83,6 @@ async_run (Pandora_Module_Service *module) { HANDLE event_log; HANDLE event; DWORD result; - int res; - string str_res; BYTE buffer[BUFFER_SIZE]; EVENTLOGRECORD *record; DWORD read; @@ -93,10 +91,20 @@ async_run (Pandora_Module_Service *module) { bool service_event; string prev_res; Pandora_Module_List *modules; + bool polling; prev_res = module->getLatestOutput (); modules = new Pandora_Module_List (); modules->addModule (module); + + struct stat st; + // Use polling if there is not local politics and events + // do not emit logs. It is a way to check if there is a + // Home Edition Windows distribution + polling = (stat("C:\\Windows\\System32\\gpedit.msc", &st) != 0); + if (polling) { + pandoraLog("Async polling service %s for this Windows edition", module->getServiceName().c_str()); + } while (1) { event_log = OpenEventLog (NULL, "Service Control Manager"); @@ -113,6 +121,11 @@ async_run (Pandora_Module_Service *module) { if (result != WAIT_OBJECT_0) { CloseHandle (event); CloseEventLog (event_log); + // If time out and polling, + // check the service status actively + if (result == WAIT_TIMEOUT && polling) { + module->execute_async_service(prev_res, module, modules); + } continue; } @@ -138,17 +151,7 @@ async_run (Pandora_Module_Service *module) { /* A start/stop action was thrown */ if (service_event) { - res = Pandora_Wmi::isServiceRunning (module->getServiceName ()); - str_res = inttostr (res); - if (str_res != prev_res) { - module->setOutput (str_res); - prev_res = str_res; - Pandora_Windows_Service::getInstance ()->sendXml (modules); - } - - if (res == 0 && module->isWatchdog ()) { - Pandora_Wmi::startService (module->getServiceName ()); - } + module->execute_async_service(prev_res, module, modules); } CloseHandle (event); CloseEventLog (event_log); @@ -156,6 +159,31 @@ async_run (Pandora_Module_Service *module) { delete modules; } +/* + * Execute the service async task + */ + +void +Pandora_Module_Service::execute_async_service( + string &prev_res, Pandora_Module_Service *module, Pandora_Module_List *modules +) { + string str_res; + int res; + + res = Pandora_Wmi::isServiceRunning (module->getServiceName ()); + str_res = inttostr (res); + if (str_res != prev_res) { + module->setOutput (str_res); + prev_res = str_res; + Pandora_Windows_Service::getInstance ()->sendXml (modules); + } + + if (res == 0 && module->isWatchdog ()) { + pandoraLog("Starting service"); + Pandora_Wmi::startService (module->getServiceName ()); + } +} + void Pandora_Module_Service::run () { int res; diff --git a/pandora_agents/win32/modules/pandora_module_service.h b/pandora_agents/win32/modules/pandora_module_service.h index bdec6152ed..f0b8a9d79f 100644 --- a/pandora_agents/win32/modules/pandora_module_service.h +++ b/pandora_agents/win32/modules/pandora_module_service.h @@ -23,6 +23,7 @@ #define __PANDORA_MODULE_SERVICE_H__ #include "pandora_module.h" +#include "pandora_module_list.h" namespace Pandora_Modules { /** @@ -41,6 +42,7 @@ namespace Pandora_Modules { void run (); string getServiceName () const; bool isWatchdog () const; + void execute_async_service (string &prev_res, Pandora_Module_Service *module, Pandora_Module_List *modules); void setWatchdog (bool watchdog); }; diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 8adf0ead32..8e67c3f05d 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.712(Build 170908)") +#define PANDORA_VERSION ("7.0NG.714(Build 171030)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/versioninfo.rc b/pandora_agents/win32/versioninfo.rc index fc578b0d73..1bf56988f9 100644 --- a/pandora_agents/win32/versioninfo.rc +++ b/pandora_agents/win32/versioninfo.rc @@ -11,7 +11,7 @@ BEGIN VALUE "LegalCopyright", "Artica ST" VALUE "OriginalFilename", "PandoraAgent.exe" VALUE "ProductName", "Pandora FMS Windows Agent" - VALUE "ProductVersion", "(7.0NG.712(Build 170908))" + VALUE "ProductVersion", "(7.0NG.714(Build 171030))" VALUE "FileVersion", "1.0.0.0" END END diff --git a/pandora_agents/win32/windows/pandora_wmi.cc b/pandora_agents/win32/windows/pandora_wmi.cc index e4763cc433..fb572bddcb 100644 --- a/pandora_agents/win32/windows/pandora_wmi.cc +++ b/pandora_agents/win32/windows/pandora_wmi.cc @@ -369,16 +369,16 @@ Pandora_Wmi::getOSName () { dhGetValue (L"%s", &name, quickfix, L".Caption"); - if (name != NULL) { - // Remove the (R) character. - for (int i = 0; i < strlen(name); i++) { - if ((unsigned char)name[i] == 0xAE) { - name[i] = ' '; - } - } - ret = name; - dhFreeString (name); - } + if (name != NULL) { + // Remove the (R) character. + for (int i = 0; i < strlen(name); i++) { + if ((unsigned char)name[i] == 0xAE) { + name[i] = ' '; + } + } + ret = name; + dhFreeString (name); + } } NEXT_THROW (quickfix); } catch (string errstr) { @@ -411,12 +411,12 @@ Pandora_Wmi::getOSVersion () { L".CSDVersion"); if (version != NULL) { - // Remove the (R) character. - for (int i = 0; i < strlen(version); i++) { - if ((unsigned char)version[i] == 0xAE) { - version[i] = ' '; - } - } + // Remove the (R) character. + for (int i = 0; i < strlen(version); i++) { + if ((unsigned char)version[i] == 0xAE) { + version[i] = ' '; + } + } ret = version; dhFreeString (version); } @@ -501,7 +501,7 @@ Pandora_Wmi::getSystemName () { * @param flags Process creation flags */ bool -Pandora_Wmi::runProgram (string command, DWORD flags) { +Pandora_Wmi::runProgram (string command, DWORD flags, BOOL user_session) { PROCESS_INFORMATION process_info; STARTUPINFO startup_info; bool success; @@ -514,11 +514,75 @@ Pandora_Wmi::runProgram (string command, DWORD flags) { startup_info.cb = sizeof (startup_info); ZeroMemory (&process_info, sizeof (process_info)); - pandoraDebug ("Start process \"%s\".", command.c_str ()); - cmd = strdup (command.c_str ()); - success = CreateProcess (NULL, cmd, NULL, NULL, FALSE, flags, - NULL, NULL, &startup_info, &process_info); - pandoraFree (cmd); + if (user_session) { + DWORD sessionId = WTSGetActiveConsoleSessionId(); + startup_info.cb = sizeof(STARTUPINFO); + startup_info.hStdError = 0; + startup_info.hStdInput = 0; + startup_info.hStdOutput = 0; + if ( + startup_info.hStdError != 0 + || startup_info.hStdInput != 0 + || startup_info.hStdOutput != 0 + ) { + startup_info.dwFlags |= STARTF_USESTDHANDLES; + } + + HANDLE procHandle = GetCurrentProcess(); + HANDLE token, userToken; + + // Tray to open the process + if (OpenProcessToken(procHandle, TOKEN_DUPLICATE, &token) == 0) { + pandoraDebug ("Open Process Token fails with error %d.", GetLastError()); + return false; + } + + // Duplicate token + if (DuplicateTokenEx(token, + MAXIMUM_ALLOWED, + 0, + SecurityImpersonation, + TokenPrimary, + &userToken) == 0) { + pandoraDebug ("Duplicate token fails with error %d.", GetLastError()); + return false; + } + + // Set Token Information + if (SetTokenInformation(userToken, + (TOKEN_INFORMATION_CLASS)TokenSessionId, + &sessionId, + sizeof(sessionId)) == 0) { + // Error 1314 will be thrown if agent is not running as service. + if (GetLastError() != 1314) { + pandoraDebug ("Set token information fails with error %d.", GetLastError()); + return false; + } + } + + LPSTR command_exec = (LPSTR)command.c_str(); + + // Create Process As User + // Changed inherit and command + success = CreateProcessAsUser( + userToken, + 0, + command_exec, + 0, + 0, + FALSE, + flags, + 0, + NULL, + &startup_info, + &process_info); + } else { + pandoraDebug ("Start process \"%s\".", command.c_str ()); + cmd = strdup (command.c_str ()); + success = CreateProcess (NULL, cmd, NULL, NULL, FALSE, flags, + NULL, NULL, &startup_info, &process_info); + pandoraFree (cmd); + } if (success) { pandoraDebug ("The process \"%s\" was started.", command.c_str ()); @@ -949,7 +1013,7 @@ getIPs(VARIANT *ip_array){ if (V_VT(&pvArray[i]) == VT_BSTR) { if (i > 0) { ret += " , "; - } + } LPSTR szStringA; ret += Pandora_Strutils::strUnicodeToAnsi( V_BSTR(&pvArray[i])); } diff --git a/pandora_agents/win32/windows/pandora_wmi.h b/pandora_agents/win32/windows/pandora_wmi.h index 601499f4a1..de4f3db81b 100644 --- a/pandora_agents/win32/windows/pandora_wmi.h +++ b/pandora_agents/win32/windows/pandora_wmi.h @@ -53,7 +53,7 @@ namespace Pandora_Wmi { string getOSBuild (); string getSystemName (); string getSystemAddress (); - bool runProgram (string command, DWORD flags = 0); + bool runProgram (string command, DWORD flags = 0, BOOL user_session = false); bool startService (string service_name); bool stopService (string service_name); void runWMIQuery (string wmi_query, diff --git a/pandora_console/DEBIAN/control b/pandora_console/DEBIAN/control index b183226957..350d367ec4 100644 --- a/pandora_console/DEBIAN/control +++ b/pandora_console/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-console -Version: 7.0NG.712-170908 +Version: 7.0NG.714-171030 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 d89326f528..c3ff60b879 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.712-170908" +pandora_version="7.0NG.714-171030" package_pear=0 package_pandora=1 diff --git a/pandora_console/extensions/agents_modules.php b/pandora_console/extensions/agents_modules.php index cb6fe8cd42..a69343d6dd 100644 --- a/pandora_console/extensions/agents_modules.php +++ b/pandora_console/extensions/agents_modules.php @@ -66,11 +66,14 @@ function mainAgentsModules() { $modulegroup = get_parameter('modulegroup', 0); $refr = get_parameter('refresh', 0); // By default 30 seconds + $recursion = get_parameter('recursion', 0); $group_id = (int)get_parameter('group_id', 0); $offset = (int)get_parameter('offset', 0); $hor_offset = (int)get_parameter('hor_offset', 0); $block = $config['block_size']; + if(get_parameter('modulegroup') != null){ $agents_id = (array)get_parameter('id_agents2', -1); + } $selection_a_m = (int)get_parameter('selection_agent_module'); $modules_selected = (array)get_parameter('module', 0); $update_item = (string)get_parameter('edit_item',''); @@ -139,6 +142,8 @@ function mainAgentsModules() { $filter_groups_label = ''.__('Group').''; $filter_groups = html_print_select_groups(false, "AR", true, 'group_id', $group_id, '', '', '', true, false, true, '', false , 'width: auto;'); + $filter_recursion_label = ''.__('Recursion').''; + $filter_recursion = html_print_checkbox('recursion', 1, 0, true); //groups module $filter_module_groups_label = ''.__('Module group').''; $filter_module_groups = html_print_select_from_sql ("SELECT * FROM tmodule_group ORDER BY name", @@ -245,12 +250,12 @@ function mainAgentsModules() { if($config['pure'] != 1){ echo '
'; + . ui_get_url_refresh (array ('offset' => $offset, 'hor_offset' => $offset, 'group_id' => $group_id, 'modulegroup' => $modulegroup)).'">'; echo ''; echo ""; echo ""; - echo ""; + echo ""; echo ""; echo ""; echo ""; @@ -375,9 +380,14 @@ function mainAgentsModules() { } if ($group_id > 0) { - $filter_groups['id_grupo'] = $group_id; + if($recursion){ + $filter_groups['id_grupo'] = array_merge($group_id, + groups_get_id_recursive($group_id, true)); + } + else{ + $filter_groups['id_grupo'] = $group_id; + } } - $agents = agents_get_agents ($filter_groups); $nagents = count($agents); @@ -675,12 +685,14 @@ $ignored_params['refresh']=''; } $("#group_id").change (function () { + jQuery.post ("ajax.php", {"page" : "operation/agentes/ver_agente", "get_agents_group_json" : 1, "id_group" : this.value, "privilege" : "AW", - "keys_prefix" : "_" + "keys_prefix" : "_", + "recursion" : $('#checkbox-recursion').is(':checked') }, function (data, status) { $("#id_agents2").html(''); @@ -699,7 +711,34 @@ $ignored_params['refresh']=''; "json" ); }); - + + $("#checkbox-recursion").change (function () { + jQuery.post ("ajax.php", + {"page" : "operation/agentes/ver_agente", + "get_agents_group_json" : 1, + "id_group" : $("#group_id").val(), + "privilege" : "AW", + "keys_prefix" : "_", + "recursion" : $('#checkbox-recursion').is(':checked') + }, + function (data, status) { + $("#id_agents2").html(''); + $("#module").html(''); + jQuery.each (data, function (id, value) { + // Remove keys_prefix from the index + id = id.substring(1); + + option = $("") + .attr ("value", value["id_agente"]) + .html (value["alias"]); + $("#id_agents").append (option); + $("#id_agents2").append (option); + }); + }, + "json" + ); + }); + $("#modulegroup").change (function () { jQuery.post ("ajax.php", {"page" : "operation/agentes/ver_agente", diff --git a/pandora_console/extensions/db_status.php b/pandora_console/extensions/db_status.php index e5e1d84331..2b0e281993 100755 --- a/pandora_console/extensions/db_status.php +++ b/pandora_console/extensions/db_status.php @@ -31,8 +31,6 @@ function extension_db_status_extension_tables() { function extension_db_status() { global $config; - - $db_user = get_parameter('db_user', ''); $db_password = get_parameter('db_password', ''); $db_host = get_parameter('db_host', ''); @@ -40,11 +38,11 @@ function extension_db_status() { $db_status_execute = (bool)get_parameter('db_status_execute', false); - ui_print_page_header (__("DB Status"), + ui_print_page_header (__("DB Schema check"), "images/extensions.png", false, "", true, ""); - if (! check_acl ($config['id_user'], 0, "DM")) { + if (!is_user_admin($config['id_user'])) { db_pandora_audit("ACL Violation", "Trying to access db status"); require ("general/noaccess.php"); @@ -184,7 +182,7 @@ function extension_db_check_tables_differences($connection_test, ui_print_result_message( empty($diff_tables), __('Successful the DB Pandora has all tables'), - __('Unsuccessful the DB Pandora has not all tables. The tables lost are (%s)', + __('Pandora DB could not retrieve all tables. The missing tables are (%s)', implode(", ", $diff_tables))); if (!empty($diff_tables)) { @@ -233,16 +231,15 @@ function extension_db_check_tables_differences($connection_test, if (!empty($result)) { while ($row = mysql_fetch_array ($result)) { $fields_system[$row[0]] = array( - 'field ' => $row[0], - 'type' => $row[1], - 'null' => $row[2], - 'key' => $row[3], + 'field ' => $row[0], + 'type' => $row[1], + 'null' => $row[2], + 'key' => $row[3], 'default' => $row[4], - 'extra' => $row[5]); + 'extra' => $row[5]); } mysql_free_result ($result); } - foreach ($fields_test as $name_field => $field_test) { if (!isset($fields_system[$name_field])) { $correct_fields = false; @@ -262,13 +259,12 @@ function extension_db_check_tables_differences($connection_test, $field_system = $fields_system[$name_field]; $diff = array_diff($field_test, $field_system); - if (!empty($diff)) { foreach ($diff as $config_field => $value) { switch ($config_field) { case 'type': ui_print_error_message( - __('Unsuccessful the field %s in the table %s must be setted the type with %s.', + __('Unsuccessful the field %s in the table %s must be set the type with %s.', $name_field, $table, $value)); ui_print_info_message( __('You can execute this SQL query for to fix.') . "
" . @@ -279,13 +275,14 @@ function extension_db_check_tables_differences($connection_test, break; case 'null': ui_print_error_message( - __('Unsuccessful the field %s in the table %s must be setted the null values with %s.', + __('Unsuccessful the field %s in the table %s must be null: (%s).', $name_field, $table, $value)); - if ($value == "no") { + + if ($value == "YES") { ui_print_info_message( __('You can execute this SQL query for to fix.') . "
" . '
' .
-											"ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . "INT NULL;" .
+											"ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . " "  . $field_test['type'] . " NULL;" .
 										'
' ); } @@ -293,7 +290,7 @@ function extension_db_check_tables_differences($connection_test, ui_print_info_message( __('You can execute this SQL query for to fix.') . "
" . '
' .
-											"ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . "INT NOT NULL;" .
+											"ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . " " . $field_test['type'] . " NOT NULL;" .
 										'
' ); } @@ -301,21 +298,31 @@ function extension_db_check_tables_differences($connection_test, break; case 'key': ui_print_error_message( - __('Unsuccessful the field %s in the table %s must be setted the key as defined in the SQL file.', + __('Unsuccessful the field %s in the table %s must be set the key as defined in the SQL file.', $name_field, $table)); ui_print_info_message( __('Please check the SQL file for to know the kind of key needed.')); break; case 'default': + if($field_test['null'] == "YES" || !isset($field_test['null']) || $field_test['null'] == ""){ + $null_defect = " NULL"; + } + else{ + $null_defect = " NOT NULL"; + } ui_print_error_message( - __('Unsuccessful the field %s in the table %s must be setted the default value as %s.', + __('Unsuccessful the field %s in the table %s must be set %s as default value.', $name_field, $table, $value)); ui_print_info_message( - __('Please check the SQL file for to know the kind of default value needed.')); + __('You can execute this SQL query for to fix.') . "
" . + '
' .
+											"ALTER TABLE " . $table . " MODIFY COLUMN " . $name_field . " "  . $field_test['type'] . $null_defect . " DEFAULT " . $value . ";" .
+										'
' + ); break; case 'extra': ui_print_error_message( - __('Unsuccessful the field %s in the table %s must be setted as defined in the SQL file.', + __('Unsuccessful the field %s in the table %s must be set as defined in the SQL file.', $name_field, $table)); ui_print_info_message( __('Please check the SQL file for to know the kind of extra config needed.')); @@ -358,5 +365,5 @@ function extension_db_status_execute_sql_file($url, $connection) { } extensions_add_godmode_function('extension_db_status'); -extensions_add_godmode_menu_option(__('DB Status'), 'DM', 'gextensions', null, "v1r1", 'gdbman'); +extensions_add_godmode_menu_option(__('DB Schema check'), 'DM', 'gextensions', null, "v1r1", 'gdbman'); ?> \ No newline at end of file diff --git a/pandora_console/extensions/dbmanager.php b/pandora_console/extensions/dbmanager.php index c74332b1eb..114c3bf709 100644 --- a/pandora_console/extensions/dbmanager.php +++ b/pandora_console/extensions/dbmanager.php @@ -114,7 +114,7 @@ function dbmgr_extension_main () { global $config; - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { + if (!is_user_admin($config['id_user'])) { db_pandora_audit("ACL Violation", "Trying to access Setup Management"); require ("general/noaccess.php"); return; @@ -167,7 +167,7 @@ function dbmgr_extension_main () { echo 'An error has occured when querying the database.
'; echo $error; - db_pandora_audit("Extension DB inface", "Error in SQL", false, false, $sql); + db_pandora_audit("DB Interface Extension", "Error in SQL", false, false, $sql); return; } @@ -175,7 +175,7 @@ function dbmgr_extension_main () { if (! is_array ($result)) { echo "Output: ".$result; - db_pandora_audit("Extension DB inface", "SQL", false, false, $sql); + db_pandora_audit("DB Interface Extension", "SQL", false, false, $sql); return; } diff --git a/pandora_console/extensions/system_info.php b/pandora_console/extensions/system_info.php deleted file mode 100644 index 82180f52f8..0000000000 --- a/pandora_console/extensions/system_info.php +++ /dev/null @@ -1,818 +0,0 @@ - $temp2[0], - 'Size' => $temp2[1], - 'Used' => $temp2[2], - 'Use%' => $temp2[3], - 'Avail' => $temp2[4], - 'Mounted_on' => $temp2[5] - ); - $disk[] = $info; - } - - $systemInfo['disk'] = $disk; - - $result = shell_exec('uptime'); - preg_match('/.* load average: (.*)/', $result, $matches); - - $systemInfo['load_average'] = $matches[1]; - - $result = shell_exec('ps -Ao cmd | tail --lines=+2'); - $temp = explode("\n", $result); - foreach ($temp as $line) { - if ($line != '') { - $process[] = $line; - } - } - $systemInfo['process'] = $process; - - $logs_directory = (!empty($config["server_log_dir"])) ? io_safe_output($config["server_log_dir"]) : "/var/log/pandora"; - - $result = shell_exec('du -h ' . $logs_directory . ' | cut -d"/" -f1'); - $systemInfo['size_var_log_pandora'] = $result; - - $result = shell_exec('date'); - $systemInfo['date'] = $result; -} - -function getLastLinesLog($file, $numLines = 2000) { - $result = shell_exec('tail -n ' . $numLines . ' ' . $file); - - return $result; -} - -function show_logfile($file_name, $numLines = 2000) { - global $config; - - if (!file_exists($file_name)) { - echo "

" . __("Cannot find file") . "(" . $file_name . - ")

"; - } - else { - if (!is_readable($file_name)) { - echo "

" . __("Cannot read file") . "(" . $file_name . - ")

"; - } - else { - echo "

" . $file_name . "

"; - echo ""; - } - } -} - -function logFilesLines($file_name, $numLines) { - global $config; - - if (!file_exists($file_name)) { - return ''; - } - else { - if (!is_readable($file_name)) { - return ''; - } - else { - return shell_exec('tail -n ' . $numLines . ' ' . $file_name); - } - } -} - -function getLastLog($numLines = 2000) { - global $config; - - $logs_directory = (!empty($config["server_log_dir"])) ? io_safe_output($config["server_log_dir"]) : "/var/log/pandora"; - - show_logfile($config["homedir"]."/pandora_console.log", $numLines); - show_logfile($logs_directory."/pandora_server.log", $numLines); - show_logfile($logs_directory."/pandora_server.error", $numLines); - show_logfile("/etc/mysql/my.cnf", $numLines); - show_logfile($config["homedir"]."/include/config.php", $numLines); - show_logfile("/etc/pandora/pandora_server.conf", $numLines); - show_logfile("/var/log/syslog", $numLines); -} - -function show_array($title, $anchor, $array = array()) { - - $table = new StdClass(); - $table->width = '100%'; - $table->class = "databox filters"; - $table->head = array(); - $table->head[0] = $title; - $table->data = array(); - - foreach ($array as $index => $item) { - if (!is_array($item)) { - $row = array(); - $row[] = $index; - $row[] = $item; - $table->data[] = $row; - } - else { - foreach ($item as $index2 => $item2) { - if (!is_array($item2)) { - $row = array(); - $row[] = $index; - $row[] = $index2; - $row[] = $item2; - $table->data[] = $row; - } - else { - foreach ($item2 as $index3 => $item3) { - $row = array(); - $row[] = $index; - $row[] = $index2; - $row[] = $index3; - $row[] = $item3; - $table->data[] = $row; - } - } - } - } - } - - echo "

" . $title . "

"; - - html_print_table($table); -} - -function generate_info($checks, $log_num_lines = 2000) { - global $config; - - $pandora_diag = isset($checks['pandora_diagnostic']) ? $checks['pandora_diagnostic'] : false; - $system_info = isset($checks['system_info']) ? $checks['system_info'] : false; - $log_info = isset($checks['log_info']) ? $checks['log_info'] : false; - - $tempDirSystem = sys_get_temp_dir(); - $nameDir = 'dir_' . uniqid(); - $tempDir = $tempDirSystem . '/' . $nameDir . '/'; - mkdir($tempDir); - - $zipArchive = $config['attachment_store'] . '/last_info.zip'; - @unlink($zipArchive); - - $url_zip = ui_get_full_url(false); - - $url = $url_zip . 'attachment/last_info.zip'; - - $result = array(); - $result['success'] = false; - $result['url'] = $url; - $result['location'] = $zipArchive; - - $some_check = $log_info || $system_info || $pandora_diag; - - $zip = new ZipArchive; - - $zip_openned = $zip->open($zipArchive, ZIPARCHIVE::CREATE) === true; - - if ($some_check && $zip_openned) { - - if ($pandora_diag) { - $systemInfo = array(); - getPandoraDiagnostic($systemInfo); - - $file = fopen($tempDir . 'pandora_diagnostic.txt', 'w'); - - if ($file !== false) { - ob_start(); - foreach ($systemInfo as $index => $item) { - if (is_array($item)) { - foreach ($item as $secondIndex => $secondItem) { - echo $index. ";" . $secondIndex . ";" . $secondItem . "\n"; - } - } - else { - echo $index . ";" . $item . "\n"; - } - } - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $zip->addFile($tempDir . 'pandora_diagnostic.txt', 'pandora_diagnostic.txt'); - } - - if ($system_info) { - $info = array(); - getSystemInfo($info); - - $file = fopen($tempDir . 'system_info.txt', 'w'); - - if ($file !== false) { - ob_start(); - $string = ""; - foreach ($info as $index => $item) { - if (is_array($item)) { - foreach ($item as $secondIndex => $secondItem) { - if (is_array($secondItem)) { - foreach ($secondItem as $thirdIndex => $thirdItem) { - if (is_array($thirdItem)) { - echo $index. ";" . $secondIndex . ";" . $thirdIndex . "\n"; - } - else { - echo $index. ";" . $secondIndex . ";" . $thirdIndex . ";" . $thirdItem . "\n"; - } - } - } - else { - echo $index. ";" . $secondIndex . ";" . $secondItem . "\n"; - } - - } - } - else { - echo $index . ";" . $item . "\n"; - } - } - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $zip->addFile($tempDir . 'system_info.txt', 'system_info.txt'); - } - - $server_logs_directory = (!empty($config["server_log_dir"])) ? io_safe_output($config["server_log_dir"]) : "/var/log/pandora"; - - if ($log_info) { - file_put_contents($tempDir . 'pandora_console.log.lines_' . $log_num_lines, getLastLinesLog($config["homedir"]."/pandora_console.log", $log_num_lines)); - $zip->addFile($tempDir . 'pandora_console.log.lines_' . $log_num_lines, 'pandora_console.log.lines_' . $log_num_lines); - file_put_contents($tempDir . 'pandora_server.log.lines_' . $log_num_lines, getLastLinesLog($server_logs_directory."/pandora_server.log", $log_num_lines)); - $zip->addFile($tempDir . 'pandora_server.log.lines_' . $log_num_lines, 'pandora_server.log.lines_' . $log_num_lines); - file_put_contents($tempDir . 'pandora_server.error.lines_' . $log_num_lines, getLastLinesLog($server_logs_directory."/pandora_server.error", $log_num_lines)); - $zip->addFile($tempDir . 'pandora_server.error.lines_' . $log_num_lines, 'pandora_server.error.lines_' . $log_num_lines); - file_put_contents($tempDir . 'my.cnf.lines_' . $log_num_lines, getLastLinesLog("/etc/mysql/my.cnf", $log_num_lines)); - $zip->addFile($tempDir . 'my.cnf.lines_' . $log_num_lines, 'my.cnf.lines_' . $log_num_lines); - file_put_contents($tempDir . 'config.php.lines_' . $log_num_lines, getLastLinesLog($config["homedir"]."/include/config.php", $log_num_lines)); - $zip->addFile($tempDir . 'config.php.lines_' . $log_num_lines, 'config.php.lines_' . $log_num_lines); - file_put_contents($tempDir . 'pandora_server.conf.lines_' . $log_num_lines, getLastLinesLog("/etc/pandora/pandora_server.conf", $log_num_lines)); - $zip->addFile($tempDir . 'pandora_server.conf.lines_' . $log_num_lines, 'pandora_server.conf.lines_' . $log_num_lines); - file_put_contents($tempDir . 'syslog.lines_' . $log_num_lines, getLastLinesLog("/var/log/syslog", $log_num_lines)); - $zip->addFile($tempDir . 'syslog.lines_' . $log_num_lines, 'syslog.lines_' . $log_num_lines); - } - - $zip->close(); - - $result['date'] = ui_print_timestamp(filectime($zipArchive), true); - $result['success'] = true; - } - elseif (!$some_check) { - $result['message'] = __('No options selected'); - } - elseif (!$zip_openned) { - $result['message'] = __('There was an error with the zip file'); - } - - return $result; -} - -function mainSystemInfo() { - global $config; - - - if (! check_acl ($config['id_user'], 0, "PM") && ! is_user_admin ($config['id_user'])) { - db_pandora_audit("ACL Violation", "Trying to access Setup Management"); - require ("general/noaccess.php"); - - return; - } - - $show = (bool) get_parameter('show'); - $generate = (bool) get_parameter('generate'); - $pandora_diag = (bool) get_parameter('pandora_diag', 0); - $system_info = (bool) get_parameter('system_info', 0); - $log_info = (bool) get_parameter('log_info', 0); - $log_num_lines = (int) get_parameter('log_num_lines', 2000); - - ui_print_page_header (__("System Info"), "images/extensions.png", false, "", true, "" ); - - echo '
'; - echo __("This extension can run as PHP script in a shell for extract more information, but it must be run as root or across sudo. For example: sudo php /var/www/pandora_console/extensions/system_info.php -d -s -c"); - echo '
'; - - $table = new StdClass(); - $table->width = '100%'; - $table->class = 'databox filters'; - $table->align = array(); - - if ($pandora_diag) { - $table->data[0][0] = '' . - __('Pandora Diagnostic info') . ""; - } - else { - $table->data[0][0] = __('Pandora Diagnostic info'); - } - $table->data[0][0] .= html_print_checkbox('pandora_diag', 1, $pandora_diag, true); - if ($system_info) { - $table->data[0][2] = '' . __('System info') . ''; - } - else { - $table->data[0][2] = __('System info'); - } - $table->data[0][2] .= html_print_checkbox('system_info', 1, $system_info, true); - - if ($log_info) { - $table->data[0][3] = '' . __('Log Info') . ''; - } - else { - $table->data[0][3] = __('Log Info'); - } - $table->data[0][3] .= html_print_checkbox('log_info', 1, $log_info, true); - $table->data[0][4] = __('Number lines of log'); - $table->data[0][4] .= html_print_input_text('log_num_lines', $log_num_lines, __('Number lines of log'), 5, 10, true); - - - $default_location = $config['attachment_store'] . '/last_info.zip'; - $file_exists = file_exists($default_location) && is_readable($default_location); - - $table_file = new StdClass(); - $table_file->id = "table_file"; - $table_file->class = "databox filters"; - $table_file->width = '100%'; - $table_file->style = array(); - $table_file->style[0] = "font-weight: bold"; - $table_file->data = array(); - - $display_file_link = $file_exists ? "" : "style=\"display: none;\""; - $url = ui_get_full_url(false) . "attachment/last_info.zip"; - $file_link = ""; - $file_link .= html_print_image('images/file.png', true, array('title' => __('Download'))); // Download image - $file_link .= ""; - - $data = array(); - $data[0] = __('File'); - $data['cell-link'] = $file_link; - $table_file->data['row_link'] = $data; - - $data = array(); - $data[0] = __('Created'); - $data['cell-date'] = $file_exists ? ui_print_timestamp(filectime($default_location), true) : ''; - $table_file->data['row_date'] = $data; - - $data = array(); - $data[0] = __('Location'); - $data['cell-location'] = $file_exists ? $default_location : ''; - $table_file->data['row_location'] = $data; - - echo ""; - - html_print_table($table); - - $display_table_file = $file_exists ? "" : "style=\"display: none;\""; - echo "
"; - html_print_table($table_file); - echo "
"; - - echo "
"; - html_print_submit_button(__('Generate file'), 'generate', false, 'class="sub next"'); - html_print_image('images/spinner.gif', false, array('id' => 'spinner_img', 'title' => __('Loading'), 'style' => 'display: none;')); - echo "
"; - echo ""; - - if ($show) { - if ($pandora_diag) { - $info = array(); - getPandoraDiagnostic($info); - show_array(__('Pandora Diagnostic info'), 'diag_info', $info); - } - - if ($system_info) { - $info = array(); - getSystemInfo($info); - show_array(__('System info'), 'system_info', $info); - } - - if ($log_info) { - echo "

" . __('Log Info') . "

"; - getLastLog($log_num_lines); - } - } - elseif ($generate) { - $checks = array(); - $checks['pandora_diagnostic'] = $pandora_diag; - $checks['system_info'] = $system_info; - $checks['log_info'] = $log_info; - $result = generate_info($checks, $log_num_lines); - - if ($result['success']) { - echo '' . __('File') . ': ' . $result['url'] . '
'; - echo '' . __('Location') . ': ' . $result['location']; - } - elseif (isset($result['message'])) { - echo $result['message']; - } - else { - echo __('Error'); - } - } - -?> - - $item) { - if (is_array($item)) { - foreach ($item as $secondIndex => $secondItem) { - echo $index. ";" . $secondIndex . ";" . $secondItem . "\n"; - } - } - else { - echo $index . ";" . $item . "\n"; - } - } - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - } - - if ($pandoraSystemInfo) { - $systemInfo = array(); - getSystemInfo($systemInfo, true); - - $file = fopen($tempDir . 'system_info.txt', 'w'); - - if ($file !== false) { - ob_start(); - foreach ($systemInfo as $index => $item) { - if (is_array($item)) { - foreach ($item as $secondIndex => $secondItem) { - if (is_array($secondItem)) { - foreach ($secondItem as $thirdIndex => $thirdItem) { - echo $index. ";" . $secondIndex . ";" . $thirdIndex . ";" . $thirdItem . "\n"; - } - } - else { - echo $index. ";" . $secondIndex . ";" . $secondItem . "\n"; - } - } - } - else { - echo $index . ";" . $item . "\n"; - } - } - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - } - - if ($pandoraConfFiles) { - $lines = 2000; - - $system_logs_directory = (!empty($config["server_log_dir"])) ? io_safe_output($config["server_log_dir"]) : "/var/log/pandora"; - - $file = fopen($tempDir . 'pandora_console.log' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog($config["homedir"]."/pandora_console.log", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'pandora_server.log' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog($system_logs_directory."/pandora_server.log", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'pandora_server.error' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog($system_logs_directory."/pandora_server.error", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'my.cnf', 'w'); - if ($file !== false) { - ob_start(); - echo file_get_contents('/etc/mysql/my.cnf'); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'my.cnf', 'w'); - if ($file !== false) { - ob_start(); - echo file_get_contents($config["homedir"]."/include/config.php"); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'pandora_server.conf', 'w'); - if ($file !== false) { - ob_start(); - echo file_get_contents("/etc/pandora/pandora_server.conf"); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'syslog' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog("/var/log/syslog", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'pandora_server.error' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog($system_logs_directory."/pandora_server.error", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - - $file = fopen($tempDir . 'pandora_server.log' . $lines, 'w'); - if ($file !== false) { - ob_start(); - echo getLastLinesLog($system_logs_directory."/pandora_server.log", $lines); - $output = ob_get_clean(); - fwrite($file, $output); - fclose($file); - } - } - echo 'tar zcvf ' . $tempDirSystem . '/' . $nameDir . '.tar.gz ' . $tempDir . '*' . "\n"; - $result = shell_exec('tar zcvf ' . $tempDirSystem . '/' . $nameDir . '.tar.gz ' . $tempDir . '*'); - - //TODO Delete the temp directory - - echo "You find the result file in " . $tempDirSystem . '/' . $nameDir . ".tar.gz\n"; - } -} - -if (!isset($argv)) { - //Execution across the browser - extensions_add_godmode_function('mainSystemInfo'); - extensions_add_godmode_menu_option(__('System Info'), 'PM', 'gextensions', null, "v1r1"); -} -else { - $dir = dirname($_SERVER['PHP_SELF']); - $dir = str_replace("\\", "/", $dir); // Windows compatibility - if (file_exists($dir . "/../include/config.php")) - include $dir . "/../include/config.php"; - - consoleMode(); -} -?> diff --git a/pandora_console/extras/mr/7.sql b/pandora_console/extras/mr/7.sql new file mode 100644 index 0000000000..8bbe1a7df2 --- /dev/null +++ b/pandora_console/extras/mr/7.sql @@ -0,0 +1,4 @@ + +START TRANSACTION; +ALTER TABLE tlayout_data ADD COLUMN `show_statistics` tinyint(2) NOT NULL default '0'; +COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/mr/8.sql b/pandora_console/extras/mr/8.sql new file mode 100644 index 0000000000..977f7989fd --- /dev/null +++ b/pandora_console/extras/mr/8.sql @@ -0,0 +1,3 @@ +START TRANSACTION; +ALTER TABLE tusuario ADD COLUMN `time_autorefresh` int(5) unsigned NOT NULL default '30'; +COMMIT; \ No newline at end of file diff --git a/pandora_console/extras/pandora_diag.php b/pandora_console/extras/pandora_diag.php index 5eff93bc65..a59d94022e 100644 --- a/pandora_console/extras/pandora_diag.php +++ b/pandora_console/extras/pandora_diag.php @@ -38,9 +38,10 @@ function render_row ($data, $label) { } else { echo "
"; - echo ""; + echo ""; + echo ""; echo ""; } } @@ -89,35 +90,150 @@ else { // Header ui_print_page_header (__('Pandora FMS Diagnostic tool'), "", false, "", true); - echo "
" . $filter_groups_label . "" . $filter_groups . "" . $filter_groups ."   ". $filter_recursion_label . $filter_recursion. "" . $filter_module_groups_label . "
" . $label; - echo "" . $data; - echo "
" . $label; + echo "
" . $data; + echo "
"; - echo ""; - echo ""; + echo "
".__("Item")."".__("Data value")."
"; + echo ""; } render_row ($build_version, "Pandora FMS Build"); render_row ($pandora_version, "Pandora FMS Version"); +render_info_data ("SELECT value FROM tconfig where token ='MR'","Minor Release"); render_row ($config["homedir"], "Homedir"); render_row ($config["homeurl"], "HomeUrl"); +render_info_data ("SELECT `value` + FROM tconfig + WHERE `token` = 'enterprise_installed'", "Enterprise installed"); + + $full_key = db_get_sql("SELECT value + FROM tupdate_settings + WHERE `key` = 'customer_key'"); + + $compressed_key = substr($full_key, 0,5).'...'.substr($full_key, -5); + + render_row ($compressed_key,"Update Key"); + + render_info_data ("SELECT value + FROM tupdate_settings + WHERE `key` = 'updating_code_path'", "Updating code path"); + + render_info_data ("SELECT value + FROM tupdate_settings + WHERE `key` = 'current_update'", "Current Update #"); + + +echo ""; + + render_row (phpversion(), "PHP Version"); -render_info ("tagente"); -render_info ("tagent_access"); -render_info ("tagente_datos"); -render_info ("tagente_datos_string"); -render_info ("tagente_estado"); -render_info ("tagente_modulo"); -render_info ("talert_actions"); -render_info ("talert_commands"); -render_info ("talert_template_modules"); -render_info ("tevento"); -render_info ("tlayout"); +render_row (ini_get('max_execution_time'), "PHP Max execution time"); + +render_row (ini_get('max_input_time'), "PHP Max input time"); + +render_row (ini_get('memory_limit'), "PHP Memory limit"); + +render_row (ini_get('session.cookie_lifetime'), "Session cookie lifetime"); + +echo ""; + +render_info_data ("SELECT COUNT(*) FROM tagente","Total agents"); +render_info_data ("SELECT COUNT(*) FROM tagente_modulo","Total modules"); +render_info_data ("SELECT COUNT(*) FROM tgrupo","Total groups"); +render_info_data ("SELECT COUNT(*) FROM tagente_datos","Total module data records"); +// render_info_data ("SELECT COUNT(*) FROM tagente_datos_string","Total module string data records"); +// render_info_data ("SELECT COUNT(*) FROM tagente_datos_log4x","Total module log4x data records"); +render_info_data ("SELECT COUNT(*) FROM tagent_access","Total agent access record"); +// render_info ("tagente_estado"); +// render_info ("talert_template_modules"); +render_info_data ("SELECT COUNT(*) FROM tevento","Total events"); + if($config['enterprise_installed']) - render_info ("tlocal_component"); -render_info ("tserver"); -render_info ("treport"); -render_info ("ttrap"); -render_info ("tusuario"); -render_info ("tsesion"); +render_info_data ("SELECT COUNT(*) FROM ttrap","Total traps"); +render_info_data ("SELECT COUNT(*) FROM tusuario","Total users"); +render_info_data ("SELECT COUNT(*) FROM tsesion","Total sessions"); + +echo ""; + +render_info_data ("SELECT COUNT( DISTINCT tagente.id_agente) + FROM tagente_estado, tagente, tagente_modulo + WHERE tagente.disabled = 0 + AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo + AND tagente_modulo.disabled = 0 + AND tagente_estado.id_agente = tagente.id_agente + AND tagente_estado.estado = 3","Total unknown agents"); + +render_info_data ("SELECT COUNT(tagente_estado.estado) + FROM tagente_estado + WHERE tagente_estado.estado = 4","Total not-init modules"); + + +$last_run_difference = ''; + +$diferencia = time() - date ( + db_get_sql ("SELECT `value` + FROM tconfig + WHERE `token` = 'db_maintance'")); + +$last_run_difference_months = 0; +$last_run_difference_weeks = 0; +$last_run_difference_days = 0; +$last_run_difference_minutos = 0; +$last_run_difference_seconds = 0; + +while($diferencia >= 2419200){ + $diferencia -= 2419200; + $last_run_difference_months++; +} + +while($diferencia >= 604800){ + $diferencia -= 604800; + $last_run_difference_weeks++; +} + +while($diferencia >= 86400){ + $diferencia -= 86400; + $last_run_difference_days++; +} + +while($diferencia >= 3600){ + $diferencia -= 3600; + $last_run_difference_hours++; +} + +while($diferencia >= 60){ + $diferencia -= 60; + $last_run_difference_minutes++; +} + +$last_run_difference_seconds = $diferencia; + +if($last_run_difference_months > 0){ + $last_run_difference .= $last_run_difference_months.'month/s '; +} + +if ($last_run_difference_weeks > 0) { + $last_run_difference .= $last_run_difference_weeks.' week/s '; +} + +if ($last_run_difference_days > 0) { + $last_run_difference .= $last_run_difference_days.' day/s '; +} + +if ($last_run_difference_hours > 0) { + $last_run_difference .= $last_run_difference_hours.' hour/s '; +} + +if ($last_run_difference_minutes > 0) { + $last_run_difference .= $last_run_difference_minutes.' minute/s '; +} + +$last_run_difference .= $last_run_difference_seconds.' second/s ago'; + +render_row ( date ("Y/m/d H:i:s", +db_get_sql ("SELECT `value` + FROM tconfig + WHERE `token` = 'db_maintance'")).' ('.$last_run_difference.')'.' *', "PandoraDB Last run"); + +echo ""; switch ($config["dbtype"]) { case "mysql": @@ -130,23 +246,22 @@ switch ($config["dbtype"]) { render_info_data ("SELECT `value` FROM tconfig WHERE `token` = 'db_scheme_build'", "DB Schema Build"); - render_info_data ("SELECT `value` - FROM tconfig - WHERE `token` = 'enterprise_installed'", "Enterprise installed"); - render_row ( date ("Y/m/d H:i:s", - db_get_sql ("SELECT `value` - FROM tconfig - WHERE `token` = 'db_maintance'")), "PandoraDB Last run"); + + if(strpos($_SERVER['HTTP_USER_AGENT'],'Windows') == false){ + + echo ""; + + $output = 'cat /proc/cpuinfo | grep "model name" | tail -1 | cut -f 2 -d ":"'; + $output2 = 'cat /proc/cpuinfo | grep "processor" | wc -l'; + + render_row(exec($output).' x '.exec($output2),'CPU'); + + $output = 'cat /proc/meminfo | grep "MemTotal"'; + + render_row(exec($output),'RAM'); + + } - render_info_data ("SELECT value - FROM tupdate_settings - WHERE `key` = 'customer_key';", "Update Key"); - render_info_data ("SELECT value - FROM tupdate_settings - WHERE `key` = 'updating_code_path'", "Updating code path"); - render_info_data ("SELECT value - FROM tupdate_settings - WHERE `key` = 'current_update'", "Current Update #"); break; case "postgresql": render_info_data ("SELECT \"value\" @@ -201,4 +316,12 @@ switch ($config["dbtype"]) { if ($console_mode == 0) { echo "
".__("Pandora status info")."
".__("PHP setup")."
".__("Database size stats")."
".__("Database sanity")."
".__("Database status info")."
".__("System info")."
"; } + +echo "
"; + +echo "".__('(*) Please check your Pandora Server setup and be sure that database maintenance daemon is running. It\' very important to +keep up-to-date database to get the best performance and results in Pandora')."


"; + + + ?> \ No newline at end of file diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index c5012eac00..2b9d8c5a5a 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -1150,10 +1150,10 @@ ALTER TABLE titem MODIFY `source_data` int(10) unsigned; INSERT INTO `tconfig` (`token`, `value`) VALUES ('big_operation_step_datos_purge', '100'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('small_operation_step_datos_purge', '1000'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('days_autodisable_deletion', '30'); -INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 4); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 7); UPDATE tconfig SET value = 'https://licensing.artica.es/pandoraupdate7/server.php' WHERE token='url_update_manager'; DELETE FROM `tconfig` WHERE `token` = 'current_package_enterprise'; -INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '708'); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '714'); -- --------------------------------------------------------------------- -- Table `tplanned_downtime_agents` @@ -1183,6 +1183,7 @@ ALTER TABLE tusuario ADD COLUMN `id_filter` int(10) UNSIGNED NULL DEFAULT NULL; ALTER TABLE tusuario ADD CONSTRAINT `fk_id_filter` FOREIGN KEY (`id_filter`) REFERENCES tevent_filter(`id_filter`) ON DELETE SET NULL; ALTER TABLE tusuario ADD COLUMN `session_time` int(10) signed NOT NULL default '0'; alter table tusuario add autorefresh_white_list text not null default ''; +ALTER TABLE tusuario ADD COLUMN `time_autorefresh` int(5) unsigned NOT NULL default '30'; -- --------------------------------------------------------------------- -- Table `tagente_modulo` @@ -1230,6 +1231,7 @@ ALTER TABLE tlayout ADD `background_color` varchar(50) NOT NULL default '#FFF'; -- --------------------------------------------------------------------- ALTER TABLE tlayout_data ADD `type_graph` varchar(50) NOT NULL default 'area'; ALTER TABLE tlayout_data ADD `label_position` varchar(50) NOT NULL default 'down'; +ALTER TABLE tlayout_data ADD COLUMN `show_statistics` tinyint(2) NOT NULL default '0'; -- --------------------------------------------------------------------- -- Table `tagent_custom_fields` diff --git a/pandora_console/general/header.php b/pandora_console/general/header.php index 46e95a7026..49ef936515 100644 --- a/pandora_console/general/header.php +++ b/pandora_console/general/header.php @@ -191,7 +191,7 @@ config_check(); $_GET['refr'] = null; } - $select = db_process_sql("SELECT autorefresh_white_list FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); + $select = db_process_sql("SELECT autorefresh_white_list,time_autorefresh FROM tusuario WHERE id_user = '" . $config['id_user'] . "'"); $autorefresh_list = json_decode($select[0]['autorefresh_white_list']); if ($autorefresh_list !== null && array_search($_GET['sec2'], $autorefresh_list) !== false) { @@ -389,7 +389,15 @@ config_check(); $("#combo_refr").toggle (); $("#combo_refr").css('padding-right', '9px'); href = $("a.autorefresh").attr ("href"); - $(document).attr ("location", href + "30"); + + var refresh = ''; + $(document).attr ("location", href + refresh); + + data[1][0] = __('Alias'); $table->data[1][1] = html_print_input_text ('alias', $alias, '', 50, 100, true); if($new_agent){ - $table->data[1][1] .= html_print_checkbox ("alias_as_name", 1, $alias_as_name, true).__('Use alias as name'); + $table->data[1][1] .= html_print_checkbox ("alias_as_name", 1, $config['alias_as_name'], true).__('Use alias as name'); } $table->data[2][0] = __('IP Address'); diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index bd34c56503..e2a264e6e0 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -793,7 +793,7 @@ if ($update_agent) { // if modified some agent paramenter WHERE id_group = ".$group_old); $result = db_process_sql_update ('tagente', $values, array ('id_agente' => $id_agente)); - if ($result === false) { + if ($result == false) { ui_print_error_message( __('There was a problem updating the agent')); } @@ -1043,9 +1043,7 @@ if ($update_module || $create_module) { } */ $configuration_data = str_replace('\\', "\", - io_safe_input($new_configuration_data));; - - html_debug($configuration_data, true); + io_safe_input($new_configuration_data)); } // Services are an enterprise feature, @@ -1110,7 +1108,11 @@ if ($update_module || $create_module) { $ff_event_critical = (int) get_parameter ('ff_event_critical'); $each_ff = (int) get_parameter ('each_ff'); $ff_timeout = (int) get_parameter ('ff_timeout'); - $unit = (string) get_parameter('unit'); + $unit = (string) get_parameter('unit_select'); + if($unit == "none"){ + $unit = (string) get_parameter('unit_text'); + } + $id_tag = (array) get_parameter('id_tag_selected'); $serialize_ops = (string) get_parameter('serialize_ops'); $critical_instructions = (string) get_parameter('critical_instructions'); diff --git a/pandora_console/godmode/agentes/modificar_agente.php b/pandora_console/godmode/agentes/modificar_agente.php index 712abb5dbb..090011dae9 100644 --- a/pandora_console/godmode/agentes/modificar_agente.php +++ b/pandora_console/godmode/agentes/modificar_agente.php @@ -181,7 +181,7 @@ $order_collation = ""; switch ($config["dbtype"]) { case "mysql": $order_collation = ""; - //$order_collation = "COLLATE utf8_general_ci"; + $order_collation = "COLLATE utf8_general_ci"; break; case "postgresql": case "oracle": @@ -540,10 +540,6 @@ if ($agents !== false) { } echo ''; echo ""; - if ($agent['quiet']) { - html_print_image("images/dot_green.disabled.png", false, array("border" => '0', "title" => __('Quiet'), "alt" => "")); - echo " "; - } if (check_acl ($config["id_user"], $agent["id_grupo"], "AW")) { $main_tab = 'main'; @@ -561,10 +557,30 @@ if ($agents !== false) { ''.$agent["alias"].'' . ""; echo ""; + + $in_planned_downtime = db_get_sql('SELECT executed FROM tplanned_downtime + INNER JOIN tplanned_downtime_agents ON tplanned_downtime.id = tplanned_downtime_agents.id_downtime + WHERE tplanned_downtime_agents.id_agent = '. $agent["id_agente"] . ' AND tplanned_downtime.executed = 1'); + if ($agent["disabled"]) { ui_print_help_tip(__('Disabled')); + + if (!$in_planned_downtime) { + echo ""; + } + } + + if ($agent['quiet']) { + echo " "; + html_print_image("images/dot_green.disabled.png", false, array("border" => '0', "title" => __('Quiet'), "alt" => "")); + } + + if ($in_planned_downtime) { + ui_print_help_tip (__('Agent in planned downtime'), false, 'images/minireloj-16.png'); + echo ""; } + echo '"; diff --git a/pandora_console/mobile/operation/agent.php b/pandora_console/mobile/operation/agent.php index de7833f1b1..c104857683 100644 --- a/pandora_console/mobile/operation/agent.php +++ b/pandora_console/mobile/operation/agent.php @@ -85,7 +85,7 @@ class Agent { $agent_id = $system->getRequest('agent_id', '0'); $width = $system->getRequest('width', '400'); graph_graphic_agentevents( - $this->id, $width, 30, SECONDS_1DAY, ui_get_full_url(false)); + $agent_id, $width, 30, SECONDS_1DAY, ui_get_full_url(false)); exit; } } diff --git a/pandora_console/operation/agentes/estado_agente.php b/pandora_console/operation/agentes/estado_agente.php index 151ae893ec..a458e308b3 100644 --- a/pandora_console/operation/agentes/estado_agente.php +++ b/pandora_console/operation/agentes/estado_agente.php @@ -597,22 +597,38 @@ foreach ($agents as $agent) { $agent["warning_count"], $agent["unknown_count"], $agent["total_count"], $agent["notinit_count"]); + $in_planned_downtime = db_get_sql('SELECT executed FROM tplanned_downtime + INNER JOIN tplanned_downtime_agents + ON tplanned_downtime.id = tplanned_downtime_agents.id_downtime + WHERE tplanned_downtime_agents.id_agent = '. $agent["id_agente"] . + ' AND tplanned_downtime.executed = 1'); + $data = array (); $data[0] = '
'; $data[0] .= ''; - if ($agent['quiet']) { - $data[0] .= html_print_image("images/dot_green.disabled.png", true, array("border" => '0', "title" => __('Quiet'), "alt" => "")) . " "; - } $data[0] .= ' '.$agent["alias"].''; $data[0] .= ''; + + if ($agent['quiet']) { + $data[0] .= " "; + $data[0] .= html_print_image("images/dot_green.disabled.png", true, array("border" => '0', "title" => __('Quiet'), "alt" => "")); + } + + if ($in_planned_downtime) { + $data[0] .= ui_print_help_tip (__('Agent in planned downtime'), true, 'images/minireloj-16.png'); + $data[0] .= ""; + } + $data[0] .= '
'; $data[1] = ui_print_truncate_text($agent["description"], 'description', false, true, true, '[…]', 'font-size: 6.5pt'); diff --git a/pandora_console/operation/agentes/estado_generalagente.php b/pandora_console/operation/agentes/estado_generalagente.php index 111abffeee..78f3dd06a4 100755 --- a/pandora_console/operation/agentes/estado_generalagente.php +++ b/pandora_console/operation/agentes/estado_generalagente.php @@ -74,17 +74,40 @@ $table_agent->data = array(); $data = array(); $agent_name = ui_print_agent_name($agent["id_agente"], true, 500, "font-size: medium;font-weight:bold", true); +$in_planned_downtime = db_get_sql('SELECT executed FROM tplanned_downtime + INNER JOIN tplanned_downtime_agents + ON tplanned_downtime.id = tplanned_downtime_agents.id_downtime + WHERE tplanned_downtime_agents.id_agent = '. $agent["id_agente"] . + ' AND tplanned_downtime.executed = 1'); + if ($agent['disabled']) { - $agent_name = "" . $agent_name . "" . ui_print_help_tip(__('Disabled'), true); + if ($in_planned_downtime) { + $agent_name = "" . $agent_name . ui_print_help_tip(__('Disabled'), true); + } + else { + $agent_name = "" . $agent_name . "" . ui_print_help_tip(__('Disabled'), true); + } } else if ($agent['quiet']) { - $agent_name = "" . $agent_name . " " . html_print_image("images/dot_green.disabled.png", true, array("border" => '0', "title" => __('Quiet'), "alt" => "")) . ""; + if ($in_planned_downtime) { + $agent_name = "" . $agent_name . " " . html_print_image("images/dot_green.disabled.png", true, array("border" => '0', "title" => __('Quiet'), "alt" => "")); + } + else { + $agent_name = "" . $agent_name . " " . html_print_image("images/dot_green.disabled.png", true, array("border" => '0', "title" => __('Quiet'), "alt" => "")) . ""; + } } else { $agent_name = $agent_name; } +if ($in_planned_downtime && !$agent['disabled'] && !$agent['quiet']) { + $agent_name .= "" . " " . ui_print_help_tip(__('Agent in planned downtime'), true, 'images/minireloj-16.png') . ""; +} +else if (($in_planned_downtime && !$agent['disabled']) || ($in_planned_downtime && !$agent['quiet'])) { + $agent_name .= " " . ui_print_help_tip(__('Agent in planned downtime'), true, 'images/minireloj-16.png') . ""; +} + if (!$config["show_group_name"]) $data[0] = ui_print_group_icon ($agent["id_grupo"], true); else diff --git a/pandora_console/operation/agentes/graphs.php b/pandora_console/operation/agentes/graphs.php index ff1d7bf9e3..e33d499fe8 100644 --- a/pandora_console/operation/agentes/graphs.php +++ b/pandora_console/operation/agentes/graphs.php @@ -38,8 +38,8 @@ $start_date = get_parameter ("start_date", date("Y-m-d")); $draw_events = get_parameter ("draw_events", 0); $modules = get_parameter('modules', array()); $filter = get_parameter('filter', 0); -$combined = (bool)get_parameter('combined', 1); - +$combined = get_parameter('combined', 1); +$option_type = get_parameter('option_type', 0); //---------------------------------------------------------------------- // Get modules of agent sorted as: @@ -159,7 +159,6 @@ $table->data[0][1] = html_print_select($list_modules, 'modules[]', $table->rowspan[2][0] = 7; $table->data[2][0] = ""; - $table->data[2][1] = __('Begin date'); $table->data[2][2] = html_print_input_text ("start_date", substr ($start_date, 0, 10),'', 10, 40, true); $table->data[2][2] .= html_print_image ("images/calendar_view_day.png", true, array ("onclick" => "scwShow(scwID('text-start_date'),this);")); @@ -174,12 +173,17 @@ $table->data[5][2] = __('Show alerts') . ui_print_help_tip(__('the combined graph does not show the alerts into this graph'), true); $table->data[5][3] = html_print_checkbox ("draw_alerts", 1, (bool) $draw_alerts, true); $table->data[6][2] = __('Show as one combined graph'); -$table->data[6][3] = - html_print_radio_button('combined', 1, __('one combined graph'), - $combined, true); -$table->data[6][3] .= - html_print_radio_button('combined', 0, __('several graphs for each module'), - $combined, true); +$graph_option_one_or_several = array(0 => __('several graphs for each module'), 1 => __('One combined graph')); +$table->data[6][3] = html_print_select($graph_option_one_or_several, 'combined', $combined, '', '', 1, true); + +$table->data[7][2] = __('Chart type'); +if ($combined == 1) { + $graph_option_type = array(0 => __('Area'), 1 => __('Area stack'), 2 => __('Line'), 3 => __('Line stack')); +} +else { + $graph_option_type = array(0 => __('Area'), 2 => __('Line')); +} +$table->data[7][3] = html_print_select($graph_option_type, 'option_type', $option_type, '', '', 1, true); $htmlForm = '
'; $htmlForm .= html_print_table($table, true); @@ -321,6 +325,39 @@ echo ""; // Load graphs $(document).ready(function() { + $('#combined').change(function () { + if ($('#combined').val() == 1) { + $('#option_type').empty(); + $('#option_type').append($('