summaryrefslogtreecommitdiff
path: root/examples/py-risky-flow-to-pcap/risky-flow-to-pcap.py
blob: 33c0be8103124df41f75134389ba047dfd99f045 (plain)
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
#!/usr/bin/env python3

import base64
import os
import sys

sys.path.append(os.path.dirname(sys.argv[0]) + '/../../dependencies')
import nDPIsrvd
from nDPIsrvd import TermColor, nDPIsrvdSocket, PcapPacket

def onJsonLineRecvd(json_dict, current_flow, global_user_data):
    if current_flow is None:
        return True

    PcapPacket.handleJSON(json_dict, current_flow)

    if 'flow_event_name' in json_dict and PcapPacket.isInitialized(current_flow) and \
        'ndpi' in json_dict and 'flow_risk' in json_dict['ndpi'] and not hasattr(current_flow, 'is_risky_flow'):

        current_flow.pcap_packet.doDump()
        current_flow.pcap_packet.setSuffix('risky')
        current_flow.is_risky_flow = True
        print('Risky flow with id {} marked for dumping.'.format(current_flow.flow_id))

    if hasattr(current_flow, 'is_risky_flow') and \
        (current_flow.pcap_packet.current_packet < current_flow.pcap_packet.max_packets or \
         ('flow_event_name' in json_dict and \
          (json_dict['flow_event_name'] == 'end' or json_dict['flow_event_name'] == 'idle'))):

        try:
            if current_flow.pcap_packet.fin() is True:
                print('Risky flow with id {} dumped.'.format(current_flow.flow_id))
        except RuntimeError as err:
            pass

    return True

if __name__ == '__main__':
    argparser = nDPIsrvd.defaultArgumentParser()
    args = argparser.parse_args()
    address = nDPIsrvd.validateAddress(args)

    sys.stderr.write('Recv buffer size: {}\n'.format(nDPIsrvd.NETWORK_BUFFER_MAX_SIZE))
    sys.stderr.write('Connecting to {} ..\n'.format(address[0]+':'+str(address[1]) if type(address) is tuple else address))

    nsock = nDPIsrvdSocket()
    nsock.connect(address)
    nsock.loop(onJsonLineRecvd, None)