-
Notifications
You must be signed in to change notification settings - Fork 74
/
functions.php
4222 lines (3710 loc) · 150 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?PHP
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/**
* General functions file
*/
// Force display errors to off
ini_set('display_errors', 0);
// Print errors in php log (normally apache errors log), but not notice logs
error_reporting(E_ALL ^ E_NOTICE);
// $PcreErrRuleId handling;
if (!isset($PcreErrRuleId) OR !preg_match('/^\d+$/', $PcreErrRuleId)) {
$PcreErrRuleId = 99999;
}
if (is_readable("../config.php")) {
require_once "config.php";
} else {
echo '<h1>Error!</h1><br /><p>The <b>config.php</b> file is missing or have wrong permission. Please check and run WAF-FLE again!</p>';
exit;
}
// Check if required directives are present
if (!isset($deleteLimit)) {
print "Your config.php has no \$deleteLimit directive defined.<br />\n";
print "Please define it to continue.";
exit;
}
if (!isset($SESSION_TIMEOUT)) {
print "Your config.php has no \$SESSION_TIMEOUT directive defined. <br />\n";
print "Please define it to continue.";
exit;
}
if (!isset($max_event_number)) {
print "Your config.php has no \$max_event_number directive defined. <br />\n";
print "Please define it to continue.";
exit;
}
if (isset($SETUP) AND $SETUP == true ){
header("Location: setup.php");
exit;
}
$waffleVersion = '0.6.4';
// Set PHP default timezone as system timezone, need to avoid warning messages in PHP 5.3+
date_default_timezone_set(@date_default_timezone_get());
/* Constants */
// Modsecurity severity levels
$severity[0] = "EMERGENCY";
$severity[1] = "ALERT";
$severity[2] = "CRITICAL";
$severity[3] = "ERROR";
$severity[4] = "WARNING";
$severity[5] = "NOTICE";
$severity[6] = "INFO";
$severity[7] = "DEBUG";
$severity[99] = "TRANSACTION"; // WAF-FLE way to classify events with no severity
// ModSecurity Rules Status (related to Alert Action)
// See http://sourceforge.net/apps/mediawiki/mod-security/index.php?title=Data_Format#Alert_Action_Description
$ActionStatus[0] = "Access denied with connection close"; // action: Drop
$ActionStatus[1] = "Access denied with code"; // action: Deny
$ActionStatus[2] = "Access denied with redirection"; // action: Redirect
$ActionStatus[3] = "Access denied using proxy to"; // action: Proxy
$ActionStatus[10] = "Access allowed"; // action: Allow
$ActionStatus[11] = "Access to phase allowed";
$ActionStatus[12] = "Access to request allowed";
$ActionStatus[13] = "Paused Access"; // action: Pause
$ActionStatus[14] = "Pausing transaction for"; // action: Pause
$ActionStatus[20] = "Warning"; // action: Pass or Detection Only
// timing scale definition
if ($timePreference == 'mili') {
$timingScale = 1000;
$timingScaleName = 'miliseconds';
$timingScaleAbrv = 'msec';
} else {
$timingScale = 1;
$timingScaleName = 'microseconds';
$timingScaleAbrv = 'µsec';
}
// Double check to APC
if ($APC_ON) {
$haveAPC = (extension_loaded('apc') && 1 ? true : false);
if ($haveAPC && ini_get('apc.enabled')) {
$APC_ON = true;
} else {
$APC_ON = false;
}
}
// Database connection using PDO
try {
$dbconn = new PDO('mysql:host='.$DB_HOST.';dbname='.$DATABASE, $DB_USER, $DB_PASS);
$dbconn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$dbconn->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "<h1>HTTP/1.1 500 Internal Server Error </h1><br />Error in database
connection, check if database is created, if permissions are correctly defined<br /><br />\n";
print "<b><font color=\"red\">If you are trying to install WAF-FLE, edit <i>config.php</i> and make \$SETUP \"true\"</font></b> <br /><br />";
print "Error: (insert events) Message: " . $e->getMessage() . "<br />\n";
if ($MLOG2WAFFLE_DEBUG OR $DEBUG) {
print "Error: (insert events) getTraceAsString: " . $e->getTraceAsString() . "<br />\n";
}
die();
}
// Check WAF-FLE vs. Database schema version
$sqlDatabaseVersion = 'SELECT `waffle_version` FROM `version` LIMIT 1';
try {
$checkVersion_sth = $dbconn->prepare($sqlDatabaseVersion);
// Execute the query
$checkVersion_sth->execute();
$dbSchema = $checkVersion_sth->fetch(PDO::FETCH_ASSOC);
$checkVersion_sth->closeCursor();
if ($dbSchema['waffle_version'] == '0.6.0') {
$dbSchema['waffle_version'] = '0.6.4';
}
if ($dbSchema['waffle_version'] != $waffleVersion) {
header ("Location: upgrade.php");
exit;
}
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (DatabaseVersion) Message: " . $e->getMessage() . "\n";
print "Error (DatabaseVersion) getTraceAsString: " . $e->getTraceAsString() . "\n";
}
die("Error in database query!");
}
// statistics functions
// Get events per sensor in a timeframe
function statsEventSensor()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
global $filterIndexHint;
$filterType = 'filter';
// Query for events
$selector = 'SELECT COUNT(events.sensor_id) AS sensor_count, events.sensor_id as sensor_id FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.sensor_id ORDER BY sensor_count DESC';
// Call superFilter to count filtered events
$statsEventSensor = superFilter($selector, $trailer, $filterType, FALSE);
$eventCount = count($statsEventSensor);
for ($a = 0; $a < $eventCount; ++$a) {
$sensor_name = getSensorName($statsEventSensor[$a]['sensor_id']);
$statsEventSensor[$a]['sensor_name'] = $sensor_name['name'];
$statsEventSensor[$a]['result'] = true ;
}
foreach ($statsEventSensor as $f_statusSensor) {
$f_statsEventSensorTotal = $f_statsEventSensorTotal + $f_statusSensor['sensor_count'];
}
$nextElement = count($statsEventSensor);
foreach ($statsEventSensor as $key => $value) {
$f_eventSensorPercent = round($value['sensor_count'] * 100 / $f_statsEventSensorTotal, 2);
$statsEventSensor[$key]['sensor_percent'] = $f_eventSensorPercent;
$value['sensor_percent'] = $f_eventSensorPercent;
if ($f_eventSensorPercent < 5 AND $nextElement > 7) { // make status less then 5% aggregated on 'others' when more that 7 sensors are in result
$others = $others + $value['sensor_count'];
$statsEventSensor[$nextElement]['sensor_count'] = $statsEventSensor[$nextElement]['sensor_count'] + $value['sensor_count'];
$statsEventSensor[$nextElement]['sensor_name'] = 'Others';
$statsEventSensor[$nextElement]['result'] = true;
$statsEventSensor[$nextElement]['sensor_percent'] = $statsEventSensor[$nextElement]['sensor_percent'] + $value['sensor_percent'];
unset($statsEventSensor[$key]);
}
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsEventSensor;
}
/**
* Get events in last $timeframe hours, grouping/counting in 15 min. steps.
*/
function statsEvents()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
global $filterIndexHint;
$filterType = 'filter';
$startdate = $_SESSION[$filterType]['StDate'] . " " . $_SESSION[$filterType]['StTime'];
$enddate = $_SESSION[$filterType]['FnDate'] . " " . $_SESSION[$filterType]['FnTime'];
$startFilterTime = date("U", strtotime($startdate));
$endFilterTime = date("U", strtotime($enddate));
$deltaTime = ($endFilterTime - $startFilterTime + 1);
$labelStep = round($deltaTime / 10) . ' seconds';
if ($deltaTime <= 3600) { // <=1h
$step = 30; // 30 sec
$legend = '30 seconds';
$stepRate = floor($deltaTime / $step); // 1 point each 30 sec
} elseif ($deltaTime <= 7200) { // <=2h < 1h
$step = 60;
$legend = '1 minute';
$stepRate = floor($deltaTime / $step); // 1 point each 60 sec
} elseif ($deltaTime <= 21600) { // <=6h < 2h
$step = 120;
$legend = '2 minutes';
$stepRate = floor($deltaTime / $step); // 1 point each 120 sec
} elseif ($deltaTime <= 86400) { // <=24h < 6h
$step = 300;
$legend = '5 minutes';
$stepRate = floor($deltaTime / $step); // 1 point each 300 sec
} else { // > 24h
$stepRate = 288; // 288 points, not matter how many seconds
$step = floor($deltaTime / $stepRate);
$legend = round($step/60) . ' minutes';
}
// generate a syntethic array of values
for ( $a = 0; $a < $stepRate; ++$a) {
$statTime = date("Y-m-d H:i:s",floor(($startFilterTime + ($step * $a))/$step)*$step);
$statEvent_synthetic[$statTime]['block'] = 0;
$statEvent_synthetic[$statTime]['allow'] = 0;
$statEvent_synthetic[$statTime]['warning'] = 0;
}
// Query for events
$selector = 'SELECT events.a_timestamp as a_timestamp, COUNT(events.h_action_status = 20 OR NULL) AS warning, COUNT(events.h_action_status < 10 OR NULL) AS block, COUNT(events.h_action_status >= 10 AND events.h_action_status < 20 OR NULL) AS allow FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY (UNIX_TIMESTAMP(events.a_timestamp)) DIV :step';
$extraField = array('step' => $step);
// Call superFilter to count filtered events
$statsEvents = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
foreach($statsEvents as $key => $stat) {
$timestampFloored = floor(strtotime($stat['a_timestamp'])/$step)*$step;
$statsEventsTime[date("Y-m-d H:i:s", $timestampFloored)]['block'] = $stat['block'];
$statsEventsTime[date("Y-m-d H:i:s", $timestampFloored)]['allow'] = $stat['allow'];
$statsEventsTime[date("Y-m-d H:i:s", $timestampFloored)]['warning'] = $stat['warning'];
}
$statEventsComplete = array_multimerge($statEvent_synthetic, $statsEventsTime);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return array($step, $labelStep, $legend, $statEventsComplete);
}
function statsTopRules()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Check if join table are needed
if ((isset($_SESSION[$filterType]['ruleid']) AND !isset($_SESSION[$filterType]['Not_ruleid'])) OR isset($_SESSION[$filterType]['tag'])) {
$selector = 'SELECT COUNT( events_messages.h_message_ruleId ) AS rule_count, events_messages.h_message_ruleId AS message_ruleId FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
} else {
$selector = 'SELECT COUNT( events_messages.h_message_ruleId ) AS rule_count, events_messages.h_message_ruleId AS message_ruleId FROM date_range, events JOIN events_messages ON events.event_id = events_messages.event_id ';
}
// SQL Query trailer
$trailer = ' GROUP BY events_messages.h_message_ruleId ORDER BY rule_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopRules = superFilter($selector, $trailer, $filterType, FALSE);
$ruleCount = count($statsTopRules);
for ($a = 0; $a < $ruleCount; ++$a) {
$ruleName = getRuleName($statsTopRules[$a]['message_ruleId']);
$statsTopRules[$a]['message_ruleMsg'] = $ruleName['message_ruleMsg'];
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopRules;
}
function statsTopSources()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.a_client_ip ) AS source_count, INET_NTOA(events.a_client_ip) AS client_ip FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.a_client_ip ORDER BY source_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopSources = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopSources;
}
// Get the top web host (as in Host header)
function statsTopTargets()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.b_host ) AS host_count, events.b_host FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.b_host ORDER BY host_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopTargets = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopTargets;
}
// statsTopStatus
function statsTopStatus()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.f_status ) AS status_count, events.f_status AS status, http_code.msg AS msg FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
$selector = $selector . 'JOIN http_code ON http_code.code=events.f_status ';
// SQL Query trailer
$trailer = ' GROUP BY events.f_status ORDER BY status_count DESC LIMIT 0 , 10';
$extraField = array('step' => $step);
// Call superFilter to count filtered events
$statsTopStatus = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
foreach ($statsTopStatus as $f_status) {
$f_statusTotal = $f_statusTotal + $f_status['status_count'];
}
// make status less then 5% aggregated on 'others'
$nextElement = count($statsTopStatus);
foreach ($statsTopStatus as $key => $value) {
$f_statusPercent = round($value['status_count'] * 100 / $f_statusTotal, 2);
$statsTopStatus[$key]['status_percent'] = $f_statusPercent;
$value['status_percent'] = $f_eventSensorPercent;
if ($f_statusPercent < 10) {
$others = $others + $value['status_count'];
$statsTopStatus[$nextElement]['status_count'] = $statsTopStatus[$nextElement]['status_count'] + $value['status_count'];
$statsTopStatus[$nextElement]['status'] = '';
$statsTopStatus[$nextElement]['msg'] = 'Others';
$statsTopStatus[$nextElement]['status_percent'] = $statsTopStatus[$nextElement]['status_percent'] + $value['status_percent'];
unset($statsTopStatus[$key]);
}
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopStatus;
}
// statsTopSeverity
function statsTopSeverity()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
$selector = 'SELECT COUNT( events.h_severity ) AS severity_count, events.h_severity AS severity FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
$selector = $selector . ' JOIN http_code ON http_code.code=events.f_status ';
// SQL Query trailer
$trailer = ' GROUP BY events.h_severity ORDER BY severity_count DESC LIMIT 0 , 10';
$extraField = array('step' => $step);
// Call superFilter to count filtered events
$statsTopSeverity = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
foreach ($statsTopSeverity as $h_severity) {
$h_severityTotal = $h_severityTotal + $h_severity['severity_count'];
}
// make status less then 5% aggregated on 'others'
$nextElement = count($statsTopSeverity);
foreach ($statsTopSeverity as $key => $value) {
$h_severityPercent = round($value['severity_count'] * 100 / $h_severityTotal, 2);
$statsTopSeverity[$key]['severity_percent'] = $h_severityPercent;
$value['severity_percent'] = $h_severityPercent;
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopSeverity;
}
function statsTopPath()
{
global $DEBUG;
global $filterIndexHint;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.b_path ) AS b_path_count, b_path FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.b_path ORDER BY b_path_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopPath = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopPath;
}
function statsTopCC()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.a_client_ip_cc ) AS client_cc_count, a_client_ip_cc AS client_cc FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.a_client_ip_cc ORDER BY client_cc_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopSources = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopSources;
}
function statsTopASN()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
$filterType = 'filter';
global $filterIndexHint;
// Query for events
$selector = 'SELECT COUNT( events.a_client_ip_asn ) AS client_ASN_count, a_client_ip_asn AS client_ASN FROM date_range, events ';
if (count($_SESSION['filterIndexHint']) > 0 and $_SESSION['filterIndexHint'] != false) {
$selector = $selector . 'USE INDEX '.$filterIndexHint;
}
// SQL Query trailer
$trailer = ' GROUP BY events.a_client_ip_asn ORDER BY client_ASN_count DESC LIMIT 0 , 10';
// Call superFilter to count filtered events
$statsTopSources = superFilter($selector, $trailer, $filterType, FALSE, $extraField);
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $statsTopSources;
}
function array_multimerge ($array1, $array2)
{
if (is_array($array2) && count($array2)) {
foreach ($array2 as $k => $v) {
if (is_array($v) && count($v)) {
$array1[$k] = array_multimerge($array1[$k], $v);
} else {
$array1[$k] = $v;
}
}
}
return $array1;
}
// checkUser: validate user against userbase or external userbase
function checkUser($username, $password)
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
/* prepare statement using PDO*/
global $dbconn;
$sha1Password = sha1($password);
$sqlcheckUser = 'SELECT `user_id`, `username`, `email` FROM users WHERE username = :username AND password = :password';
if ($DEBUG) {
$debugInfo[__FUNCTION__][$debugCount]['query'] = $sqlcheckUser;
}
try {
$query_sth = $dbconn->prepare($sqlcheckUser);
$query_sth->bindParam(":username", $username);
$query_sth->bindParam(":password", $sha1Password);
// Execute the query
$query_sth->execute();
$checkUser = $query_sth->fetchAll(PDO::FETCH_ASSOC);
$userCount = count($checkUser);
if ($userCount == 1) {
$checkUser[0]['result'] = TRUE;
} else {
$checkUser[0]['result'] = FALSE;
}
if ($checkUser[0]['user_id'] == "1" AND $password == "admin") {
$checkUser[0]['changePass'] = true;
}
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $checkUser;
}
// getTagID Get Tag ID based on tag string
function getTagID($tag_string)
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
/* prepare statement using PDO*/
global $dbconn;
global $APC_ON;
global $CACHE_TIMEOUT;
if ($APC_ON AND ($tag_id = apc_fetch('tag_'.sha1($tag_string)))) {
$tag_id = $tag_id;
} else {
$sqlGetTagId = '
SELECT `tag_id`, `tag_name` FROM `tags`
UNION
SELECT `tag_id`, `tag_name` FROM `tags_custom`
';
if ($DEBUG) {
$debugInfo[__FUNCTION__][$debugCount]['query'] = $sqlGetTagId;
}
try {
$query_sth = $dbconn->prepare($sqlGetTagId);
// Execute the query
$query_sth->execute();
$GetTagId = $query_sth->fetchAll(PDO::FETCH_ASSOC);
$tagCount = $query_sth->rowCount();
$queryStatus = $query_sth->errorCode();
if ($queryStatus != 0 OR $tagCount == 0) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
global $MLOG2WAFFLE_DEBUG;
if ($MLOG2WAFFLE_DEBUG) {
$arr = $query_sth->errorInfo();
print_r($arr);
}
exit();
} else {
foreach ($GetTagId as $Tag) {
if ($tag_string == $Tag['tag_name']) {
$tag_id = $Tag['tag_id'];
}
if ($APC_ON) {
apc_store('tag_'.sha1($Tag['tag_name']), $Tag['tag_id'], $CACHE_TIMEOUT);
}
}
// if no tag found, a custom tag will be created on tags_custom table
if (!isset($tag_id) OR $tag_id == "") {
$sqlNewTagId = 'INSERT INTO `tags_custom` (`tag_name`, `tag_title`) VALUES(:TagName, :TagTitle)';
if ($DEBUG) {
$debugInfo[__FUNCTION__][$debugCount]['query'] = $sqlNewTagId;
}
try {
$queryNewTag_sth = $dbconn->prepare($sqlNewTagId);
$queryNewTag_sth->bindParam(":TagName", $tag_string);
$queryNewTag_sth->bindParam(":TagTitle", $tag_string);
$queryNewTag_sth->execute();
$tag_id = $dbconn->lastInsertId();
$insertStatus = $queryNewTag_sth->errorCode();
$arr = $queryNewTag_sth->errorInfo();
if ($APC_ON) {
apc_store('tag_'.sha1($tag_name), $tag_id, $CACHE_TIMEOUT);
}
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
global $MLOG2WAFFLE_DEBUG;
if ($MLOG2WAFFLE_DEBUG OR $DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
}
}
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
global $MLOG2WAFFLE_DEBUG;
if ($MLOG2WAFFLE_DEBUG OR $DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $tag_id;
}
// getTagName Get Tag Name based on tag id
function getTagName($tag_id)
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
/* prepare statement using PDO*/
global $dbconn;
global $APC_ON;
global $CACHE_TIMEOUT;
if ($APC_ON AND ($tag_name = apc_fetch('tag_'.$tag_id))) {
$tag_name = $tag_name;
} else {
$sqlGetTagName = '
SELECT `tag_id`, `tag_name` FROM `tags`
UNION
SELECT `tag_id`, `tag_name` FROM `tags_custom`
';
if ($DEBUG) {
$debugInfo[__FUNCTION__][$debugCount]['query'] = $sqlGetTagName;
}
try {
$query_sth = $dbconn->prepare($sqlGetTagName);
$query_sth->bindParam(":tag_id", $tag_id);
$query_sth->bindParam(":tag_idCustom", $tag_id);
// Execute the query
$query_sth->execute();
$GetTagName = $query_sth->fetchAll(PDO::FETCH_ASSOC);
foreach ($GetTagName as $Tag) {
if ($tag_id == $Tag['tag_id']) {
$tag_name = $Tag['tag_name'];
}
if ($APC_ON) {
// apc_store('tag_'.$tag_id, $Tag['tag_name'], $CACHE_TIMEOUT);
print "";
}
}
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $tag_name;
}
// getTags Fetch all Tag
function getTags()
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
/* prepare statement using PDO*/
global $dbconn;
global $APC_ON;
global $CACHE_TIMEOUT;
if ($APC_ON AND ($tags = apc_fetch('tags'))) {
$tags = $tags;
} else {
$sqlGetTags = ' SELECT `tag_id`, `tag_name` FROM `tags`
UNION
SELECT `tag_id`, `tag_name` FROM `tags_custom`
ORDER BY tag_name';
if ($DEBUG) {
$debugInfo[__FUNCTION__][$debugCount]['query'] = $sqlGetTags;
}
try {
$query_sth = $dbconn->prepare($sqlGetTags);
// Execute the query
$query_sth->execute();
$tagsList = $query_sth->fetchAll(PDO::FETCH_ASSOC);
$queryStatus = $query_sth->errorCode();
/*
if ($APC_ON) {
// apc_store('tags', $tagsList, $CACHE_TIMEOUT);
print "";
}
*/
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
}
if ($DEBUG) {
$stoptime = microtime(true);
$timespend = $stoptime - $starttime;
$debugInfo[__FUNCTION__][$debugCount]['time'] = $timespend;
}
return $tagsList;
}
// process all filter operation, receive a sql selector and trailer, the type of filter (filter, delete, fp), if should count events, and some extra fields
function superFilter($selector, $trailer, $filterType, $count = FALSE, $extraField = array())
{
global $DEBUG;
if ($DEBUG) {
global $debugInfo;
$debugCount = count($debugInfo[__FUNCTION__]);
$starttime = microtime(true);
}
/* prepare statement using PDO*/
global $dbconn;
// Start filter composition
$sql = $selector;
if (isset($_SESSION[$filterType]['StDate']) AND isset($_SESSION[$filterType]['StTime']) AND isset($_SESSION[$filterType]['FnDate']) AND isset($_SESSION[$filterType]['FnTime'])) {
global $tempDate;
if (!$tempDate) {
// Create a temp table with date range
$sqlCreateDateRangeTempTable='CREATE TEMPORARY TABLE IF NOT EXISTS `date_range` (`a_date` DATE NOT NULL)';
try {
$sthTempTable = $dbconn->prepare($sqlCreateDateRangeTempTable);
$sthTempTable->execute();
$insertTempDateRange = 'INSERT INTO `date_range`
(`a_date`) SELECT DISTINCT a_date FROM events WHERE a_date BETWEEN :startDate AND :stopDate ORDER BY a_date DESC';
$st_dateRange = $dbconn->prepare($insertTempDateRange);
try {
$st_dateRange->bindParam(":startDate", $_SESSION[$filterType]['StDate']);
$st_dateRange->bindParam(":stopDate", $_SESSION[$filterType]['FnDate']);
$st_dateRange->execute();
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
$tempDate = true;
} catch (PDOException $e) {
header("HTTP/1.1 500 Internal Server Error");
header("Status: 500");
print "HTTP/1.1 500 Internal Server Error \n";
if ($DEBUG) {
print "Error (".__FUNCTION__.") Message: " . $e->getMessage() . "\n";
print "Error (".__FUNCTION__.") getTraceAsString: " . $e->getTraceAsString() . "\n";
}
exit();
}
}
// workaround for mysql limitation of only one access to temp table per query;
global $tempDatetag;
if (!$tempDatetag) {
// Create a temp table with date range
$sqlCreateDateRangeTagTempTable='CREATE TEMPORARY TABLE IF NOT EXISTS `date_rangeMsg` (`a_date` DATE NOT NULL)';
try {
$sthTempTableTag = $dbconn->prepare($sqlCreateDateRangeTagTempTable);
$sthTempTableTag->execute();
$insertTempDateRangeTag = 'INSERT INTO `date_rangeMsg` (`a_date`) SELECT DISTINCT a_date FROM events WHERE a_date BETWEEN :startDate AND :stopDate ORDER BY a_date DESC';
$st_dateRangeTag = $dbconn->prepare($insertTempDateRangeTag);
try {
$st_dateRangeTag->bindParam(":startDate", $_SESSION[$filterType]['StDate']);
$st_dateRangeTag->bindParam(":stopDate", $_SESSION[$filterType]['FnDate']);
$st_dateRangeTag->execute();
} catch (PDOException $e) {