-
Notifications
You must be signed in to change notification settings - Fork 0
/
logs.cgi
executable file
·2053 lines (1857 loc) · 74.6 KB
/
logs.cgi
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
#!/usr/bin/perl
# logs.cgi
print DEBUGLOG "beginning processing logs.cgi\n" if $debug;
###########################################################################
#
# Program : Log Analyzer for DansGuardian
# Author : Jimmy Myrick (jmyrick@cherokeek12.org)
# Version : 1.0
# Released : October 10, 2005
#
# 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.
#
#
# If you like it and want to send me something, that's ok too.
# How about a gift certificate to amazon.com or a donation to DansGuardian
# on my behalf?
#
###########################################################################
# by declaring all the globals we'll reference (including some in our own
# libraries)_before_ pulling in libraries and adding the 'use ...' _after_
# pulling in libraries, we can 'use strict' for our own code without
# generating any messages about the less-than-clean code in the very old
# Webmin libraries themselves
our (%text, %access, %config, %in, $module_name, $modulever, $moduleinfo);
our ($debug, $dg_version, $current_lang, $module_config_directory);
##########################################################################
# declare global variables
##########################################################################
our ($parseactionsandreasonregexp, $parsetoeolregexp, $parsetoeolregexpjr);
######## settings
our ($sSD, $sED, $sSDY, $sSDM, $sSDD, $sEDY, $sEDM, $sEDD);
our ($sL, $sZ, $sD, $sR, $sG, $sP);
our ($sSumExc, $sSumDen, $sSumAlw, $sSumCnt);
our ($sA, $sA2, $sSN, $sSD);
our ($sRC, $sRM, $sRG);
our ($sCAT, $sMIME, $sGRP, $sIP, $sUN, $sWGHT, $sAGT);
our ($sWD, $sWN);
our ($sTITLE); # <-- only on batch reports (in fact use "defined $sTITLE" as a switch)
######## "global" variables that are part of the UI
our ($msg);
our ($line);
########
our ($dgDate);
######## "global" variables used to pass information between large block subroutines
our ($linesRead, $allowedTotal, $deniedTotal, $exceptionTotal, $grandTotal);
our ($noaddr, $nouser, $userisaddr);
our (@files, $file);
######## all these are globally available resources (they're in a subroutine only for coding clarity) #####
our (%order2title, %order2varname, %order2source, %what2subtitle, %what2varname, %what2option);
our (%reasons_number2text, %reasons_text2number);
our (%reasonMessageNumbers, %regexpreasonMessageNumbers);
our (%phrasereasonMessageNumbers, %blanketreasonMessageNumbers, %exceptionreasonMessageNumbers);
our (%regexpreasons_number2text, %regexpreasons_text2number);
our (%phrasereasons_number2text, %phrasereasons_text2number);
our (%blanketreasons_number2text, %blanketreasons_text2number);
our (%exceptionreasons_number2text, %exceptionreasons_text2number);
######## "global" variables freely used by large block subroutines
our ($hashname, $separator);
our ($order, $source, $varname);
our ($modpattern, $modurl);
our ($majormime, $prevmajormime);
our ($substring);
our ($number);
######## "global" variables used to pass around parts of log entries
our ($date, $time, $ip, $user);
our ($url, $baseurl, $queryurl, $protocol, $allbutprotocol, $urlpath, $sitename, $protocolandsitename);
our ($toeol, $cl1, $cl2, $method, $retcode, $size, $clientname);
our ($category, @categoryeach, $weight, $filtergroup, $filtergroupnum, $mimetype, $browseragent);
our ($action, $otheractions, $reason, $reasonjr, $subreason, $subreasonjr, $privatereason);
######## counters
our (%filtergroups, $listchanged_filtergroups);
our (%mimetypes, $listchanged_mimetypes);
our (%categories, $listchanged_categories);
######## temps
our ($onecategory, $categorytemp);
######## initialized counters
our $formaterrcount = 0;
our $languageerrcount = 0;
our $formaterrcountthislogfile = 0;
# Begin Webmin header stuff (also note footer at bottom of script)
require './dansguardian-lib.pl';
use POSIX;
use warnings;
use strict qw(subs vars);
our $pagename = $text{'index_logs'};
# finish transferring anything set by the calling URL from %in to our vars
while (my ($name, $value) = each %in) {
$$name = $value;
}
&webminheader();
# give checkboxes a definite value if coming from menu
# (oddity of HTML, checkboxes are just plain absent if off)
&setCheckboxes();
# give a default value to anything that's not set yet
&setDefaults();
# standardize variables
&canonicalizeVars();
# Check user acl
&checkmodauth('logs');
# End of Webmin header stuff
###########################################################################
#
# Change to point to your DansGuardian log directory
#
###########################################################################
# modified to use a setting from our module-config
our $logdir = &canonicalizefilepath($config{'log_path'});
###########################################################################
#
# Log filename. Change this to match the prefix of your log files
# This defaults to access.log and should not have to be modified.
#
# Any logfiles in $logdir that match the prefix $logfile and are gzip'ed
# with a .gz extension will also be read. The results will be printed in
# reverse chronological filename order.
#
# Example:
# If you have the files: access.log access.log.0.gz access.log.1.gz
# where they are newest to oldest, then any matches in
# access.log.1.gz will be printed first, followed by access.log.0.gz
# and then access.log
#
# No sorting is done by the program and the results are displayed in logfile
# order. If your results are out of sequence, check the filename/dates
# to be sure they are compressed and rotated properly. If you use
# the FreeBSD newsyslog.conf to rotate your logs, this will not be a
# problem.
#
###########################################################################
# essentially hard-coded, as there is no provision for changing this
our $logfile = 'access.log';
###########################################################################
#
# If you need the perl modules below, download and untar them to a directory.
# Then cd to the directory and enter the commands:
# perl Makefile.PL; make; make test; make install
#
# This is needed to do gzip'ed log files on the fly
#
# If you need more instructions,
# go here: http://www.cpan.org/modules/INSTALL.html
#
# Get it here: http://www.cpan.org/authors/id/PMQS/Compress-Zlib-1.16.tar.gz
#
###########################################################################
# essentially hard-coded, as there is no provision for changing this
use Compress::Zlib;
###########################################################################
#
# This should determine where the program is called from automagically.
# If not, uncomment the first line, change to your server name/path and
# comment the second line. You can use Apache restrictions to block
# access to this file if desired.
#
###########################################################################
# changed to work properly for log analysis embedded in Webmin rather than standalone
#$cgipath = 'http://your.server.com/cgi-bin/dglog/dglog.pl';
our $cgipath = $ENV{SCRIPT_NAME};
(our $modulenameself = $cgipath) =~ s{^.*/([^/]*)$}{$1};
###########################################################################
#
# SHOULDN'T HAVE TO MODIFY ANYTHING BELOW THIS LINE
#
###########################################################################
if (&cputoobusy()) {
print "<p><span style='color: brown'>$text{'error_verybusy'}</span><br>\n";
}
###########################################################################
# check prerequisites and complain about any that aren't found
###########################################################################
if (($config{'messages_path'} =~ m/follow/i) || ($config{'log_format'} =~ m/follow/i)) {
if (! &checkdgconf) {
print "<span style='color: brown'>$text{'error_confnotfound'}<br>$text{'index_location'}: " . &group2conffilepath(0) . "</span><p>\n";
}
}
our $logfileformat;
our $whereisit = $config{'log_format'};
if ((! defined $whereisit) || ($whereisit eq '') || ($whereisit =~ m/follow/i)) {
$logfileformat = &getconfigvalue('logfileformat');
} else {
$logfileformat = $whereisit;
}
if (! (($logfileformat == 1) || ($logfileformat == 2) || ($logfileformat == 4))) {
print "<span style='color: brown'>$text{'error_logfileformat_notsupp'}<br>$text{'view_logfileformat'}: $logfileformat</span><p>\n";
&webminfooterandexit();
}
##########################################################################
# begin processing request
##########################################################################
# set up housekeeping
&initVars();
# get our persistent data that drives our configuration
&unPersistData();
# define "constants"
&initConstants();
# define 'today'
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon = $mon + 1; # mon starts at 0
$year = $year + 1900; # year needs 1900 added
if ($a eq 'i') { # Inquiry into logs
# check some input variables for validity
# if anything invalid is found, reprint the menu (but with current values) then exit
&validateVars();
# Need a few global variables to keep from passing back and forth a bunch
$linesRead = 0;
$allowedTotal = 0;
$deniedTotal = 0;
$exceptionTotal = 0;
$grandTotal = 0;
# and need some global counters
$noaddr = 0;
$nouser = 0;
$userisaddr = 0;
# do the work
&searchLog();
} elsif ($a eq 'd') {
# alternate inquiry into logs, settings from %in (batch or detail) rather than menu
# typically used for "details" (hence the acronym)
# do not validateVars(), as we couldn't get here if anything was invalid
# do the work it would do though
&dateParts2wholeDates;
# Need a few global variables to keep from passing back and forth a bunch
$linesRead = 0;
$grandTotal = 0;
# and need some global counters
$noaddr = 0;
$nouser = 0;
$userisaddr = 0;
# do the work
&searchLog();
}
else {
# maybe a='m', or maybe a='', or maybe a is not set
&printMenu();
}
# save our persistent information that drives our configuration
&persistData();
# Webmin footer
&webminfooterandexit();
# all done!
###########################################################################
#
# SUBROUTINES FOR MAJOR PORTIONS OF PROCESSING
#
###########################################################################
#############
sub searchLog
#############
{
my $first = 1;
#&printHeader(); # standalone, but don't do this when embedded in Webmin
opendir(D, $logdir);
@files = grep {/^$logfile/} readdir(D);
# the sort below puts the files in a consistent (and hopefully chronological) order
@files = reverse sort partialnumeric @files;
closedir(D);
print "<small>\n";
# list all the files we're going to analyze (possibly including compressed ones)
$first = 1;
foreach $file (@files) {
next if (($file =~ m/\.gz$/) && ($sZ eq 'off'));
if ($first) {
print "<span style='color: darkred; font-size: smaller'>$text{'view_whichlogfiles'} $logdir: $file";
$first = 0;
} else {
print ", $file";
}
}
print "</span><br>\n" if !$first;
# go through all files and list compressed ones if we're not going to analyze them
$first = 1;
foreach $file (@files) {
if ($file =~ m/\.gz$/) {
if ($sZ eq 'off') {
if ($first) {
print "<span style='color: brown; font-size: smaller'>$text{'error_lognotcompressed'} $logdir: $file";
$first = 0;
} else {
print ", $file";
}
next;
}
}
}
print "</span><br>\n" if !$first;
# print the standard filter-settings heading
print "<br>\n";
&printFilter();
# go through contents of all files and print detail and/or count for summary
if ($sD eq "on") {
print "<hr style='height: 3'><small><i>\n";
print "$text{'view_detailcaption1'}<br>\n";
print "$text{'view_detailcaption2'}<br>\n" if $sG eq 'on';
print "<a href='#'>" if $sL eq 'on';
print "$text{'view_detailcaption3'}";
print "</a>" if $sL eq 'on';
print "<br>\n";
print "<span style='color: #686828'>$text{'view_detailcaption4a'}</span><br>\n" if $sR eq 'on';
print "<span style='color: #686828'>$text{'view_detailcaption4b'}</span><br>\n" if $sP eq 'on';
print "<span style='color: red'>$text{'view_detailcaption5'}</span><br>\n";
print "</i></small>\n";
}
foreach $file (@files) {
$formaterrcountthislogfile = 0;
our $logdirfile = "$logdir/$file";
if ($file =~ m/\.gz$/) {
if ($sZ eq 'on') {
my $gz = gzopen($logdirfile,'r');
if (!$gz) {
$msg = "$text{'view_err_cannotopen'} ($logdirfile)<p>$text{'view_err_fixperms'}";
&printMenu(); # try again
&webminfooterandexit();
}
while ($gz->gzreadline($line)) {
&checkLine($line);
}
$gz->gzclose;
}
}
else {
unless (open(F,$logdirfile)) {
$msg = "$text{'view_err_cannotopen'} ($logdirfile)<p>$text{'view_err_fixperms'}";
&printMenu(); # try again
&webminfooterandexit();
}
while ($line = <F>) {
&checkLine($line);
}
close(F);
}
}
our $messages = 0;
if (($formaterrcount > ($linesRead * 0.001)) && ($linesRead > 3)) {
print "<br><span style='color: brown'>$text{'error_warning'} $text{'view_err_notparse'}: $formaterrcount - $text{'view_err_logformat'}</span>\n";
++$messages;
}
if (($languageerrcount > ($linesRead * 0.001)) && ($linesRead > 3)) {
print "<br><span style='color: brown'>$text{'error_warning'} $text{'view_err_notunderstood'}: $languageerrcount - $text{'view_err_language'}</span>\n";
++$messages;
}
if ((($noaddr - $formaterrcount) > ($linesRead * 0.35)) && ($linesRead > 3)) {
print "<br><span style='color: brown'>$text{'error_noaddr'}</span>\n";
++$messages;
}
if ((($nouser - $formaterrcount) > ($linesRead * 0.35)) && ($linesRead > 3)) {
print "<br><span style='color: brown'>$text{'error_nouser'}</span>\n";
++$messages;
}
if ((($userisaddr - $formaterrcount) > ($linesRead * 0.35)) && ($linesRead > 3)) {
print "<br><span style='color: brown'>$text{'error_userisaddr'}</span>\n";
++$messages;
}
print "<br><br>\n" if $messages;
if ($grandTotal > 0) {
if ($sD eq 'on') {
print "<hr style='height: 3'>\n";
if (($sSumExc eq 'on') || ($sSumDen eq 'on') || ($sSumAlw eq 'on')) { print "<br><br>\n"; }
}
print "<div style='max-width: 1600px'><!-- begin summary tables, not off right edge of screen -->\n";
my $first = 1;
if ($sSumExc eq "on") {
if ($first) { $first = 0; } else { print "<br><br>\n"; }
print "<center><span style='padding: 1ex; border: 1px greenyellow solid; font-size: larger; font-weight: 800'>" . uc($text{'view_exception'}) . ' ' . ucfirst($text{'view_summaries'}) . "</span></center><br><br>\n";
if ($exceptionTotal != 0) {
foreach my $order (keys %order2source) {
$hashname = "exception$order";
&showSummary($exceptionTotal,'exception',$sSumCnt,$order,%$hashname);
}
}
print "<br><hr style='height: 3'>\n";
}
if ($sSumDen eq "on") {
if ($first) { $first = 0; } else { print "<br><br>\n"; }
print "<center><span style='padding: 1ex; border: 1px greenyellow solid; font-size: larger; font-weight: 800'>" . uc($text{'view_denied'}) . ' ' . ucfirst($text{'view_summaries'}) . "</span></center><br><br>\n";
if ($deniedTotal != 0) {
foreach my $order (keys %order2source) {
$hashname = "denied$order";
&showSummary($deniedTotal,'denied',$sSumCnt,$order,%$hashname);
}
}
print "<br><hr style='height: 3'>\n";
}
if ($sSumAlw eq "on") {
if ($first) { $first = 0; } else { print "<br><br>\n"; }
print "<center><span style='padding: 1ex; border: 1px greenyellow solid; font-size: larger; font-weight: 800'>" . uc($text{'view_allowed'}) . ' ' . ucfirst($text{'view_summaries'}) . "</span></center><br><br>\n";
if ($allowedTotal != 0) {
foreach my $order (keys %order2source) {
$hashname = "allowed$order";
&showSummary($allowedTotal,'allowed',$sSumCnt,$order,%$hashname);
}
}
print "<br><hr style='height: 3'>\n";
}
print "</div><!-- end summary tables -->\n";
print "</small>\n";
} else {
print "</small>\n";
print "<br><center><span style='padding: 1ex; border: 1px orange solid; font-weight: 600'>$text{'view_no'}</span></center><br>\n";
}
&printTotals();
}
#################
sub initConstants
#################
{
# without some sort of "terminator" on the subreason, can get into doing an awful lot of
# backtracking with attendant horrid performance - performance problem is very noticeable
# test for "terminator" has to be a little careful though, stopping before GET and POST and
# CONNECT, but _not_ SSL - which can legitimately be in the middle of the subreason field
$parseactionsandreasonregexp = '(?:((?:\*(?!(?:DENIED|EXCEPTION))[A-Z]{6,}\* ?)*) )?(?:(\*(?:DENIED|EXCEPTION)\*) )?(?:([^.:* ][^.:]*)\.?(?::+ +((?:(?! [A-R][A-R][A-Z]).)+))? +)?';
$parsetoeolregexp = '^ *' . $parseactionsandreasonregexp . '([A-Z]{3,8}) (\d+) (?:(-?\d+) )?(?:((?:(?!\d\d? )[^ ]+ )*(?!\d\d? )[^ ]+) )?(?:([1-9]\d?) )?(?:(\d\d\d) )?(?:(-|[-\w]+\/[-_.\w]+) )?(?:(\w[-_\w]*(?:\.[-_\w]+)+) )?(?:([a-zA-Z][^ ]*) )?(?:([a-zA-Z][^ ]*\d.+ .*[^ ]) )? *$';
($parsetoeolregexpjr = $parsetoeolregexp) =~ s/\((?:[^()]*|[^()]*\([^()]*\)[^()]*|[^()]*\([^()]*\([^()]*\)[^()]*\)[^()]*)\)[^()]*$/()/;
}
#########################
sub clearRequestVariables
#########################
{
$cl1 = '';
$date = '';
$time = '';
$user = '';
$ip = '';
$url = '';
$protocol = '';
$allbutprotocol = '';
$baseurl = '';
$queryurl = '';
$sitename = '';
$protocolandsitename = '';
$urlpath = '';
$cl2 = '';
$otheractions = ''; # URLMOD, CONTENTMOD, SCANNED, INFECTED, etc.
$action = ''; # DENIED or EXCEPTION etc., if exists
$reason = ''; # Reason for 1 if exists
$reasonjr = ''; # Same except with trailing number deleted for standardized comparisons
$subreason = ''; # Detail supporting reason (maybe Regular Expression, maybe Phrases, maybe...)
$subreasonjr = ''; # Same except with leading number (score) deleted for better appearance
$method = ''; # method (GET or POST ...or maybe CONNECT)
$size = ''; # Size of webpage/document in bytes
$weight = ''; # Calculated weight/score
$category = ''; # Principal #listcategory's contributing to disposition of request
@categoryeach = (); # Individual #listcategory's
$filtergroupnum = ''; # 1-based number of filter group request was actually assigned to
$retcode = ''; # HTTP return code
$mimetype = ''; # MIME type of requested webpage/document according to remote server
$clientname = ''; # Client host name (reversed from IP above)
$filtergroup = ''; # Filter group name (assume no whitespace) (same as fg# above but more convenient)
$browseragent = ''; # browser Agent string (hard to parse because so variable)
}
######################
sub canonicalizereason
######################
{
my $reasonout = $_[0];
return '' if !$reasonout;
# probable future change: delete leading and trailing numbers too as they're always variable
$reasonout =~ s/^\s+//;
$reasonout =~ s/[\s:;.,!?]+$//;
return $reasonout;
}
#############
sub checkLine
#############
{
my ($line) = @_;
chomp $line;
$linesRead++;
# Print out a single character every bunch of log file lines read.
# Doing this keeps the browser connection alive and prevents browser timeouts
# (it also reassures the interactive human user that we're still doing something)
if (($linesRead % 2000) == 0) {
print defined $sTITLE ? ' ' : '.'; # use non-blank to reassure user if interactive
# (if batch use blank to avoid defacing report)
# (the performance is definitely not great, as we re-evaluate interactive/batch every
# time we print a character rather than doing it just once ...but who cares?)
}
&clearRequestVariables(); # this is probably unnecessary paranoia, but do it anyway
# it prevents errors with weird input, and it guarantees
# correct operation of some of the sub-parsing
goto qw(UNK NATIVE DELIM NOTSUPP DELIM)[$logfileformat];
UNK: {
$msg = "$text{'error_logfileformat_range'} ($logfileformat)";
&printMenu(); # try again
&webminfooterandexit();
}
NOTSUPP: {
print "<span style='color: brown'>$text{'error_logfileformat_notsupp'}<br>$text{'view_logfileformat'}: $logfileformat</span><p>\n";
&webminfooterandexit();
}
DELIM: {
$separator = ( qr//, qr//, qr/"\s*,\s*"/, qr//, qr/\t/ )[$logfileformat];
($cl1, $user, $ip, $url, $cl2, $method, $size, $weight, $category, $filtergroupnum, $retcode, $mimetype, $clientname, $filtergroup, $browseragent) = split $separator, $line, 15;
($date,$time) = ($cl1 =~ m/^\s*"?([^"\s]\S+)\s+(\S+[^"\s])"?\s*$/);
$cl2 =~ s/\s*$/ /; # add trailing space to be sure actions&reason regexp works right
($otheractions, $action, $reason, $subreason) = ($cl2 =~ m/^\s*$parseactionsandreasonregexp\s*$/);
$browseragent =~ s/\s+$//; # clean up by trimming right in case unclean parse
goto ENDCASE;
}
NATIVE: {
($date,$time,$user,$ip,$url,$toeol) = split(/ /,$line,6);
"" =~ /()()()()()()()()()()()()()()/; # preset all match vars to nothing just in case this doesn't pars
$toeol =~ s/\s*$/ /; # be sure there's a space tacked onto the end, makes our regexps much simpler
$toeol =~ s/\s{2,}/ /g; # reduce all multiple whitespace sequences to a single space each
# (arguably this loses a bit of information, but it makes our regexps _much_ simpler)
($otheractions, $action, $reason, $subreason, $method, $size, $weight, $category, $filtergroupnum, $retcode, $mimetype, $clientname, $filtergroup, $browseragent) = ($toeol =~ m/$parsetoeolregexp/);
# if parse failure, try again without "agent string" & end anchor ($browseragentstring will be blank)
($otheractions, $action, $reason, $subreason, $method, $size, $weight, $category, $filtergroupnum, $retcode, $mimetype, $clientname, $filtergroup, $browseragent) = ($toeol =~ m/$parsetoeolregexpjr/) if (!$otheractions && !$action && !$reason && !$subreason && !$method);
goto ENDCASE;
}
# different parsing options all come back together here - we're back to common code
ENDCASE:
# finish subsplitting a few more things
if ($url) {
# (note assumption variables are initially empty strings)
($protocol, $allbutprotocol) = ($url =~ m{(\w+)://+(.*)$});
$protocol = '' if !$protocol;
$allbutprotocol = '' if !$allbutprotocol;
($baseurl, $queryurl) = split /\?/, $allbutprotocol, 2;
$baseurl = '' if !$baseurl;
$queryurl = '' if !$queryurl;
($sitename, $urlpath) = ($baseurl =~ m{^(?:([^/:]+)(?::\d+)?|\w)(?:/+(.*))?$});
$sitename = '' if !$sitename;
$urlpath = '' if !$urlpath;
$protocolandsitename = "$protocol://$sitename";
# protocol part of url (HTTP, FTP, etc.)
# baseurl is part without http:// or ftp:// and without the query part
# sitename is just the part of the baseurl before the first '/'
# urlpath is the part after the first '/' and before the '?'
}
@categoryeach = split(/\s*,\s*/, $category) if $category;
# (note assumption that @categoryeach is initially empty)
map s/^\((.*)\)$/$1/, @categoryeach;
# do some modifications to make the data more friendly for us even if logged weirdly
if (!$action && exists $exceptionreasons_text2number{&canonicalizereason($reason)}) {
# may not be flagged if logexceptionhits=1 in dansguardian.conf, make it seem as though logexceptionhits=2
$action = '*EXCEPTION*';
}
#
if (exists $blanketreasons_text2number{&canonicalizereason($subreason)}) {
# "promote" canonicalized blanket reasons to full reason
$subreasonjr = &canonicalizereason($subreason);
$reasonjr = $subreasonjr;
} else {
# calculate modified versions of a couple variables to make our comparisons easier
# (note these assume reasonjr and subreasonjr are initially empty strings '')
($reasonjr = $reason) =~ s/\s+\d+\s*$// if $reason; # canonicalize for comparisons (remove 'naughtynesslimit')
($subreasonjr = $subreason) =~ s/^\s*\d+\s+// if $subreason; # remove score repeat to improve display
}
#following line useful for debugging, would delete it except too much detailed typing
#print DEBUGLOG "line: [$line] (toeol: [$toeol]) --parsed to: date=$date, time=$time, user=$user, ip=$ip, url=$url(protocol=$protocol, allbutprotocol=$allbutprotocol, protocolandsitename=$protocolandsitename, baseurl=$baseurl, sitename=$sitename, urlpath=$urlpath, queryurl=$queryurl), otheractions=$otheractions, action=$action, reason=$reason (reasonjr=$reasonjr), subreason=$subreason (subreasonjr=$subreasonjr), method=$method, size=$size, weight=$weight, category=$category (categoryeach=@categoryeach), filtergroupnum=$filtergroupnum, retcode=$retcode, mimetype=$mimetype, clientname=$clientname, filtergroup=$filtergroup, browseragent=$browseragent ;; sA=$sA, sA2=$sA2<br>\n";
# try to "canonicalize" the data
# (don't mess with IP, USER, or URL(Domain) for now,
# as doing so before there's _full_ support
# screws up the "click for details" functionality)
@categoryeach = ( '-' ) if ! $category;
$category = '-' if ! $category;
$retcode = '???' if ! $retcode;
$mimetype = '-' if ! $mimetype;
$filtergroup = '-' if ! $filtergroup;
$browseragent = '-' if ! $browseragent;
$ip = '-' if !$ip;
$user = '-' if !$user;
# don't swap in local names for IPs where known for now,
# as it's not _fully_ supported yet
# the shortcut below at first appears to work,
# but in fact causes problems with the "click for details" functionality
##$ip = $clientname if length $clientname > 1;
# issue an error message (a few times) if we have a problem
my $parseokcount = 0;
++$parseokcount if $ip;
++$parseokcount if $sitename;
++$parseokcount if $urlpath;
++$parseokcount if $action;
++$parseokcount if $reason;
++$parseokcount if $method;
++$parseokcount if $retcode;
if ($parseokcount < 4) {
print DEBUGLOG "in Log Analysis determined parse was screwed up so blanking everything\n" if $debug;
#print DEBUGLOG "just before blank because of misparse: line: [$line] (toeol: [$toeol]) --parsed to: date=$date, time=$time, user=$user, ip=$ip, url=$url(protocol=$protocol, allbutprotocol=$allbutprotocol, protocolandsitename=$protocolandsitename, baseurl=$baseurl, sitename=$sitename, urlpath=$urlpath, queryurl=$queryurl), otheractions=$otheractions, action=$action, reason=$reason (reasonjr=$reasonjr), subreason=$subreason (subreasonjr=$subreasonjr), method=$method, size=$size, weight=$weight, category=$category (categoryeach=@categoryeach), filtergroupnum=$filtergroupnum, retcode=$retcode, mimetype=$mimetype, clientname=$clientname, filtergroup=$filtergroup, browseragent=$browseragent ;; sA=$sA, sA2=$sA2<br>\n";
print "<p align=center><span style='color: red; font-weight: bold;'>$text{'error_warning'} $text{'view_err_notparse'} - $text{'view_err_logformat'}</span><br><i>example ($file):</i> $line<p>\n" if (($formaterrcountthislogfile < 1) && !$sTITLE);
++$formaterrcount;
++$formaterrcountthislogfile;
# since we've determined the parse was screwed up,
# completely blank ALL fields to make it very clear this is a failure
# and so (hopefully) not pollute the reports
&clearRequestVariables();
}
# keep count of items we could not understand, probably because they were in a different language
if (($reasonjr !~ m/^[-_+=.,:;\s]*$/) && (! exists $reasons_text2number{&canonicalizereason($reasonjr)})) {
++$languageerrcount;
}
# keep counts to figure out what kind of data we were given
++$noaddr if ((length($ip) <= 3) || ($ip =~ m/^\s*0+\./));
if (length($user) <= 3) {
++$nouser;
} else {
++$userisaddr if $user !~ m/^\D{4,}$/;
}
# keep choice lists complete
map $categories{lc $_}=1, @categoryeach;
$listchanged_categories = 1;
$mimetypes{lc $mimetype} = 1;
$listchanged_mimetypes = 1;
$filtergroups{lc $filtergroup} = 1;
$listchanged_filtergroups = 1;
# no further processing on records that don't match filter
# Rule out the easy matches first
if ($sIP ne 'ALL') {
my ($addrpart, $cidrpart) = split qr(\s*[-\\/:]\s*), $sIP, 2;
$addrpart = $sIP if ! defined $addrpart;
$cidrpart = 32 if ! $cidrpart;
my $numericaddrpart = &octets2numeric($addrpart);
my $numericactual = &octets2numeric($ip);
my $binmask = &cidr2binmask($cidrpart);
return if (($numericactual & $binmask) != ($numericaddrpart & $binmask));
}
return if (($sUN ne 'ALL') && ($sUN !~ m/^$user$/i));
# Rule out further matches
return if (($sCAT ne 'ALL') && (!existsinarray($sCAT, 'ignorecase', @categoryeach)));
return if (($sMIME ne 'ALL') && ($mimetype !~ m/^\s*$sMIME/i));
return if (($sGRP ne 'ALL') && ($sGRP !~ m/^$filtergroup$/i));
return if (($sAGT ne 'ALL') && ($browseragent !~ m/$sAGT/i));
return if (($sSN ne 'ALL') && ($protocolandsitename !~ m/$sSN$/i));
# don't do a date comparison unless we are told to
if ($sSD ne 'ALL' || $sED ne 'ALL') {
$dgDate = &convertDate($date);
return if (($sSD ne 'ALL') && ($dgDate lt $sSD));
return if (($sED ne 'ALL') && ($dgDate gt $sED));
}
# filter action/reason
if ($sA ne 'ALL') {
return if (($sA eq 'exceptionALL') &&
($action ne '*EXCEPTION*'));
return if (($sA eq 'deniedALL') &&
($action ne '*DENIED*'));
return if (($sA eq 'allowALL') &&
($action eq '*DENIED*'));
$privatereason = &canonicalizereason($reasonjr);
foreach my $number (keys %reasons_number2text) {
# find the one matching reason, process it, and exit this loop
next if $number != $sA;
my $reasontext = &canonicalizereason($reasons_number2text{$number});
return if $privatereason ne $reasontext;
last;
}
}
# filter action again against second criteria if following hyperlink
if ($sA2 ne 'ALL') {
return if (($sA2 eq 'exceptionALL') &&
($action ne '*EXCEPTION*'));
return if (($sA2 eq 'deniedALL') &&
($action ne '*DENIED*'));
return if (($sA2 eq 'allowALL') &&
($action eq '*DENIED*'));
}
# filter by weight(score) if specified
if ($sWGHT ne 'ALL') {
return if (! eval "$weight $sWGHT");
}
#print "next record summary counts, action=$action, sSumExc=$sSumExc, sSumDen=$sSumDen, sSumAlw=$sSumAlw<br>\n";
# Anything that gets this far has "passed the filter", so count it
$grandTotal++;
#print DEBUGLOG "matched filter: line: [$line] (toeol: [$toeol]) --parsed to: date=$date, time=$time, user=$user, ip=$ip, url=$url(protocol=$protocol, allbutprotocol=$allbutprotocol, protocolandsitename=$protocolandsitename, baseurl=$baseurl, sitename=$sitename, urlpath=$urlpath, queryurl=$queryurl), otheractions=$otheractions, action=$action, reason=$reason (reasonjr=$reasonjr), subreason=$subreason (subreasonjr=$subreasonjr), method=$method, size=$size, weight=$weight, category=$category (categoryeach=@categoryeach), filtergroupnum=$filtergroupnum, retcode=$retcode, mimetype=$mimetype, clientname=$clientname, filtergroup=$filtergroup, browseragent=$browseragent ;; sA=$sA, sA2=$sA2<br>\n";
# Do summary processing if ANY summary selected
if ($sSumAlw eq "on" || $sSumDen eq "on" || $sSumExc eq "on") {
if (($action eq '*EXCEPTION*') && ($sSumExc eq 'on')) {
$exceptionTotal++;
# Don't waste memory if didn't want this
while (($order, $source) = each %order2source) {
$hashname = "exception$order";
$$hashname{$$source} ++;
}
}
if (($action eq '*DENIED*') && ($sSumDen eq 'on')) {
$deniedTotal++;
# Don't waste memory if didn't want this
while (($order, $source) = each %order2source) {
$hashname = "denied$order";
$$hashname{$$source} ++;
}
}
if (($action ne '*DENIED*') && ($sSumAlw eq 'on')) {
$allowedTotal++;
# Don't waste memory if didn't want this
while (($order, $source) = each %order2source) {
$hashname = "allowed$order";
$$hashname{$$source} ++;
}
}
}
if (($sD eq 'on') && ($date ne '')) {
my $displayip = $clientname ? "$ip($clientname)" : $ip;
print "<br>$date $time $displayip $user $filtergroup $method $size $mimetype $category $weight<br>\n";
print "$browseragent<br>\n" if (($sG eq 'on') && ($browseragent !~ m/^[-_+=.,:;\s]*$/));
if ($sL eq 'on') {
print "<a href='$url' target=_blank>$url</a><br>\n";
} else {
print "$url<br>\n";
}
if ($sR eq 'on') {
# former hack ($reason =~ m/reg[uo]|compr/i) replaced with real working totally language-independent test
if (exists $regexpreasons_text2number{$reason}) {
($modpattern = $subreason) =~ s/\(\?:/\(/g;
($modurl = $allbutprotocol) =~ s!$modpattern!<span style='color: #686828; text-decoration: underline'>$&</span>!i;
my $escapedsubreason = &html_escape($subreason);
print "<span style='color: #686828'>$escapedsubreason</span> $text{'view_matched'}=> $protocol://$modurl<br>\n";
my %completedranges = ();
my $first = 1;
SUBSTRING: for my $i (1..$#-) {
$substring = $$i;
next if !$substring;
#print "$i: $-[$i] - $+[$i] = $$i<br>\n";
if (($substring =~ m/^\W?\w{3,}\W?/) || ($substring =~ m/^\W{0,2}\w{4,}\W{0,2}$/) || ($substring =~ m/^\W{0,3}\w{5,}\W{0,3}$/) || ($substring =~ m/\w{6,}/)) {
while (my ($left, $right) = each %completedranges) {
if (($-[$i] >= $left) && ($+[$i] <= $right)) {
# this "word" was already included in a larger "word" that was already processed
#print "superceded by completedranges $left $right<br>\n";
next SUBSTRING;
}
}
$completedranges{$-[$i]} = $+[$i];
if ($first) {
print "$text{'view_matchterms'}: <span style='color: #686828'>";
$first = 0;
} else {
print "</span>, <span style='color: #686828'>";
}
$substring =~ s/^\W+//; # trim away things that are obviously not part of a word
$substring =~ s/\W+$//; # trim away things that are obviously not part of a word
print "$substring";
}
}
print "</span><br>\n" if ! $first;
}
}
if ($sP eq 'on') {
if (exists $phrasereasons_text2number{$reasonjr}) {
print "<span style='color: #686828'>$subreasonjr</span><br>\n";
}
}
if ($action ne '' && $reason ne '') {
print "<span style='color: red'>$action : $reason";
print ": $reasonjr" if $reason !~ m/$reasonjr/;
print "</span><br>\n";
}
}
}
#############
sub printMenu
#############
{
#&printHeader(); # standalone, but don't do this when embedded in Webmin
print "
<form action=$cgipath name=mainmenu><input type=hidden name=a value='i'>
<table align=center bgcolor=ffffff border=1 cellpadding=7 cellspacing=1>\n";
if ($msg ne "") {
print "<tr><td colspan=3 bgcolor=c80000 align=center>
<font face=arial,helvetica,sans-serif size=3><b>$msg</b>
</font></tr>\n";
}
# "Filter" section title
print "
<tr bgcolor=#e0e0e0>
<th colspan=3>" .
uc($text{'view_requestfilters'}) . "<br>($text{'view_anded'})
</th>
</tr>\n";
# Filter items column headings
print "
<tr bgcolor=#f0f0f0>
<th>
$text{'view_parameter'}
</th>
<th>
$text{'view_value'}
</th>
<th width=30%>
$text{'view_description'}
</th></tr>\n";
# Menu item for entering date ranges
print "<script type=text/javascript>
function setALLStartDates(myself)
{
if (myself.selectedIndex > 1) return;
myself.form.sSDY.selectedIndex = 0;
myself.form.sSDM.selectedIndex = 0;
myself.form.sSDD.selectedIndex = 0;
}
function setALLEndDates(myself)
{
if (myself.selectedIndex > 1) return;
myself.form.sEDY.selectedIndex = 0;
myself.form.sEDM.selectedIndex = 0;
myself.form.sEDD.selectedIndex = 0;
}
function setNewStartDates(myself)
{
var field;
field = myself.form.sSDY;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
field = myself.form.sSDM;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
field = myself.form.sSDD;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
}
function setNewEndDates(myself)
{
var field;
field = myself.form.sEDY;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
field = myself.form.sEDM;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
field = myself.form.sEDD;
if (field.selectedIndex == 0) { field.selectedIndex = 2; }
}
</script>\n";
print "
<tr><td align=left>
Enter $text{'field_daterange'}
<br>
</td>
<td align=left>
$text{'field_startdate'}<br>
<select name=sSDY onChange='setNewStartDates(this);setALLStartDates(this);'>";
&buildSelect(2002,2020,$year,$sSDY);
print "</select><select name=sSDM onChange='setNewStartDates(this);setALLStartDates(this);'>";
&buildSelect(01,12,$mon,$sSDM);
print "</select><select name=sSDD onChange='setNewStartDates(this);setALLStartDates(this);'>";
&buildSelect(01,31,$mday,$sSDD);
print "</select><br>
$text{'field_enddate'}<br>
<select name=sEDY onChange='setNewEndDates(this);setALLEndDates(this);'>";
&buildSelect(2002,2020,$year,$sEDY);
print "</select><select name=sEDM onChange='setNewEndDates(this);setALLEndDates(this);'>";
&buildSelect(01,12,$mon,$sEDM);
print "</select><select name=sEDD onChange='setNewEndDates(this);setALLEndDates(this);'>";
&buildSelect(01,31,$mday,$sEDD);
print "</select>
</td>
<td align=center>
Either specify a start date and end date,
or set <i>any</i> field to '--ALL--'
to include all the request records
available in the logs directory
regardless of their date.
</td></tr>\n";
# Menu item for IP viewing
print "
<tr><td align=left>
Enter $text{'field_ipaddress'}
</td>
<td align=left>
<input name=sIP maxlength=35 size=20 value='$sIP'>
</td>
<td align=center>
examples:<br>
for a single system 172.16.34.45,<br>
for a whole subnet 172.16.0.0/12<br>(or equivalently 172.16.0.0/255.240.0.0)
</td></tr>
<script>
if (document.mainmenu.sIP.value == 'ALL') document.mainmenu.sIP.value = '';
</script>\n";
# Menu item for username viewing
print "
<tr><td align=left>
Enter a $text{'field_username'}
</td>
<td align=left>
<input name=sUN maxlength=35 size=20 value='$sUN'>
</td>
<td align=center>
authplugin(s) should be enabled and functioning<br>
</td></tr>
<script>
if (document.mainmenu.sUN.value == 'ALL') document.mainmenu.sUN.value = '';
</script>\n";
# Menu item for sitename (domain) viewing
print "
<tr><td align=left>
Enter a Site (domain) Name
</td>
<td align=left>
<input name=sSN maxlength=50 size=20 value='$sSN'>
</td>
<td align=center>
Enter the www.domain.com part of a URL only<br>
(just 'domain' without 'www' or 'com' or dots is okay)
</td></tr>
<script>