-
Notifications
You must be signed in to change notification settings - Fork 0
/
aplogfilter.php
87 lines (85 loc) · 3.4 KB
/
aplogfilter.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
<?php
require_once('./cidrmatch.php');
/*
Apache Log Filter - a utility that reads an Apache httpd
log file and outputs a "filtered" result.
It uses a JSON file to contain an array of "known" IP
addresses. If the IP in a log line of text matches any
of the filters then that line is skipped. Otherwise it
is written to the output file.
*/
function apLogFilter($logfile, $outfile, $filtsel = 'iplist') {
$ret = new stdClass();
$ret->r = false;
$ret->m = '';
// aplogfilter.json contains an array of IP addresses or CIDR ranges
$filter = json_decode(file_get_contents('./aplogfilter.json'));
if(($filter === null) || (!isset($filter->iplist))) {
$ret->m = 'bad filter file';
$ret->r = false;
} else {
// haven't found anything yet...
$ipfound = false;
// open the output file first...
if(($op = fopen($outfile, 'w')) === false) {
$ret->m = 'cannot open for output - '.$outfile;
$ret->r = false;
} else {
// open the log file...
if(($lp = fopen($logfile, 'r')) !== false) {
// read one line at a time...
while(($line = fgets($lp)) !== false) {
// extract the IP address from the line
if(($end = strpos($line, ' -')) === false) {
$ret->m = 'unknown line - '.$line;
$ret->r = false;
break;
} else {
$unkip = substr($line, 0, $end);
// compare the unknown IP address against the filters...
foreach($filter->iplist as $filterip) {
// is the current filter a CIDR?
if(iscidr($filterip)) {
if(cidrmatch($unkip, $filterip)) {
$ipfound = true;
break;
}
} else {
// look for an exact match
if($filterip === $unkip) {
$ipfound = true;
break;
}
}
}
// all filters checked, was there a match?
if($ipfound === true) {
// yes, found a match. reset and continue...
$ipfound = false;
} else {
// no matches, write the line into the output file
if(fwrite($op, $line, strlen($line)) === false) {
$ret->m = 'error writing to '.$outfile;
$ret->r = false;
break;
}
}
}
}
fflush($op);
fclose($op);
fclose($lp);
if($ret->m === '') {
$ret->m = $outfile . ' has been saved';
$ret->r = true;
}
} else {
fclose($op);
$ret->m = 'cannot open for input - '.$logfile;
$ret->r = false;
}
}
}
return $ret;
}
?>