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 | #!/usr/bin/env python
import ConfigParser, os, re
config_file = "/path/to/apache_util.config"
class ApacheUtil:
"""
example config file:
[main]
apache_log = /var/log/apache2/access.log
ban_file = /etc/deny.hosts
ban_after = 5
ban_level = ALL
"""
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.config.read(config_file)
self.apache_log = self.config.get("main", "apache_log")
self.ban_file = self.config.get("main", "ban_file")
self.ban_after = int(self.config.get("main", "ban_after"))
self.ban_level = self.config.get("main", "ban_level")
self.parts = [
r'(?P<host>\S+)',
r'\S+',
r'(?P<user>\S+)',
r'\[(?P<time>.+)\]',
r'"(?P<request>.+)"',
r'(?P<status>[0-9]+)',
r'(?P<size>\S+)',
r'"(?P<referer>.*)"',
r'"(?P<agent>.*)"',
]
self.pattern = re.compile(r'\s+'.join(self.parts)+r'\s*\Z')
self.matches = {
"rfi":{}
}
def add_match(self, type, ip):
if type not in self.matches:
return "Invalid type"
else:
if ip in self.matches[type]:
self.matches[type][ip] += 1
else:
self.matches[type][ip] = 1
def ban_matches(self, type):
file = open(self.ban_file, "r")
contents = file.read()
file.close()
banned = ""
total = 0
for match in self.matches[type]:
if self.matches[type][match] >= self.ban_after and contents.find(match) == -1:
banned += "%s: %s \n" % match
total += 1
if banned != "":
file = open(self.ban_file, "a")
file.write(banned)
file.close()
print "banned %d %s's" % (total, type)
def ban_rfi(self):
for line in file(self.apache_log):
m = self.pattern.match(line)
request = m.groupdict()
#print request
pat = re.compile(r'(.*)(http|https|ftp):\/\/(.*)')
if pat.match(request['request'].split()[1]):
self.add_match("rfi", request['host'])
self.ban_matches('rfi')
if __name__ == "__main__":
ap = ApacheUtil()
ap.ban_rfi()
|