2017-10-28 19:00:18 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2017-10-29 11:52:59 +01:00
|
|
|
"""
|
2019-03-31 20:51:34 +02:00
|
|
|
Example analyzing script for saved exports (by main.py, as JSON).
|
|
|
|
This file belongs to https://github.com/bitkeks/python-netflow-v9-softflowd.
|
2017-10-29 11:52:59 +01:00
|
|
|
|
2019-03-31 20:51:34 +02:00
|
|
|
Copyright 2017-2019 Dominik Pataky <dev@bitkeks.eu>
|
2017-10-29 11:52:59 +01:00
|
|
|
Licensed under MIT License. See LICENSE.
|
|
|
|
"""
|
2017-10-28 19:00:18 +02:00
|
|
|
|
2019-10-05 09:06:06 +02:00
|
|
|
import argparse
|
|
|
|
from collections import namedtuple
|
|
|
|
import contextlib
|
2017-10-28 19:00:18 +02:00
|
|
|
from datetime import datetime
|
2019-10-05 09:06:06 +02:00
|
|
|
import functools
|
2017-10-28 19:00:18 +02:00
|
|
|
import ipaddress
|
|
|
|
import json
|
2017-10-29 11:52:59 +01:00
|
|
|
import socket
|
2019-10-05 09:06:06 +02:00
|
|
|
import sys
|
2018-02-20 12:09:10 +01:00
|
|
|
|
|
|
|
|
2019-10-05 09:06:06 +02:00
|
|
|
Pair = namedtuple('Pair', ['src', 'dest'])
|
2017-10-29 11:52:59 +01:00
|
|
|
|
|
|
|
|
2019-10-31 17:35:15 +01:00
|
|
|
@functools.lru_cache(maxsize=128)
|
2019-10-05 09:06:06 +02:00
|
|
|
def resolve_hostname(ip):
|
|
|
|
return socket.getfqdn(ip)
|
2017-10-29 11:52:59 +01:00
|
|
|
|
2019-10-17 05:23:51 +02:00
|
|
|
|
|
|
|
def fallback(d, keys):
|
|
|
|
for k in keys:
|
|
|
|
try:
|
|
|
|
return d[k]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
raise KeyError(", ".join(keys))
|
|
|
|
|
|
|
|
|
2017-10-29 11:52:59 +01:00
|
|
|
class Connection:
|
|
|
|
"""Connection model for two flows.
|
|
|
|
The direction of the data flow can be seen by looking at the size.
|
|
|
|
|
|
|
|
'src' describes the peer which sends more data towards the other. This
|
2019-10-05 09:06:06 +02:00
|
|
|
does NOT have to mean that 'src' was the initiator of the connection.
|
2017-10-29 11:52:59 +01:00
|
|
|
"""
|
|
|
|
def __init__(self, flow1, flow2):
|
2019-10-05 09:06:06 +02:00
|
|
|
if not flow1 or not flow2:
|
|
|
|
raise Exception("A connection requires two flows")
|
|
|
|
|
2019-10-17 05:23:51 +02:00
|
|
|
# Assume the size that sent the most data is the source
|
2019-10-31 17:35:15 +01:00
|
|
|
# TODO: this might not always be right, maybe use earlier timestamp?
|
2019-10-17 05:23:51 +02:00
|
|
|
size1 = fallback(flow1, ['IN_BYTES', 'IN_OCTETS'])
|
|
|
|
size2 = fallback(flow2, ['IN_BYTES', 'IN_OCTETS'])
|
|
|
|
if size1 >= size2:
|
2017-10-29 11:52:59 +01:00
|
|
|
src = flow1
|
|
|
|
dest = flow2
|
|
|
|
else:
|
|
|
|
src = flow2
|
|
|
|
dest = flow1
|
|
|
|
|
2019-10-05 09:06:06 +02:00
|
|
|
ips = self.get_ips(src)
|
2017-10-29 11:52:59 +01:00
|
|
|
self.src = ips.src
|
|
|
|
self.dest = ips.dest
|
2019-10-17 05:23:51 +02:00
|
|
|
self.src_port = fallback(src, ['L4_SRC_PORT', 'SRC_PORT'])
|
2019-10-31 17:35:15 +01:00
|
|
|
self.dest_port = fallback(dest, ['L4_DST_PORT', 'DST_PORT'])
|
2019-10-17 05:23:51 +02:00
|
|
|
self.size = fallback(src, ['IN_BYTES', 'IN_OCTETS'])
|
2017-10-29 11:52:59 +01:00
|
|
|
|
2017-10-29 19:38:33 +01:00
|
|
|
# Duration is given in milliseconds
|
|
|
|
self.duration = src['LAST_SWITCHED'] - src['FIRST_SWITCHED']
|
|
|
|
if self.duration < 0:
|
|
|
|
# 32 bit int has its limits. Handling overflow here
|
2019-10-05 09:06:06 +02:00
|
|
|
# TODO: Should be handled in the collection phase
|
2017-10-29 19:38:33 +01:00
|
|
|
self.duration = (2**32 - src['FIRST_SWITCHED']) + src['LAST_SWITCHED']
|
|
|
|
|
2017-10-29 11:52:59 +01:00
|
|
|
def __repr__(self):
|
|
|
|
return "<Connection from {} to {}, size {}>".format(
|
|
|
|
self.src, self.dest, self.human_size)
|
|
|
|
|
2019-10-05 09:06:06 +02:00
|
|
|
@staticmethod
|
|
|
|
def get_ips(flow):
|
|
|
|
# TODO: These values should be parsed into strings in the collection phase.
|
|
|
|
# The floating point representation of an IPv6 address in JSON
|
|
|
|
# could lose precision.
|
|
|
|
|
|
|
|
# IPv4
|
2019-10-31 17:35:15 +01:00
|
|
|
if flow.get('IP_PROTOCOL_VERSION') == 4 \
|
|
|
|
or 'IPV4_SRC_ADDR' in flow \
|
|
|
|
or 'IPV4_DST_ADDR' in flow:
|
2019-10-05 09:06:06 +02:00
|
|
|
return Pair(
|
|
|
|
ipaddress.ip_address(flow['IPV4_SRC_ADDR']),
|
|
|
|
ipaddress.ip_address(flow['IPV4_DST_ADDR'])
|
|
|
|
)
|
|
|
|
|
|
|
|
# IPv6
|
|
|
|
return Pair(
|
|
|
|
ipaddress.ip_address(flow['IPV6_SRC_ADDR']),
|
|
|
|
ipaddress.ip_address(flow['IPV6_DST_ADDR'])
|
|
|
|
)
|
|
|
|
|
2017-10-29 11:52:59 +01:00
|
|
|
@property
|
|
|
|
def human_size(self):
|
|
|
|
# Calculate a human readable size of the traffic
|
|
|
|
if self.size < 1024:
|
2017-10-29 19:38:33 +01:00
|
|
|
return "%dB" % self.size
|
2017-10-29 11:52:59 +01:00
|
|
|
elif self.size / 1024. < 1024:
|
|
|
|
return "%.2fK" % (self.size / 1024.)
|
|
|
|
elif self.size / 1024.**2 < 1024:
|
|
|
|
return "%.2fM" % (self.size / 1024.**2)
|
|
|
|
else:
|
|
|
|
return "%.2fG" % (self.size / 1024.**3)
|
|
|
|
|
2017-10-29 19:38:33 +01:00
|
|
|
@property
|
|
|
|
def human_duration(self):
|
|
|
|
duration = self.duration // 1000 # uptime in milliseconds, floor it
|
|
|
|
if duration < 60:
|
|
|
|
# seconds
|
|
|
|
return "%d sec" % duration
|
|
|
|
if duration / 60 > 60:
|
|
|
|
# hours
|
|
|
|
return "%d:%02d.%02d hours" % (duration / 60**2, duration % 60**2 / 60, duration % 60)
|
|
|
|
# minutes
|
|
|
|
return "%02d:%02d min" % (duration / 60, duration % 60)
|
|
|
|
|
2017-10-29 11:52:59 +01:00
|
|
|
@property
|
|
|
|
def hostnames(self):
|
|
|
|
# Resolve the IPs of this flows to their hostname
|
2019-10-05 09:06:06 +02:00
|
|
|
src_hostname = resolve_hostname(self.src.compressed)
|
|
|
|
dest_hostname = resolve_hostname(self.dest.compressed)
|
2017-10-29 19:38:33 +01:00
|
|
|
return Pair(src_hostname, dest_hostname)
|
2017-10-29 11:52:59 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def service(self):
|
|
|
|
# Resolve ports to their services, if known
|
2019-10-05 09:06:06 +02:00
|
|
|
# Try source port, fallback to dest port, otherwise "unknown"
|
|
|
|
with contextlib.suppress(OSError):
|
|
|
|
return socket.getservbyport(self.src_port)
|
|
|
|
with contextlib.suppress(OSError):
|
|
|
|
return socket.getservbyport(self.dest_port)
|
|
|
|
return "unknown"
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
parser = argparse.ArgumentParser(description="Output a basic analysis of NetFlow data")
|
|
|
|
parser.add_argument('filename', nargs='?', type=argparse.FileType('r'),
|
|
|
|
default=sys.stdin,
|
|
|
|
help="The file to analyze (defaults to stdin if not provided)")
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
data = json.load(args.filename)
|
|
|
|
|
|
|
|
# Go through data and disect every flow saved inside the dump
|
|
|
|
for key in sorted(data):
|
|
|
|
timestamp = datetime.fromtimestamp(float(key)).strftime("%Y-%m-%d %H:%M.%S")
|
|
|
|
|
|
|
|
flows = data[key]
|
|
|
|
pending = None # Two flows normally appear together for duplex connection
|
|
|
|
for flow in flows:
|
|
|
|
if not pending:
|
|
|
|
pending = flow
|
|
|
|
continue
|
2017-10-29 11:52:59 +01:00
|
|
|
con = Connection(pending, flow)
|
2019-10-31 17:35:15 +01:00
|
|
|
print("{timestamp}: {service:7} | {size:8} | {duration:9} | {src_host} ({src}) to {dest_host} ({dest})" \
|
|
|
|
.format(timestamp=timestamp, service=con.service.upper(), src_host=con.hostnames.src, src=con.src,
|
|
|
|
dest_host=con.hostnames.dest, dest=con.dest, size=con.human_size, duration=con.human_duration))
|
2017-10-29 11:52:59 +01:00
|
|
|
pending = None
|