3 /**********************************************************************************
4 ** (c) Copyright 2002, Brenno J.S.A.A.F. de Winter, De Winter Information Solutions
5 ** This is free software; you can redistribute it and/or modify it under the
6 ** terms of the GNU General Public License, see the file COPYING.
7 ***********************************************************************************/
12 AUTHOR : Brenno J.S.A.A.F. de Winter
13 De Winter Information Solutions
14 COPYRIGHT : 2002 - De Winter Information Solutions,
15 Brenno J.S.A.A.F. de Winter
18 First : November 8th 2002
19 Gnucomo-0.0.3: December 6th 2002
20 Gnucomo-0.0.8: September 4th 2003
22 $Log: gcm_daemon.php,v $
23 Revision 1.25 2007-12-12 09:06:21 arjen
24 Added a new script gcm_maintenance.php to cleanup the database
25 and check referential integrity. Purging old log entries is
26 removed from the gcm_daemon script.
28 Revision 1.24 2007/11/17 09:34:07 arjen
29 Cleaned up some leftovers
31 Revision 1.23 2007/11/03 10:31:12 arjen
32 Added the class definition for a filesystem parameter.
33 New issue type: 'property out of range'.
35 Revision 1.22 2007/10/23 11:23:52 arjen
36 Record the date when adding the number of abuses for an IP address
39 Revision 1.21 2007/01/11 13:47:41 arjen
40 Log_adv and derived tables removed.
41 Create notifications from log entries with pattern matching.
43 Revision 1.20 2005/06/04 07:15:16 arjen
44 Added pattern check on log entries with the service_pattern table.
46 Revision 1.19 2004/01/10 20:04:12 arjen
47 Send email about open notifications to an object's users.
49 Revision 1.18 2003/12/03 08:07:21 arjen
50 Changed the type of log_adv_daemon_email.delay and log_adv_daemon_email.xdelay
51 from time to interval. These delays can be more than 24 hours.
53 Revision 1.17 2003/10/29 09:58:29 arjen
54 Create separate notifications for different objects in service_check().
56 Revision 1.16 2003/09/03 12:48:48 arjen
57 Check the log table against the servies running on an object and
58 create notifications if a service is not supposed to be available
59 or is not known at all.
61 Revision 1.15 2003/09/02 12:48:09 arjen
62 BUGFIX: Secondary indices on log_notification were unique.
63 Additional information in the 'usr' table: 'display_name' and 'email'.
64 Added new issues and services.
66 Revision 1.14 2003/09/01 06:51:07 arjen
67 Accept command argument '-c config' to use an alternate
68 gnucomo configuration.
70 Revision 1.13 2003/08/14 10:22:42 arjen
73 Revision 1.12 2003/08/05 07:46:37 arjen
74 BUGFIX: Print an error message if a parameter does not have
77 Revision 1.11 2003/07/09 07:25:02 arjen
78 Gcm_daemon gathers statistics on parameters, notifications, etc. for all objects.
80 Revision 1.10 2003/03/29 08:33:58 arjen
81 In phpclasses/db.class.php: Added the database connection string as
82 an argument to the function copy_db_class.
83 Fixed the PHP member function db::db_connect(). The Postgres connection
84 string is now passed as an argument to that function.
86 Revision 1.9 2003/02/21 08:37:59 arjen
87 Added new table to the database: log_adv_daemon_email.
92 // $Id: gcm_daemon.php,v 1.25 2007-12-12 09:06:21 arjen Exp $
94 ini_set('include_path', '.:./classes:../phpclasses');
95 ini_set('html_errors', 'false');
97 define("BATCHSIZE", 10000);
99 //Tell the log that we're up.
100 define_syslog_variables();
102 require_once "gnucomo_config.php";
103 require_once "db.class.php";
105 // Set the standard variables //
107 $project_name = "gnucomo"; // name of the entire project
108 $app_name = "gcm_daemon"; // name of the application running
109 $developrelease = "FALSE"; // Indicates if special debug settings are needed
110 $db_version = 53; // The db_version indicates what the level of
111 // the database should be. If the database is
112 // old an update will be generated.
113 $gcmd_version = 5; // This value indicates the active version of
114 // the gcm_daemon, which is saved in the database.
115 // Log records that were not recognized before
116 // will now be recognized. The version doesn't
117 // mean anything in the overall gnucomo project.
119 //Avoid time-limit issues
122 // Scan the command arguments
124 for ($argi = 1; $argi < $argc; $argi++)
126 switch ($argv[$argi])
130 $project_name = $argv[$argi];
134 echo "Usage: gcm_daemon [-c configname]\n";
140 // Read the database settings //
141 $class_settings = new gnucomo_config();
142 if (!$class_settings->read($project_name))
144 echo "Can not read Gnucomo configuration file for $project_name.\n";
148 openlog("gnucomo", LOG_PID, LOG_DAEMON);
149 syslog(LOG_INFO, "gcm_daemon started");
151 //Open an connection to the database
152 $dbms_type = $class_settings->find_parameter("database", "type");
153 $dbms_host = $class_settings->find_parameter("database", "host");
154 $dbms_name = $class_settings->find_parameter("database", "name");
155 $dbms_user = $class_settings->find_parameter("gcm_daemon", "user");
156 $dbms_password = $class_settings->find_parameter("gcm_daemon", "password");
158 db_select($dbms_type);
160 $dbms->db_host = $dbms_host;
161 $dbms->db_name = $dbms_name;
162 $dbms->db_user = $dbms_user;
163 $dbms->db_password = $dbms_password;
164 $dbms->db_connect($class_settings->database());
166 if ($dbms->have_db_connection() == "FALSE")
168 exit ("Database connection failed.");
172 // The database connection has been made.
173 $dbms_working = copy_db_class($dbms, $class_settings->database());
176 // Verify if the database is up-to-date by checking the versionnumber
178 $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'db_version' ";
179 $dbms->query($local_sql);
181 if ($dbms->fetch_row() == "TRUE")
183 $active_version = $dbms->db_result_row[0];
185 // Update the database to the most recent version.
187 if ($active_version < $db_version)
189 include ("gnucomo_db_version.php");
194 syslog (LOG_INFO, "Couldn't initialize database version. Is this a gnucomo database?");
195 die ("Couldn't initialize database version.\n");
198 // The gcm_daemon version is maintained in the database to enable
199 // automatic update actions.
201 $local_sql = "SELECT setting_value FROM db_value
202 WHERE setting = 'gcm_daemon_version'";
203 $dbms->query($local_sql);
205 if ($dbms->fetch_row() == "TRUE")
207 if ($dbms->db_result_row[0] < $gcmd_version)
210 //Update de gcm_daemon version in the database
211 $local_sql = "UPDATE db_value SET setting_value = '".$gcmd_version;
212 $local_sql .= "' WHERE setting = 'gcm_daemon_version'";
213 $dbms->query($local_sql);
219 // Now we loop the tasks that we have to do.
225 echo "Processing logs...\n";
228 find_notifications();
229 //mail_notifications();
231 // Gather the statistics for each object
233 $obj_result = $dbms->query("SELECT objectid FROM object");
234 for ($obj = 0; $obj < $dbms->num_rows($obj_result); $obj++)
236 $object = $dbms->fetch_object($obj_result, $obj);
237 echo "Gathering statistics for object " . $object->objectid . "\n";
238 GatherStatistics($object->objectid);
241 $keep_running = false;
243 } while ($keep_running == true);
245 //Tell the log that we're ending our efforts in a nice way
247 syslog (LOG_INFO, "gcm_daemon ended nicely");
249 function process_log ()
252 /* This function will walk through the log-records that haven't been processed
253 * first a snapshot will be created of a the non-processed records.
254 * sequentially each record will dealt with. By doing that changes will be made
255 * in several log_adv_xxx tables
261 global $dbms_working;
262 global $class_settings;
266 // Find records in log that still have to be processed.
268 $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'log_processing'";
269 $dbms->query($local_sql);
271 if ($dbms->fetch_row() == "TRUE")
273 $last_log = $dbms->db_result_row[0];
276 echo "Last processed logid = $last_log \n";
278 //Query the log-table
279 $log_limit = $last_log + BATCHSIZE;
280 $local_sql = "SELECT * FROM log WHERE logid > CAST(".$last_log." AS BIGINT)
281 AND logid <= $log_limit ORDER BY logid";
282 $dbms->query($local_sql);
284 //Update the log-statistics in the object-table
285 $local_statistics_db = copy_db_class($dbms, $class_settings->database());
286 $local_findobject_db = copy_db_class($dbms, $class_settings->database());
289 $local_upper_row = $dbms->num_rows() + $last_log + 1;
290 $local_sql = "SELECT COUNT(logid), objectid from log WHERE logid > CAST(". $last_log .
291 " AS BIGINT) AND logid < CAST (" . $local_upper_row . " AS BIGINT) GROUP BY objectid";
292 $local_statistics_db->query ($local_sql);
295 for ($i = 1; $i <= $local_statistics_db->num_rows(); $i++)
297 $local_object_row = $local_statistics_db->fetch_row();
299 $local_sql = "UPDATE object SET log_count = log_count + " .
300 $local_statistics_db->db_result_row[0] . " WHERE objectid = '" .
301 $local_statistics_db->db_result_row[1] . "'";
303 $local_findobject_db->query($local_sql);
308 if ($dbms->num_rows() > 0)
311 //Create a database connection for changes in the database.
312 $dbms_changes = copy_db_class($dbms, $class_settings->database());
313 if ($dbms_changes->have_db_connection() == 'TRUE')
317 $local_sql_statistics = "";
318 $local_object_os = "";
319 $local_object_os_version = "";
321 match_log_patterns($last_log);
323 // Register that the logrecords have been processed.
325 $local_sql = "UPDATE db_value SET setting_value = '"
326 . $local_upper_row ."' where setting = 'log_processing'";
327 $dbms->query($local_sql);
330 // Update the statistics for the object-table
336 syslog (LOG_INFO, "Couldn't clone database connection.");
337 die ("Couldn't reconnect to the database.\n");
344 * Update a single statistic for some object.
345 * If it does not yet exist, it will be created.
348 function UpdateStatistic($objectid, $name, $value)
352 $result = $dbms->query("SELECT objectid FROM object_statistics WHERE
353 objectid='$objectid' AND statname='$name'");
354 if ($dbms->num_rows() == 0)
356 $dbms->query("INSERT INTO object_statistics VALUES
357 ('$objectid', '$name', '$value')");
361 $dbms->query("UPDATE object_statistics SET statvalue='$value' WHERE
362 statname='$name' AND objectid='$objectid'");
367 * Gather the statistics for a single object ($objectid).
368 * We count the number of parameters, removed parameters, notifications
369 * closed notifications and log entries. The totals of these are
370 * maintained in a separate table: object_statistics.
373 function GatherStatistics($objectid)
377 // Gather statistics on parameters
379 $r = $dbms->query("SELECT paramid FROM parameter WHERE objectid=CAST('"
380 . $objectid . "' AS BIGINT)");
381 $nr_parameters = $dbms->num_rows($r);
383 $removed_parameters = 0;
384 for ($p = 0; $p < $nr_parameters; $p++)
386 $param = pg_fetch_object($r, $p);
387 $qry ="select change_nature from history where paramid= CAST('";
388 $qry .= $param->paramid . "' AS BIGINT) order by modified desc";
389 $rhist = $dbms->query($qry);
390 if ($dbms->num_rows($rhist) == 0)
392 echo "ERROR: No history for parameter id " . $param->paramid . "\n";
396 $hist = $dbms->fetch_object($rhist, 0);
397 if ($hist->change_nature == "REMOVED")
399 $removed_parameters++;
404 UpdateStatistic($objectid, 'parameters', $nr_parameters);
405 UpdateStatistic($objectid, 'removed_parameters', $removed_parameters);
407 // Gather statistics on notifications
409 $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
410 objectid = CAST('" . $objectid . "' AS BIGINT)");
411 $cnt = $dbms->fetch_object($r, 0);
412 UpdateStatistic($objectid, 'notifications', $cnt->count);
414 $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
415 objectid = CAST('" . $objectid . "' AS BIGINT) AND statuscode ='cls'");
416 $cnt = $dbms->fetch_object($r, 0);
417 UpdateStatistic($objectid, 'closed_notifications', $cnt->count);
419 // Gather statistics on log entries
421 $r = $dbms->query("SELECT count(logid) FROM log WHERE
422 objectid = CAST('" . $objectid . "' AS BIGINT)");
423 $cnt = $dbms->fetch_object($r, 0);
424 UpdateStatistic($objectid, 'logs', $cnt->count);
427 function match_log_patterns($logstart)
431 $notifications = array();
433 $log_limit = $logstart + BATCHSIZE;
434 $noqueue_res = $dbms->query("select logid, objectid, servicecode, rawdata from log
435 where logid > $logstart and logid <= $log_limit
437 for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
439 $logentry = $dbms->fetch_object($noqueue_res, $row);
440 //echo "\n----------\n" . $logentry->rawdata . "\n----------\n";
441 $service = $logentry->servicecode;
442 $pattern_res = $dbms->query("select * from service_pattern where service='$service'
443 OR service='ANY' order by rank");
445 $match_found = false;
446 for ($patnr = 0; !$match_found && $patnr < $dbms->num_rows($pattern_res); $patnr++)
448 $srv_pat = $dbms->fetch_object($pattern_res, $patnr);
449 //echo " Checking with pattern " . $srv_pat->pattern . "\n";
450 if (ereg($srv_pat->pattern, $logentry->rawdata, $matches))
452 // Scan the argument for '$n' expressions and expand
454 $srv_pat->argument = expand_arguments($srv_pat->argument, $matches);
455 //echo " " . $srv_pat->pattern . " matches.\n";
456 //echo " Matched string: " . $matches[0] . "\n";
457 //echo " Action = " . $srv_pat->action . "(" . $srv_pat->argument . ")\n\n";
460 switch ($srv_pat->action)
466 $notif = $srv_pat->argument;
467 if (!isset($notifications[$logentry->objectid][$notif]))
469 //echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
470 $remark = "Notification generated from Gnucomo pattern match.";
471 $notifications[$logentry->objectid][$notif] =
472 $dbms->new_notification($logentry->objectid, $notif, $remark);
474 if (isset($notifications[$logentry->objectid][$notif]))
476 //echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
477 $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
478 $insertion .= $notifications[$logentry->objectid][$notif] . "', '";
479 $insertion .= $logentry->logid . "')";
480 $dbms->query($insertion);
485 //echo "Recording abuse for address ", $srv_pat->argument, "\n Log entry:\n ";
486 //echo $logentry->rawdata, "\n Pattern:\n ", $srv_pat->pattern, "\n\n";
488 if (record_abuse($logentry->logid, $logentry->objectid, $srv_pat->argument, 1) >= 32)
490 $source_ip = $srv_pat->argument;
491 $notif = 'abuses exceeded';
492 if (!isset($notifications[$logentry->objectid][$notif][$source_ip]))
494 echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
495 $remark = "Abuses from IP address $source_ip exceeded the limit.";
496 $notifid = $dbms->new_notification($logentry->objectid, $notif, $remark);
497 $notifications[$logentry->objectid][$notif][$source_ip] = $notifid;
499 // Add log entries from previously detected abuses
501 echo " Add log entries from previously detected abuses\n";
502 $abuses = $dbms->query("SELECT logid FROM log_abuse WHERE objectid = '" .
503 $logentry->objectid . "' AND source = '$source_ip'");
504 for ($abusenr = 0; $abusenr < $dbms->num_rows($abuses); $abusenr++)
506 $log_abuse = $dbms->fetch_object($abuses, $abusenr);
507 if ($log_abuse->logid != $logentry->logid)
509 $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
510 $insertion .= $notifid . "', '";
511 $insertion .= $log_abuse->logid . "')";
512 $dbms->query($insertion);
516 if (isset($notifications[$logentry->objectid][$notif][$source_ip]))
518 //echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
519 $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
520 $insertion .= $notifications[$logentry->objectid][$notif][$source_ip] . "', '";
521 $insertion .= $logentry->logid . "')";
522 $dbms->query($insertion);
527 record_abuse($logentry->logid, $logentry->objectid, $srv_pat->argument, -4);
530 echo "Error: unrecognized action in service pattern: " . $srv_pat->action . "\n";
536 // echo " " . $srv_pat->pattern . " does not match.\n";
544 * Some IP address abused us. Record the event.
545 * Return the number of abuse points recorded so far for the address
548 function record_abuse($logid, $objectid, $sourceip, $points)
552 $abuse_points = $points;
554 $ipaddress = gethostbyname($sourceip);
555 //echo " IP address for $sourceip is $ipaddress.\n";
556 $sourceip = $ipaddress;
558 $abres = $dbms->query("SELECT * FROM object_abuse WHERE objectid='$objectid' AND source='$sourceip'");
560 if (pg_numrows($abres) == 0 && $points > 0)
562 //echo "$sourceip is new.\n";
563 $dbms->query("INSERT INTO object_abuse VALUES ('$objectid', '$sourceip', '$points', '', NOW())");
564 $dbms->query("INSERT INTO log_abuse VALUES ('$logid', '$objectid', '$sourceip')");
566 else if (pg_numrows($abres) != 0)
568 $abuse = $dbms->fetch_object($abres, 0);
569 if ($abuse->status == '' || $abuse->status == 'dropped')
571 $abuse_points = $abuse->nr_abuses + $points;
572 if ($abuse_points < 0)
576 //echo $sourceip . " will get " . $abuse_points . " abuse points, ";
577 //echo "Status was " . $abuse->status . "\n";
578 $dbms->query("UPDATE object_abuse SET nr_abuses='$abuse_points'" .
579 ", last_change=NOW() WHERE objectid='$objectid' AND source='$sourceip'");
583 $dbms->query("INSERT INTO log_abuse VALUES ('$logid', '$objectid', '$sourceip')");
585 if ($abuse_points >= 32)
587 //echo " BLOCK IP adrress $sourceip on the firewall.\n";
588 $dbms->query("UPDATE object_abuse SET status='dropped'" .
589 " WHERE objectid='$objectid' AND source='$sourceip'");
594 return $abuse_points;
599 * Service_check - Check the log entries if there are any unknown
603 function service_check()
607 $unknown_notification = array();
608 $unused_notification = array();
611 // How far did we get last time ?
613 $lastlogres = $dbms->query("SELECT setting_value FROM db_value
614 WHERE setting = 'log_servicecheck'");
616 if ($dbms->num_rows($lastlogres) == 1)
618 $last_log = $dbms->Field($lastlogres, 0, 'setting_value');
622 $dbms->query("INSERT INTO db_value (setting, setting_value)
623 VALUES ('log_servicecheck', '0')");
626 echo "Running service check from log id $last_log.\n";
627 // Query the log-table
629 $log_limit = $last_log + BATCHSIZE;
630 $qry = "SELECT logid, objectid, servicecode FROM log
631 WHERE logid > CAST(".$last_log." AS BIGINT) AND logid <= $log_limit
633 $log_res = $dbms->query($qry);
634 //$log_res = $dbms->query("SELECT logid, objectid, servicecode,rawdata FROM log");
636 for ($log_row = 0; $log_row < $dbms->num_rows($log_res); $log_row++)
638 $log_entry = $dbms->fetch_object($log_res, $log_row);
639 $last_log = $log_entry->logid;
641 // Check if the service is used on the object.
643 $qry = "SELECT * FROM object_service WHERE objectid='";
644 $qry .= $log_entry->objectid . "' AND servicecode='";
645 $qry .= $log_entry->servicecode . "'";
647 $os_res = $dbms->query($qry);
648 if ($dbms->num_rows($os_res) == 0)
650 // Service is not found for the object, check if the service
653 $qry = "SELECT * FROM service WHERE servicecode='";
654 $qry .= $log_entry->servicecode . "'";
656 if ($dbms->num_rows($dbms->query($qry)) == 0)
658 if (!isset($unknown_notification[$log_entry->objectid]))
660 $remark = "One or more log entries from a service that is not in the database";
661 $unknown_notification[$log_entry->objectid] =
662 $dbms->new_notification($log_entry->objectid, 'service unknown', $remark);
664 if (isset($unknown_notification[$log_entry->objectid]))
666 $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
667 $insertion .= $unknown_notification[$log_entry->objectid] . "', '";
668 $insertion .= $log_entry->logid . "')";
669 $dbms->query($insertion);
674 if (!isset($unused_notification[$log_entry->objectid]))
676 $remark = "One or more log entries from a service not running on this object";
677 $unused_notification[$log_entry->objectid] =
678 $dbms->new_notification($log_entry->objectid, 'service not used', $remark);
680 if (isset($unused_notification[$log_entry->objectid]))
682 $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
683 $insertion .= $unused_notification[$log_entry->objectid] . "', '";
684 $insertion .= $log_entry->logid . "')";
685 $dbms->query($insertion);
691 $qry = "UPDATE db_value SET setting_value = '"
692 . $last_log . "' WHERE setting = 'log_servicecheck'";
696 function find_notifications ()
700 * Do something with notification checks.
708 // Find checks that have to be executed.
709 $local_sql = "select * from notification_check where
710 age(last_execution) > time_between_executions";
711 $dbms->query($local_sql);
713 for ($i=0; $i<$dbms->num_rows(); $i++)
715 // A check has been found that has to be executed
721 * find open notifications and send an email to the object's users.
724 function mail_notifications ()
728 $notifres = $dbms->query("SELECT notificationid, objectid, type_of_issueid FROM notification
729 WHERE statuscode != 'cls'");
731 for ($notifrow = 0; $notifrow < pg_numrows($notifres); $notifrow++)
733 $notification = pg_fetch_object($notifres, $notifrow);
735 $issue = pg_fetch_object($dbms->query("SELECT description FROM type_of_issue
736 WHERE type_of_issueid='" . $notification->type_of_issueid . "'"), 0);
737 echo "Mailing Notification for object id " . $notification->objectid . "\n";
738 $object = pg_fetch_object($dbms->query("SELECT objectname FROM object
739 WHERE objectid='" . $notification->objectid ."'"), 0);
741 $users = $dbms->query("SELECT username FROM object_user WHERE objectid='" . $notification->objectid . "'");
743 for ($userrow = 0; $userrow < pg_numrows($users); $userrow++)
745 $objusr = pg_fetch_object($users, $userrow);
746 $usr = pg_fetch_object($dbms->query("SELECT email FROM usr
747 WHERE username='" . $objusr->username . "'"), 0);
749 $message = "Notification " . $notification->notificationid . ": " . $issue->description;
750 $message .= " for object " . $object->objectname . "\n";
752 mail($usr->email, "GnuCoMo Notification", $message);
758 * The 'command' may contain positional parameters such as '$1' and '$3',
759 * just like the shell. These parameters are replaced by content from
763 function expand_arguments($command, $args)
765 while (ereg('\$([0-9]+)', $command, $match))
768 if ($index >= count($args))
770 echo "Error: Argument $index not found for $command.\n";
771 $command = ereg_replace('\$' . $index, "", $command);
775 $command = ereg_replace('\$' . $index, $args[$index], $command);