This repository was archived by the owner on Jan 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathipfix-rita-debug.py
More file actions
executable file
·432 lines (371 loc) · 14.4 KB
/
ipfix-rita-debug.py
File metadata and controls
executable file
·432 lines (371 loc) · 14.4 KB
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
#!/usr/bin/env python3
import subprocess
import sys
import os.path
import os
import signal
import threading
import tempfile
import time
import shutil
"""
Built against:
tcpdump --version:
tcpdump version 4.9.2
libpcap version 1.8.1
OpenSSL 1.0.2g 1 Mar 2016
docker-compose --version
docker-compose version 1.22.0, build f46880fe
"""
def OrEvent(*events):
"""
Used to wait for any one of a set of given events.
"""
or_event = threading.Event()
def or_set(self):
self._set()
self.changed()
def or_clear(self):
self._clear()
self.changed()
def changed():
if any([e.is_set() for e in events]):
or_event.set()
else:
or_event.clear()
for e in events:
e._set = e.set
e._clear = e.clear
e.changed = changed
e.set = lambda e=e: or_set(e)
e.clear = lambda e=e: or_clear(e)
changed()
return or_event
class StoppedException(Exception):
""" Indicates a thread was stopped """
pass
class TCPDump_Monitor(threading.Thread):
"""
Uses TCPDump to monitor for netflow/ ipfix data. Fires self.data_found
when data is seen crossing the wire. May fire exception_encountered
if a problem arises. Once self.data_found has been fired, the first
instance of tcpdump is killed off, and a second one is started which
writes to file.
"""
def __init__(self, pcap_file_path, ipfix_iface):
threading.Thread.__init__(self)
self.data_found = threading.Event()
self.exception_encountered = threading.Event()
self.__stop_event = threading.Event()
self.pcap_file_path = pcap_file_path
self.ipfix_iface = ipfix_iface
self.tcpdump_proc = None
def stop(self):
# The process gets killed here in case
# the run method is blocking on a piped read
if self.tcpdump_proc is not None and self.tcpdump_proc.poll() is None:
os.killpg(os.getpgid(self.tcpdump_proc.pid), signal.SIGTERM)
self.__stop_event.set()
def stopped(self):
return self.__stop_event.is_set()
def run(self):
try:
self.tcpdump_proc = subprocess.Popen(
["tcpdump", "-l", "-i", self.ipfix_iface, "udp port 2055"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
start_new_session=True
)
for line in iter(self.tcpdump_proc.stdout.readline, b''):
# iter(tcpdump_proc.stdout.readline, b'') should exit
# when the process is killed
line = line.decode(sys.stdout.encoding)
if "UDP" in line and not self.data_found.is_set():
self.data_found.set()
break
if self.stopped():
raise StoppedException()
os.killpg(os.getpgid(self.tcpdump_proc.pid), signal.SIGTERM)
for line in iter(self.tcpdump_proc.stdout.readline, b''):
# line = line.decode(sys.stdout.encoding)
# print(line, end="")
pass
self.tcpdump_proc.wait()
if self.stopped():
raise StoppedException()
self.tcpdump_proc = subprocess.Popen(
["tcpdump", "-i", self.ipfix_iface, "-C", "50", "-w",
self.pcap_file_path, "-s", "0", "udp port 2055"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
start_new_session=True
)
self.__stop_event.wait()
except (ValueError, OSError):
print("Unable to start tcpdump.")
self.exception_encountered.set()
except StoppedException:
pass
# Stop was called before we were ready to stop
# No exception was encountered as this is defined behavior.
except Exception as e:
print("An error occurred while running tcpdump.")
print(e)
self.exception_encountered.set()
finally:
if not self.stopped():
self.stop()
if self.tcpdump_proc is not None and self.tcpdump_proc.poll() is None:
# You must drain a process' pipe before you can .wait() for it
for line in iter(self.tcpdump_proc.stdout.readline, b''):
# line = line.decode(sys.stdout.encoding)
# print(line, end="")
pass
self.tcpdump_proc.wait()
class IPFIX_RITA_Monitor(threading.Thread):
"""
Monitors the ipfix-rita application log for errors and records
a copy of the log. Fires self.error_found once an error has been found
in the logs. May fire self.exception_encountered if a problem is encountered
during the process.
"""
IPFIX_RITA = "ipfix-rita"
def __init__(self, log_file_path):
threading.Thread.__init__(self)
self.error_found = threading.Event()
self.exception_encountered = threading.Event()
self.__stop_event = threading.Event()
self.__docker_compose_attached_event = threading.Event()
self.log_file_path = log_file_path
self.ipfix_rita_proc = None
def stop(self):
# The process gets killed here in case
# the run method is blocking on a piped read
if self.ipfix_rita_proc is not None and self.ipfix_rita_proc.poll() is None:
# Have to wait for the attach step from docker-compose
# otherwise, docker-compose doesn't actually stop everything.
self.__docker_compose_attached_event.wait()
os.killpg(os.getpgid(self.ipfix_rita_proc.pid), signal.SIGTERM)
self.__stop_event.set()
def stopped(self):
return self.__stop_event.is_set()
def run(self):
try:
log_file = open(self.log_file_path, 'w')
except:
print("Could not open {0}".format(self.log_file_path))
self.exception_encountered.set()
return
try:
subprocess.check_call(
[IPFIX_RITA_Monitor.IPFIX_RITA, "stop"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if self.stopped():
raise StoppedException()
self.ipfix_rita_proc = subprocess.Popen(
[IPFIX_RITA_Monitor.IPFIX_RITA, "up"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
start_new_session=True
)
for line in iter(self.ipfix_rita_proc.stdout.readline, b''):
# iter(ipfix_rita_proc.stdout.readline, b'') should exit
# when the process is killed
line = line.decode(sys.stdout.encoding)
# print(line, end="")
if "ERR" in line and not self.error_found.is_set():
self.error_found.set()
if "Attaching" in line and not self.__docker_compose_attached_event.is_set():
self.__docker_compose_attached_event.set()
log_file.write(line)
self.__stop_event.wait()
self.ipfix_rita_proc.wait()
except (ValueError, OSError):
print("Could not execute IPFIX-RITA.")
self.exception_encountered.set()
except StoppedException:
pass
# Stop was called before we were ready to stop
# No exception was encountered as this is defined behavior.
except Exception as e:
print("An error occurred while monitoring ipfix-rita.")
print(e)
self.exception_encountered.set()
finally:
if not self.stopped():
self.stop()
log_file.close()
LOG_FILE_NAME = "ipfix-rita-log.txt"
PCAP_FILE_NAME = "ipfix-data.pcap"
ARCHIVE_NAME = "ipfix-rita-debug"
WAIT_MINUTES = 5 # How long to wait for the detection of ipfix data/ errors
MONITOR_MINUTES = 5 # How long to record ipfix data/ the error log
def main():
print(
"This script will aid you in collecting diagnostic information from IPFIX-RITA."
)
print(
"First, the script will ensure that traffic is being received on UDP port 2055 and begin a packet capture."
)
print(
"Next, the script will restart ipfix-rita, record the application log, and look for errors."
)
print("")
if os.geteuid() != 0:
print("This script requires administrator privileges.")
return 1
if shutil.which("ipfix-rita") is None:
print("IPFIX-RITA is not installed.")
return 1
if shutil.which("tcpdump") is None:
print("tcpdump is not installed")
self.exception_encountered.set()
return 1
ipfix_iface = input(
"Which interface is being used to collect Netflow/ IPFIX data? "
)
print("")
with tempfile.TemporaryDirectory() as tmp_dir_path:
try:
archive_folder = os.path.join(tmp_dir_path, ARCHIVE_NAME)
os.mkdir(archive_folder, 0o0755)
pcap_file_path = os.path.join(archive_folder, PCAP_FILE_NAME)
tcpdump_monitor = TCPDump_Monitor(pcap_file_path, ipfix_iface)
print(
"Monitoring {0} for UDP data on port 2055...".format(
ipfix_iface
)
)
print(
"The monitor will wait up to {0} minutes for data to arrive.".format(
WAIT_MINUTES
)
)
tcpdump_data_or_exception_event = OrEvent(
tcpdump_monitor.data_found,
tcpdump_monitor.exception_encountered,
)
tcpdump_monitor.start()
if not tcpdump_data_or_exception_event.wait(timeout=60 * WAIT_MINUTES):
print(
"No UDP data was found on port 2055 on the interface {0}.".format(
ipfix_iface
)
)
print(
"The script can not continue without IPFIX/ Netflow v9 data."
)
tcpdump_monitor.stop()
tcpdump_monitor.join()
return 1
elif tcpdump_monitor.exception_encountered.is_set():
tcpdump_monitor.stop()
tcpdump_monitor.join()
return 1
assert tcpdump_monitor.data_found.is_set()
except (KeyboardInterrupt, SystemExit):
print("Stopping the IPFIX-RITA debug script...")
tcpdump_monitor.stop()
tcpdump_monitor.join()
return 1
except Exception as e:
print(e)
tcpdump_monitor.stop()
tcpdump_monitor.join()
return 1
print("UDP data was found on port 2055 on {0}.".format(ipfix_iface))
print(
"TCPDump will begin recording UDP data on port 2055 on the interface {0}.".format(
ipfix_iface
)
)
print("")
try:
log_file_path = os.path.join(archive_folder, LOG_FILE_NAME)
ipfix_rita_monitor = IPFIX_RITA_Monitor(log_file_path)
print(
"Restarting IPFIX-RITA and monitoring the application log for errors..."
)
print(
"The script will wait for up to {0} minutes for an error to occur.".format(
WAIT_MINUTES
)
)
ipfixErrOrExceptionEvent = OrEvent(
ipfix_rita_monitor.error_found,
ipfix_rita_monitor.exception_encountered
)
ipfix_rita_monitor.start()
if not ipfixErrOrExceptionEvent.wait(timeout=WAIT_MINUTES * 60):
print("No errors were found! Please check if RITA has received any data by")
print("running `rita show-databases` and looking for new results.")
print("If RITA has successfully received data from IPFIX-RITA and your")
print("IPFIX/ Netflow v9 device is not listed under the compatibility matrix")
print("in the main README.md, please contact [email protected],")
print("and we will add your device to the list.")
print("")
print("Thank you for your time.")
tcpdump_monitor.stop()
tcpdump_monitor.join()
ipfix_rita_monitor.stop()
ipfix_rita_monitor.join()
return 0
elif ipfix_rita_monitor.exception_encountered.is_set():
tcpdump_monitor.stop()
tcpdump_monitor.join()
ipfix_rita_monitor.stop()
ipfix_rita_monitor.join()
return 1
assert ipfix_rita_monitor.error_found.is_set()
print("An error was found in the IPFIX-RITA logs.")
print(
"Monitoring IPFIX-RITA for more errors for {0} minutes...".format(
MONITOR_MINUTES
)
)
time.sleep(MONITOR_MINUTES * 60)
except (KeyboardInterrupt, SystemExit):
print("Stopping the IPFIX-RITA debug script...")
# The finally will execute before the return
return 1
except Exception as e:
print(e)
# the finally will execute before the return
return 1
finally:
tcpdump_monitor.stop()
tcpdump_monitor.join()
ipfix_rita_monitor.stop()
ipfix_rita_monitor.join()
print("")
print("TCPDump and IPFIX-RITA have been stopped.")
print("The script will now package the results.")
try:
subprocess.check_call(
["tar", "-C", tmp_dir_path, "-czf", "{0}.tgz".format(ARCHIVE_NAME), ARCHIVE_NAME]
)
except subprocess.CalledProcessError:
print(
"Could not create tarball containing the collected debug files"
)
return 1
print(
"Please email {0}.tgz along with a description of the settings and model of your IPFIX/ Netflow v9".format(
ARCHIVE_NAME
)
)
print(
"device to [email protected] for further assistance."
)
print("")
print(
"Thank you for your time."
)
return 0
if __name__ == "__main__":
main()