/
pylog.py
426 lines (354 loc) · 14.3 KB
/
pylog.py
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
import re, os, sys, time, codecs, binascii, copy
import carny
def test(args):
gen_count = 0
parse_count = 0
for arg in args:
gen = gen_events(arg)
for e in gen:
gen_count += 1
print("test complete. Number of events: %d" % gen_count)
def gen_events(path):
'''takes in a string representing a path on your computer, then utilizes
the rest of the library to produce a generator which yields dictionaries
representing log events. These '''
log_dict = get_log_type(path)
if os.path.isfile(path) and log_dict is not None:
type_used = log_dict["type"]
print("INFO: log type is: %s" % type_used)
file_name = log_dict["file_name"]
method = log_dict["method"]
if log_dict["multiline"]:
return method(path, type_used, file_name)
else:
pat = log_dict["pattern"]
headers = log_dict["headers"]
lines = gen_line(path)
events = gen_dirty_event(lines, method, pat, headers)
return gen_clean(events,type_used, file_name)
def gen_clean(events, used, name):
'''Take in an event iterable, log type, and a file name
and use the latter two to enrich the event and give the event
an epoch timestamp as well as ensure that there are no unprintable
hex characters. Yields a dictionary representing a cleaned event.'''
for e in events:
if e is not None:
if used in unspecified:
e["date_time"] = e["date_time"].strip()+" 2006"
try:
e["epoch"] = carny.guess(e["date_time"])
except Exception as e:
print("ERROR: event is mis-formatted: %s" % str(e))
yield None
e['type'] = used
e['file_name'] = name
c = utf8_check(e)
yield c
def utf8_check(event):
'''check an event to see if it has any nasty characters. '''
has_hex = False
for k,v in event.iteritems():
try:
str(v).encode(encoding='utf8')
except Exception as e:
print("WARN: found unsupported characters, tried reformatting line from iso-8859-9 to utf8 : %s" % (v))
event[k] = reformat_content(v).decode('iso-8859-9').encode('utf8')
has_hex = True
event["has_hex"] = has_hex
return event
def gen_dirty_event(lines, method, pattern, use_headers=None):
'''abstaction generator that takes in lines of log files
their parsing method, the pattern to use, and the fields that
the line will be parsed into (if necessary). Methods supplied
in the "method" argument must return a dictionary or None.'''
for line in lines:
yield method(line, pattern, use_headers)
def gen_line(path):
'''Given a path, yeild each line for further processing. '''
with open(path) as f:
for line in f:
yield line
def get_log_type(path):
'''determine is pylog can parse the file given. There are strict
naming conventions used in pylog. Utilize the log_types() method to aid
in your use.'''
log_dict = None
file_name = path.split("/")[-1]
#find the appropriate log definition for parsing
for log_type in log_map:
if log_type in file_name or log_type in file_name.split(".")[0]:
log_dict = log_map[log_type]
log_dict['type'] = log_type
#find it and get out before we duplicate (greedy)
break
#If we have a generic .log file (after specials have been checked)
#select the appropriate generic log file parser
if log_dict is None and file_name.endswith(".log"):
log_dict = generic_logs['.log']
log_dict['type'] = '.log'
#If we have the log type, add the file name
if log_dict is not None:
log_dict['file_name'] = file_name
else:
print("WARN: Log type %s not found, pylog is ignoring"%file_name)
return log_dict
def parse_line(line,pattern, headers=None):
ret = None
if headers is not None:
ret = _use_headers(line,pattern,headers)
else:
d = re.compile(pattern,re.VERBOSE).match(line)
if d is not None:
ret = d.groupdict()
return ret
def _use_headers(line, pattern, headers):
cpy = copy.deepcopy(headers)
splits = line.split(pattern)
if len(splits) >= 8 and not splits[7]:
splits.remove('')
if len(splits) != len(cpy):
cpy.append("extra")
print("WARN: Header mismatch, tried a quick fix: %s" % (line))
if len(splits) != len(cpy):
print("ERROR: Header mismatch, recheck log file: %s" % (line))
print("ERROR: headers for above error: %s" % (str(headers)))
ret = dict(zip(cpy,splits))
try:
ret["date_time"] = ret["date"]+" "+ret["time"]
except Exception as e:
print("WARN: _use_headers caught an exception while trying to munge date_time", e)
return ret
def parse_ie_log(line,pattern,headers=None):
headers1 = ["date_time","log_level","message"]
headers2 = ["date_time","message"]
splits = line.split(pattern)
if len(splits) > 2:
return dict(zip(headers1,splits))
else:
return dict(zip(headers2,splits))
def parse_unamed_log(line, pattern,headers=None):
row = line.split(pattern)
header1 = ["date_time","time","client_ip", "client_hostname",
"partner_Name","server_hostname","server_ip",
"recipient-address","event_id","msg_id","priority",
"recipient_report_status","total_bytes","number_recipients",
"origination_time","encryption","service_version",
"linked_msg_id","message_subject","sender_address","additional"]
ret = None
if len(row) == len(header1):
ret = dict(zip(header1,row))
return ret
def parse_mail_log_line(line,pattern,headers=None):
first_pass = parse_line(line,pattern,headers)
pairs = first_pass['rest'].split(",")
for pair in pairs:
items = pair.split("=")
first_pass[items[0].strip()] = items[1].strip()
return first_pass
def parse_ossec_log(path, type_used, file_name):
events = []
with open(path) as f:
for line in f:
if "**" in line:
event = dict()
event["file_name"] = file_name
event["type"] = type_used
event["message"]= line
else:
m = re.match(r'(?P<date_time>^\d{,4}\s+\w+\s+\d\d\s+\d\d:\d\d:\d\d)',line)
if m is not None:
event["date_time"] = m.groupdict()["date_time"]
event["message"] = event["message"] + line
indx = line.find(":")
if indx != -1:
#these logs have dynamic fields in the format "<header> : <message>"
event[line[:indx].strip()] = line[indx+1:].strip()
if not line.strip():
events.extend([event])
return events
def log_types():
first_keys = log_map.keys()
keys = first_keys+ [".log"]
return keys
def asciirepl(match):
# replace the hexadecimal characters with ascii characters
s = match.group()
return binascii.unhexlify(s)
def reformat_content(data):
p = re.compile(r'\\x(\w{2})')
return p.sub(asciirepl, data)
unspecified = ["_maillog", "_messages", "_secure", "_last.log"]
win_log = {"pattern":"\t",
"method":parse_line,
"headers":["date","time","type","catetory","event_code","source_name","user","computer_name","description"],
"multiline":False,
}
#TODO: handle the numeric logs better.
generic_logs ={ ".log":
{"pattern":"\t",
"method":parse_unamed_log,
"headers":None,
"multiline":False,
}
}
#The bread and butter of the script, contains regexes of the logs
#and which method to use to parse the log.
log_map = {
"access_log":
{"pattern":
r"""
^
(?P<sip>[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3}\.[0-9]{,3})
\s
(?P<client_identity>[^ ]{1,})
\s
(?P<user_id>[^ ]{1,}|\-)
\s
\[(?P<date_time>[0-9]{2}\/[A-Za-z]{3}\/[0-9]{1,4}:[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}
\s
[+\-][0-9]{4})\]
\s
"(?P<http_request_type>[A-Z ]+)
\s
(?P<requested_resource>[^"]*)
\s
(?P<protocol>[^"]*)"
\s
(?P<response_code>[0-9]{3})
\s
?(?P<bytes>[0-9]{1,}|\-)
\s
"(?P<referrer>[^"]*|\-)"
\s
"(?P<agent_string>[^"]+)"
?
$
""",
"method":parse_line,
"headers":None,
"multiline":False,
},
"error_log":
{"pattern":
r'''(?P<date_time>\[.*?\]) (?P<log_level>\[.*?\]) ?(?P<client_string>\[.*?\])? (?P<error_string>.*?$)''',
"method":parse_line,
"headers":None,
"multiline":False,
},
"AppEvent":win_log,
"SecEvent":win_log,
"SysEvent":win_log,
"win_user":
{"pattern":"::",
"method":parse_ie_log,
"headers":None,
"multiline":False,
},
"_last.log":
{"pattern":
r'''^
(?P<command>\w+)
\s*
(?P<pid>\w+\d+)
\s*
(?P<source_name>(\w+[.]|\w+){1,})
\s*
(?P<date_time>\w+\s+\w+\s+\d{,2}\s+\d{,2}:\d{,2})
.*\(
(?P<duration>\d{,2}:\d{,2})
\)
''',
"method":parse_line,
"headers":None,
"multiline":False,
},
"_maillog":
{"pattern":
r'''^
(?P<date_time>\w+\s+\d\s+\d\d:\d\d:\d\d)
\s*
(?P<folder>\w+)
\s*
(?P<action>\w+\[\d{1,}\])
:\s*
(?P<mail_id>\w+)
:
(?P<rest>.*$)
''',
"method":parse_mail_log_line,
"headers":None,
"multiline":False,
},
"_messages":
{"pattern":
r'''^
(?P<date_time>\w+\s+\d\s+\d\d:\d\d:\d\d)
\s*
(?P<folder>\w+)
\s*
(?P<service>.*)
:\s*
(?P<message>.*$)
''',
"method":parse_line,
"headers":None,
"multiline":False,
},
"_secure":
{"pattern":
r'''^
(?P<date_time>\w+\s+\d\s+\d{,2}:\d{,2}:\d{,2})
\s*
(?P<folder>\w+)
\s*
(?P<service>.*)
:\s*
(?P<message>.*$)
''',
"method":parse_line,
"headers":None,
"multiline":False,
},
".xferlog":
{"pattern":
r'''^
(?P<date_time>\w+\s+\w+\s+\d{,2}\s+\d{,2}:\d{,2}:\d{,2}\s+\d{,4})
\s+
(?P<transfer_time>\d+)
\s+
(?P<remote_host>(\w+[.]|\w+){1,})
\s+
(?P<file_size>\d+)
\s+
(?P<file_name>.*?)
\s+
(?P<transfer_type>a|b)
\s+
(?P<special_action_flag>C|T|U|_)
\s+
(?P<direction>o|i|d )
\s+
(?P<access_mode>a|g|r)
\s+
(?P<username>.*?)
\s+
(?P<service_name>.*?)
\s+
(?P<authentication_method>0|1)
\s+
(?P<authenticated_user_id>.*?)
\s+
(?P<completion_status>c|i$)
''',
"method":parse_line,
"headers":None,
"multiline":False,
},
"ossec.alert.log":
{"pattern":":",
"method":parse_ossec_log,
"headers":None,
"multiline":True,
},
}
if __name__=="__main__": test(sys.argv[1:])