-
Notifications
You must be signed in to change notification settings - Fork 0
/
isshd_logparser.py
executable file
·236 lines (169 loc) · 10.4 KB
/
isshd_logparser.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
#!/usr/bin/env python
import re
import urllib
import argparse
import gzip
import os.path
from datetime import datetime
import string
import unicodedata
def openFile(filename=None):
if filename==None:
raise ValueError("No filename specified.")
elif not os.path.exists(filename) or os.path.isdir(filename):
raise ValueError("Filename specified doesn't exist or is a directory")
elif filename.endswith(".gz"):
return gzip.open(filename, 'r')
else:
return open(filename, 'r')
def escape_control_characters(s):
return "".join(ch.encode('unicode_escape') if unicodedata.category(unicode(ch))[0]=="C" else ch for ch in s)
def decodeData(data=None):
if data==None:
raise ValueError("No data provided.")
else:
data_decoded=urllib.unquote_plus(data).lstrip()
returndata=""
try:
returndata=escape_control_characters(data_decoded)
except UnicodeDecodeError:
returndata="UNICODE PARSE ERROR:" . data_decoded
finally:
return returndata
if __name__=="__main__":
interactivedefault=True #change to false if you want non-interactive to be default
defaultlogfilepath="/usr/local/bro/logs/isshd/isshd.log" #default path, if nothing specified
#set up command-line args
argparser = argparse.ArgumentParser(description="Extract info from isshd logs, making it more intelligible")
argparser.add_argument('-s', '--sessionid', action='store', metavar="SESSIONID", dest='sessionid', help="REQUIRED OPTION. Session to extract from the log. Note that this is usually available in the Bro notification email, right before the username.", required=True)
argparser.add_argument('-l', '--logfile', action='append', metavar='LOGFILEPATH', dest='logfiles', help="Specifies the path or paths to extract data from. May be specified multiple times, and log files may be compressed with '.gz' extension.", default=[])
argparser.add_argument('-i', '--interactive', action="store_true", dest="interactive", help="use colorized, interactive output (q to exit)", default=interactivedefault)
argparser.add_argument('-n', '--noninteractive', action="store_false", dest="interactive", help="plain, non-interactive output")
args = argparser.parse_args()
#some strings used by both branches of the code
client_key_string='Client Input'
server_key_string='Server Output'
client_notty_key_string='Client Input (no-tty)'
server_notty_key_string='Server Output (no-tty)'
#default of interactive vs non-interactive, will depend on what the user specified
#but will still be subject to the following try/except logic
interactive_output = args.interactive
try:
import urwid
#we succeeded in importing. Just use whatever the user already specified, which we've already put into "interactive_output"
#and define a bunch of stuff here, so if we don't have it, these won't throw errors about unknown names
class ItemWidget (urwid.WidgetWrap):
def __init__ (self, id, date, message, msgtype):
self.id = id
self.item = [
('fixed', 28, urwid.Padding(urwid.AttrMap(urwid.Text('%s' % date), 'date', 'focus'))),
urwid.Text((msgtype, '%s' % message))
]
w = urwid.Columns(self.item)
self.__super.__init__(w)
def selectable (self):
return True
def keypress(self, size, key):
return key
def urwidMain(eventslist, sessionid):
#main color pallette:
#Syntax:
# ( NAME , ForegroundColor, BackgroundColor, I'm Not Sure )
palette = [
('date','dark red', 'black', ''),
('focus','light red', 'black', 'standout'),
('client', 'light green', 'black', ''),
#('clientbgkey', '', 'dark green', ''),
('clientnotty', 'black', 'light green', 'standout'),
('server', 'light gray', 'black', ''),
#('serverbgkey', '', 'brown', ''),
('servernotty', 'black', 'light gray', 'standout'),
('header','light red', 'black'),
('footer','light red', 'black'),
('key','light red','black')
]
headerstring = "isshd_logparser for session %s" % sessionid
key_key_string='Key:'
footerstring = "Hotkeys: q -> Quit"
sortedeventslist = [ eventslist[i] for i in sorted(eventslist) ]
mainheader = urwid.AttrMap(urwid.Text(headerstring), 'header')
legend = urwid.Columns([
urwid.Padding(urwid.AttrMap(urwid.Text(key_key_string), 'key'), left=5),
#(2, urwid.AttrMap(urwid.Text('', align='right'), 'clientbgkey')),
(len(client_key_string)+1, urwid.AttrMap(urwid.Text(client_key_string, align='left'), 'client')),
(len(client_notty_key_string)+1, urwid.AttrMap(urwid.Text(client_notty_key_string, align='left'), 'clientnotty')),
#(2, urwid.AttrMap(urwid.Text('', align='right'), 'serverbgkey')),
(len(server_key_string)+1, urwid.AttrMap(urwid.Text(server_key_string, align='left'), 'server')),
(len(server_notty_key_string)+1, urwid.AttrMap(urwid.Text(server_notty_key_string, align='left'), 'servernotty'))
])
headercolumns = urwid.Columns([
mainheader,
(len(key_key_string)+len(client_key_string)+len(server_key_string)+len(client_notty_key_string)+len(server_notty_key_string)+10, legend)
])
footer = urwid.AttrMap(urwid.Text(footerstring), 'footer')
frame = urwid.Frame( urwid.ListBox( sortedeventslist ), header=headercolumns, footer=footer)
def unhandled(key):
if key in ('q','Q'):
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(frame, palette, unhandled_input=unhandled)
loop.run()
except ImportError:
#had a problem importing URWID library
if (args.interactive):
print "Error: interactive output requires the URWID library (urwid.org), but I can't seem to find it. Reverting to non-interactive output"
interactive_output=False
if args.logfiles==[]:
args.logfiles.append(defaultlogfilepath);
session_regex_match = r"^(channel_data_server_3|channel_data_client_3|channel_notty_client_data_3|channel_notty_server_data_3)\s+time=([.\d]+)\s+uristring=(\S+)\s+uristring=-?\d+%%3A(\S+)\s+count=%s\s+count=0\s+uristring=(\S+)\s*$" % args.sessionid
session_regex_match_re = re.compile(session_regex_match)
sessionevents = {} #collector for events; the exact structure will be different for interactive vs non-interactive
idcount=0 #we need a unique ID for the interactive ItemWidgets, unused otherwise
for filename in args.logfiles:
print "Parsing file %s" % filename
fh = openFile(filename)
line = fh.readline()
#I'm putting this if conditional outside the "while line" loop
#so we will only encounter/evaluate the if, once per file, not
#once per line. It does duplicate some code, but not much.
if (interactive_output):
while line:
matchresults = session_regex_match_re.search(line)
if matchresults != None:
matchcaptures = matchresults.groups()
if matchcaptures[0]=="channel_data_server_3":
sessionevents[datetime.fromtimestamp(float(matchcaptures[1]))]=ItemWidget(idcount, datetime.fromtimestamp(float(matchcaptures[1])), decodeData(matchcaptures[4]), 'server')
idcount += 1
elif matchcaptures[0]=="channel_data_client_3":
sessionevents[datetime.fromtimestamp(float(matchcaptures[1]))]=ItemWidget(idcount, datetime.fromtimestamp(float(matchcaptures[1])), decodeData(matchcaptures[4]), 'client')
idcount += 1
elif matchcaptures[0]=="channel_notty_client_data_3":
sessionevents[datetime.fromtimestamp(float(matchcaptures[1]))]=ItemWidget(idcount, datetime.fromtimestamp(float(matchcaptures[1])), decodeData(matchcaptures[4]), 'clientnotty')
idcount += 1
elif matchcaptures[0]=="channel_notty_server_data_3":
sessionevents[datetime.fromtimestamp(float(matchcaptures[1]))]=ItemWidget(idcount, datetime.fromtimestamp(float(matchcaptures[1])), decodeData(matchcaptures[4]), 'servernotty')
idcount += 1
line = fh.readline()
else: #non-interactive output
while line:
matchresults = session_regex_match_re.search(line)
if matchresults != None:
matchcaptures = matchresults.groups()
eventtype="Unknown"
if matchcaptures[0] == "channel_data_client_3":
eventtype=client_key_string
elif matchcaptures[0] == "channel_data_server_3":
eventtype=server_key_string
elif matchcaptures[0]=="channel_notty_client_data_3":
eventtype=client_notty_key_string
elif matchcaptures[0]=="channel_notty_server_data_3":
eventtype=server_notty_key_string
sessionevents[datetime.fromtimestamp(float(matchcaptures[1]))]={'type': eventtype, 'data': decodeData(matchcaptures[4])}
line = fh.readline()
fh.close()
print "Done parsing %s" % filename
if (interactive_output):
urwidMain(sessionevents, args.sessionid)
else:
for eventdatetime in sorted(sessionevents):
print "{when} {type}: {data}".format(when=eventdatetime, type=sessionevents[eventdatetime]['type']
, data=sessionevents[eventdatetime]['data'])