forked from thinhhoangpham/tcp_timearcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_data_loader_streaming.py
More file actions
1320 lines (1170 loc) · 56.1 KB
/
tcp_data_loader_streaming.py
File metadata and controls
1320 lines (1170 loc) · 56.1 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
TCP Data Loader - Streaming/Memory-Efficient Version (v2.0)
MEMORY-OPTIMIZED: Processes large CSV files in chunks to avoid out-of-memory errors.
Key differences from tcp_data_loader_chunked.py:
- Reads CSV in chunks (default 500k rows) instead of loading entire file
- Writes packets.csv incrementally during processing
- Detects flows incrementally, keeping only active flows in memory
- Completes flows on FIN/RST or timeout, freeing memory immediately
- Memory usage: ~200MB vs. 10-20GB for large files (98% reduction)
Generates the same chunked folder structure as v2.0:
- packets.csv: All packets for timearcs visualization
- flows/: Directory containing chunked flow files (multiple flows per file)
- flows/flows_index.json: Index of all flows with chunk references
- ips/ip_stats.json: IP statistics for sidebar
- ips/flag_stats.json: Flag statistics for sidebar
- ips/unique_ips.json: List of unique IP addresses
- indices/bins.json: Time-based bins for range queries
- manifest.json: Metadata about the dataset (version 2.0)
"""
import pandas as pd
import numpy as np
import json
import sys
import argparse
from pathlib import Path
from collections import defaultdict
import time
import random
# TCP flag constants
FIN, SYN, RST, PSH, ACK, URG, ECE, CWR = 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80
def load_ip_mapping(ip_map_file):
"""Load IP mapping from JSON file"""
try:
with open(ip_map_file, 'r') as f:
ip_map = json.load(f)
# Create reverse mapping (int -> ip_str)
int_to_ip = {v: k for k, v in ip_map.items()}
return ip_map, int_to_ip
except Exception as e:
print(f"Error loading IP mapping: {e}", file=sys.stderr)
return {}, {}
def classify_tcp_flags(flag_val):
"""Classify TCP flags into readable format"""
if pd.isna(flag_val):
return "INVALID"
try:
flag_val = int(flag_val)
except:
return "INVALID"
# TCP flag constants
flags = {
"FIN": 0x01, "SYN": 0x02, "RST": 0x04, "PSH": 0x08,
"ACK": 0x10, "URG": 0x20, "ECE": 0x40, "CWR": 0x80
}
# Common combinations
combinations = {
(flags["SYN"] | flags["ACK"]): "SYN+ACK",
(flags["FIN"] | flags["ACK"]): "FIN+ACK",
(flags["PSH"] | flags["ACK"]): "PSH+ACK",
(flags["RST"] | flags["ACK"]): "RST+ACK",
}
if flag_val in combinations:
return combinations[flag_val]
# Individual flags
set_flags = [name for name, val in flags.items() if flag_val & val]
if set_flags:
return "+".join(sorted(set_flags))
return "NONE" if flag_val == 0 else f"OTHER_{flag_val}"
def _safe_int(val, default=0):
"""Safely convert to int, handling NaN/None/empty."""
try:
import pandas as _pd
if _pd.isna(val):
return default
except Exception:
pass
try:
return int(val)
except Exception:
return default
def _is_set(flags: int, mask: int) -> bool:
try:
return (int(flags) & mask) != 0
except Exception:
return False
def process_single_flow(connection_key, connection_packets, flow_id):
"""
Process a single TCP connection's packets into a flow object.
Extracted from detect_tcp_flows() for use in incremental processing.
Args:
connection_key: Bidirectional connection identifier
connection_packets: List of packets for this connection (sorted by timestamp)
flow_id: Flow identifier string (e.g., "flow_000123")
Returns:
dict: Flow object with all TCP state machine processing complete
"""
# Sort packets by timestamp
connection_packets.sort(key=lambda a: a['timestamp'])
# Initialize flow with given ID
flow = {
'id': flow_id,
'key': connection_key,
'initiator': None,
'responder': None,
'initiatorPort': None,
'responderPort': None,
'state': 'new',
'phases': {
'establishment': [],
'dataTransfer': [],
'closing': []
},
'establishmentComplete': False,
'dataTransferStarted': False,
'closingStarted': False,
'closeType': None,
'startTime': None,
'endTime': None,
'totalPackets': 0,
'totalBytes': 0,
'invalidReason': None,
'expectedSeqNum': None,
'expectedAckNum': None,
'invalidPacket': None,
'synPacket': None,
'synAckPacket': None,
'packets': [] # Store all packets for this flow
}
# Set computed values
flow['startTime'] = connection_packets[0]['timestamp']
flow['endTime'] = connection_packets[-1]['timestamp']
flow['totalPackets'] = len(connection_packets)
flow['totalBytes'] = sum((p.get('length') or 0) for p in connection_packets)
# Process packets in chronological order
for packet in connection_packets:
flags = packet['flags']
syn = (flags & 0x02) != 0
ack = (flags & 0x10) != 0
fin = (flags & 0x01) != 0
rst = (flags & 0x04) != 0
psh = (flags & 0x08) != 0
# Add packet to flow's packet list
flow['packets'].append(packet)
# Skip processing if connection is already marked as invalid
if flow['state'] == 'invalid':
continue
# Process TCP state machine
if syn and not ack and not rst:
# SYN packet - connection initiation
if not flow['initiator']:
flow['initiator'] = packet['src_ip']
flow['responder'] = packet['dst_ip']
flow['initiatorPort'] = packet['src_port']
flow['responderPort'] = packet['dst_port']
flow['state'] = 'establishing'
flow['synPacket'] = packet
flow['expectedAckNum'] = packet['seq_num'] + 1
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn',
'description': 'Connection Request'
})
elif syn and ack and not rst:
# SYN+ACK packet - connection acceptance
if flow['state'] == 'establishing' and flow.get('synPacket'):
# Validate SYN+ACK acknowledgment number
if packet['ack_num'] == flow['expectedAckNum']:
flow['synAckPacket'] = packet
flow['expectedSeqNum'] = packet['seq_num'] + 1
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn_ack',
'description': 'Connection Acceptance'
})
else:
# Invalid SYN+ACK - wrong acknowledgment number
flow['state'] = 'invalid'
flow['invalidReason'] = 'invalid_synack'
flow['invalidPacket'] = packet
flow['closeType'] = 'invalid'
break
elif not flow.get('synAckPacket'):
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn_ack',
'description': 'Connection Acceptance'
})
flow['synAckPacket'] = packet
elif ack and not syn and not fin and not rst and not psh and flow['state'] == 'establishing':
# Pure ACK packet - establishment completion
if flow.get('synAckPacket') and flow.get('expectedSeqNum'):
# Validate final ACK
if packet['ack_num'] == flow['expectedSeqNum'] and packet['seq_num'] == flow['expectedAckNum']:
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'ack',
'description': 'Connection Established'
})
flow['establishmentComplete'] = True
flow['state'] = 'established'
else:
# Invalid ACK - wrong sequence/acknowledgment numbers
flow['state'] = 'invalid'
flow['invalidReason'] = 'invalid_ack'
flow['invalidPacket'] = packet
flow['closeType'] = 'invalid'
break
elif not flow['establishmentComplete']:
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'ack',
'description': 'Connection Established'
})
flow['establishmentComplete'] = True
flow['state'] = 'established'
elif (ack and not syn and not fin and not rst and flow['establishmentComplete'] and
((packet.get('length') and packet['length'] > 0) or (packet.get('seg_len') and packet['seg_len'] > 0))):
# Data transfer: any ACK packet with payload
if not flow['dataTransferStarted']:
flow['dataTransferStarted'] = True
flow['state'] = 'data_transfer'
flow['phases']['dataTransfer'].append({
'packet': packet,
'phase': 'data',
'description': 'Data Transfer'
})
elif fin and not rst:
# FIN packet - graceful close initiation
if not flow['closingStarted']:
flow['closingStarted'] = True
flow['state'] = 'closing'
flow['closeType'] = 'graceful'
flow['phases']['closing'].append({
'packet': packet,
'phase': 'fin',
'description': 'Close Request'
})
elif rst:
# RST packet - abortive close
if flow['state'] == 'establishing':
flow['invalidReason'] = 'rst_during_handshake'
flow['state'] = 'invalid'
flow['closeType'] = 'invalid'
else:
flow['state'] = 'aborted'
flow['closeType'] = 'abortive'
flow['invalidPacket'] = packet
flow['phases']['closing'].append({
'packet': packet,
'phase': 'rst',
'description': 'Connection Aborted'
})
elif ack and not syn and not fin and not rst and flow['establishmentComplete']:
# Other ACK packets
if flow['closingStarted']:
flow['phases']['closing'].append({
'packet': packet,
'phase': 'ack_close',
'description': 'Close Acknowledgment'
})
else:
if not flow['dataTransferStarted']:
flow['dataTransferStarted'] = True
flow['state'] = 'data_transfer'
flow['phases']['dataTransfer'].append({
'packet': packet,
'phase': 'ack_data',
'description': 'Data Acknowledgment'
})
# Final flow state validation
if flow['state'] == 'establishing':
# Incomplete handshake
if not flow.get('synPacket'):
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_syn'
flow['closeType'] = 'invalid'
elif not flow.get('synAckPacket'):
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_synack'
flow['closeType'] = 'invalid'
elif not flow['establishmentComplete']:
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_ack'
flow['closeType'] = 'invalid'
elif flow['state'] == 'closing':
flow['state'] = 'closed'
# Mark ongoing flows explicitly
if (
flow['state'] not in ('invalid', 'closed', 'aborted')
and not flow.get('closeType')
and (flow.get('establishmentComplete') or flow.get('dataTransferStarted'))
):
flow['state'] = 'ongoing'
flow['ongoing'] = True
flow['closeType'] = 'open'
return flow
def detect_tcp_flows_incremental(chunk_records, connection_map, ip_stats, flag_stats,
ip_pair_map, flow_counter, flow_timeout_seconds=300):
"""
Incrementally detect TCP flows from a chunk of packet records.
Maintains state across chunks via connection_map.
Args:
chunk_records: Current chunk of packets to process
connection_map: Persistent connection state (modified in place)
ip_stats: IP statistics accumulator (modified in place)
flag_stats: Flag statistics accumulator (modified in place)
ip_pair_map: IP pair statistics (modified in place)
flow_counter: Current flow ID counter
flow_timeout_seconds: Mark flows inactive after N seconds without packets (default: 300)
Returns:
tuple: (completed_flows, updated_flow_counter)
"""
# Helper functions for IP stats (same as detect_tcp_flows)
def update_ip_stats(ip_from, ip_to, length, ts):
s = ip_stats[ip_from]
s['sent_packets'] = (s.get('sent_packets') or 0) + 1
s['sent_bytes'] = (s.get('sent_bytes') or 0) + max(0, int(length or 0))
s['first_ts'] = ts if s['first_ts'] is None else min(s['first_ts'], ts)
s['last_ts'] = ts if s['last_ts'] is None else max(s['last_ts'], ts)
r = ip_stats[ip_to]
r['recv_packets'] = (r.get('recv_packets') or 0) + 1
r['recv_bytes'] = (r.get('recv_bytes') or 0) + max(0, int(length or 0))
r['first_ts'] = ts if r['first_ts'] is None else min(r['first_ts'], ts)
r['last_ts'] = ts if r['last_ts'] is None else max(r['last_ts'], ts)
def update_ip_pair(src_ip, dst_ip, length, ts):
a, b = sorted([str(src_ip), str(dst_ip)])
key = (a, b)
entry = ip_pair_map.get(key)
if not entry:
entry = {
'ip1': a, 'ip2': b,
'packet_count': 0,
'a_to_b_packets': 0,
'b_to_a_packets': 0,
'a_to_b_bytes': 0,
'b_to_a_bytes': 0,
'first_ts': ts,
'last_ts': ts
}
ip_pair_map[key] = entry
entry['packet_count'] = (entry.get('packet_count') or 0) + 1
entry['first_ts'] = min(entry['first_ts'], ts)
entry['last_ts'] = max(entry['last_ts'], ts)
if str(src_ip) == a:
entry['a_to_b_packets'] = (entry.get('a_to_b_packets') or 0) + 1
entry['a_to_b_bytes'] = (entry.get('a_to_b_bytes') or 0) + max(0, int(length or 0))
else:
entry['b_to_a_packets'] = (entry.get('b_to_a_packets') or 0) + 1
entry['b_to_a_bytes'] = (entry.get('b_to_a_bytes') or 0) + max(0, int(length or 0))
# Process current chunk: update IP stats and group packets by connection
for packet in chunk_records:
# Update IP statistics
ts = int(packet.get('timestamp', 0))
s_ip = str(packet.get('src_ip', ''))
d_ip = str(packet.get('dst_ip', ''))
length = int(packet.get('length', 0))
flag_type = str(packet.get('flag_type', 'UNKNOWN'))
flag_stats[flag_type] = flag_stats.get(flag_type, 0) + 1
update_ip_stats(s_ip, d_ip, length, ts)
update_ip_pair(s_ip, d_ip, length, ts)
# Group packets by connection (bidirectional)
if packet.get('src_port') and packet.get('dst_port') and s_ip and d_ip:
connection_a = f"{s_ip}:{packet['src_port']}-{d_ip}:{packet['dst_port']}"
connection_b = f"{d_ip}:{packet['dst_port']}-{s_ip}:{packet['src_port']}"
connection_key = connection_a if connection_a < connection_b else connection_b
# Initialize or update connection state
if connection_key not in connection_map:
flow_counter += 1
connection_map[connection_key] = {
'packets': [],
'flow_id': f"flow_{flow_counter:06d}",
'last_packet_time': ts, # Track time in microseconds
'has_fin_or_rst': False
}
conn_data = connection_map[connection_key]
conn_data['packets'].append(packet)
conn_data['last_packet_time'] = ts # Update to most recent packet time
# Check if packet has FIN or RST flag
flags = packet.get('flags', 0)
if (flags & 0x01) or (flags & 0x04): # FIN or RST
conn_data['has_fin_or_rst'] = True
# Identify completed flows (FIN/RST or timeout)
# Find the latest timestamp in this chunk for timeout calculation
if chunk_records:
latest_timestamp = max(r['timestamp'] for r in chunk_records)
else:
latest_timestamp = 0
completed_flows = []
connections_to_remove = []
timed_out_count = 0
for conn_key, conn_data in connection_map.items():
# Calculate inactivity time in seconds
time_diff_microseconds = latest_timestamp - conn_data['last_packet_time']
inactive_seconds = time_diff_microseconds / 1_000_000 # Convert to seconds
has_explicit_close = conn_data['has_fin_or_rst']
has_timed_out = inactive_seconds >= flow_timeout_seconds
is_complete = has_explicit_close or has_timed_out
if is_complete:
# Process flow using helper function
flow = process_single_flow(conn_key, conn_data['packets'], conn_data['flow_id'])
# Mark if flow was completed by timeout (for statistics)
if has_timed_out and not has_explicit_close:
flow['completed_by_timeout'] = True
timed_out_count += 1
completed_flows.append(flow)
connections_to_remove.append(conn_key)
# Remove completed flows from active connection map
for conn_key in connections_to_remove:
del connection_map[conn_key]
return completed_flows, flow_counter, timed_out_count
def detect_tcp_flows(records):
"""
Detect TCP flows from packet records.
Returns flows with full packet details for individual flow files.
"""
# Aggregates for IP stats
ip_pair_map = {}
ip_stats = defaultdict(lambda: {
'sent_packets': 0, 'recv_packets': 0,
'sent_bytes': 0, 'recv_bytes': 0,
'first_ts': None, 'last_ts': None
})
flag_stats = defaultdict(int)
def update_ip_stats(ip_from, ip_to, length, ts):
s = ip_stats[ip_from]
s['sent_packets'] = (s.get('sent_packets') or 0) + 1
s['sent_bytes'] = (s.get('sent_bytes') or 0) + max(0, int(length or 0))
s['first_ts'] = ts if s['first_ts'] is None else min(s['first_ts'], ts)
s['last_ts'] = ts if s['last_ts'] is None else max(s['last_ts'], ts)
r = ip_stats[ip_to]
r['recv_packets'] = (r.get('recv_packets') or 0) + 1
r['recv_bytes'] = (r.get('recv_bytes') or 0) + max(0, int(length or 0))
r['first_ts'] = ts if r['first_ts'] is None else min(r['first_ts'], ts)
r['last_ts'] = ts if r['last_ts'] is None else max(r['last_ts'], ts)
def update_ip_pair(src_ip, dst_ip, length, ts):
a, b = sorted([str(src_ip), str(dst_ip)])
key = (a, b)
entry = ip_pair_map.get(key)
if not entry:
entry = {
'ip1': a, 'ip2': b,
'packet_count': 0,
'a_to_b_packets': 0,
'b_to_a_packets': 0,
'a_to_b_bytes': 0,
'b_to_a_bytes': 0,
'first_ts': ts,
'last_ts': ts
}
ip_pair_map[key] = entry
entry['packet_count'] = (entry.get('packet_count') or 0) + 1
entry['first_ts'] = min(entry['first_ts'], ts)
entry['last_ts'] = max(entry['last_ts'], ts)
if str(src_ip) == a:
entry['a_to_b_packets'] = (entry.get('a_to_b_packets') or 0) + 1
entry['a_to_b_bytes'] = (entry.get('a_to_b_bytes') or 0) + max(0, int(length or 0))
else:
entry['b_to_a_packets'] = (entry.get('b_to_a_packets') or 0) + 1
entry['b_to_a_bytes'] = (entry.get('b_to_a_bytes') or 0) + max(0, int(length or 0))
# Build aggregates from all TCP records
for pkt in records:
ts = int(pkt.get('timestamp', 0))
s_ip = str(pkt.get('src_ip', ''))
d_ip = str(pkt.get('dst_ip', ''))
length = int(pkt.get('length', 0))
flag_type = str(pkt.get('flag_type', 'UNKNOWN'))
flag_stats[flag_type] += 1
update_ip_stats(s_ip, d_ip, length, ts)
update_ip_pair(s_ip, d_ip, length, ts)
# Detect flows
flows = []
connection_map = {}
# Group packets by connection
for packet in records:
if packet.get('src_port') and packet.get('dst_port') and packet.get('src_ip') and packet.get('dst_ip'):
# Create bidirectional connection key
connection_a = f"{packet['src_ip']}:{packet['src_port']}-{packet['dst_ip']}:{packet['dst_port']}"
connection_b = f"{packet['dst_ip']}:{packet['dst_port']}-{packet['src_ip']}:{packet['src_port']}"
connection_key = connection_a if connection_a < connection_b else connection_b
if connection_key not in connection_map:
connection_map[connection_key] = []
connection_map[connection_key].append(packet)
# Process each connection
flow_counter = 0
for connection_key, connection_packets in connection_map.items():
# Sort packets by timestamp
connection_packets.sort(key=lambda a: a['timestamp'])
flow_counter += 1
# Initialize flow with simple ID
flow = {
'id': f"flow_{flow_counter:06d}",
'key': connection_key,
'initiator': None,
'responder': None,
'initiatorPort': None,
'responderPort': None,
'state': 'new',
'phases': {
'establishment': [],
'dataTransfer': [],
'closing': []
},
'establishmentComplete': False,
'dataTransferStarted': False,
'closingStarted': False,
'closeType': None,
'startTime': None,
'endTime': None,
'totalPackets': 0,
'totalBytes': 0,
'invalidReason': None,
'expectedSeqNum': None,
'expectedAckNum': None,
'invalidPacket': None,
'synPacket': None,
'synAckPacket': None,
'packets': [] # Store all packets for this flow
}
# Set computed values
flow['startTime'] = connection_packets[0]['timestamp']
flow['endTime'] = connection_packets[-1]['timestamp']
flow['totalPackets'] = len(connection_packets)
flow['totalBytes'] = sum((p.get('length') or 0) for p in connection_packets)
# Process packets in chronological order
for packet in connection_packets:
flags = packet['flags']
syn = (flags & 0x02) != 0
ack = (flags & 0x10) != 0
fin = (flags & 0x01) != 0
rst = (flags & 0x04) != 0
psh = (flags & 0x08) != 0
# Add packet to flow's packet list
flow['packets'].append(packet)
# Skip processing if connection is already marked as invalid
if flow['state'] == 'invalid':
continue
# Process TCP state machine
if syn and not ack and not rst:
# SYN packet - connection initiation
if not flow['initiator']:
flow['initiator'] = packet['src_ip']
flow['responder'] = packet['dst_ip']
flow['initiatorPort'] = packet['src_port']
flow['responderPort'] = packet['dst_port']
flow['state'] = 'establishing'
flow['synPacket'] = packet
flow['expectedAckNum'] = packet['seq_num'] + 1
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn',
'description': 'Connection Request'
})
elif syn and ack and not rst:
# SYN+ACK packet - connection acceptance
if flow['state'] == 'establishing' and flow.get('synPacket'):
# Validate SYN+ACK acknowledgment number
if packet['ack_num'] == flow['expectedAckNum']:
flow['synAckPacket'] = packet
flow['expectedSeqNum'] = packet['seq_num'] + 1
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn_ack',
'description': 'Connection Acceptance'
})
else:
# Invalid SYN+ACK - wrong acknowledgment number
flow['state'] = 'invalid'
flow['invalidReason'] = 'invalid_synack'
flow['invalidPacket'] = packet
flow['closeType'] = 'invalid'
break
elif not flow.get('synAckPacket'):
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'syn_ack',
'description': 'Connection Acceptance'
})
flow['synAckPacket'] = packet
elif ack and not syn and not fin and not rst and not psh and flow['state'] == 'establishing':
# Pure ACK packet - establishment completion
if flow.get('synAckPacket') and flow.get('expectedSeqNum'):
# Validate final ACK
if packet['ack_num'] == flow['expectedSeqNum'] and packet['seq_num'] == flow['expectedAckNum']:
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'ack',
'description': 'Connection Established'
})
flow['establishmentComplete'] = True
flow['state'] = 'established'
else:
# Invalid ACK - wrong sequence/acknowledgment numbers
flow['state'] = 'invalid'
flow['invalidReason'] = 'invalid_ack'
flow['invalidPacket'] = packet
flow['closeType'] = 'invalid'
break
elif not flow['establishmentComplete']:
flow['phases']['establishment'].append({
'packet': packet,
'phase': 'ack',
'description': 'Connection Established'
})
flow['establishmentComplete'] = True
flow['state'] = 'established'
elif (ack and not syn and not fin and not rst and flow['establishmentComplete'] and
((packet.get('length') and packet['length'] > 0) or (packet.get('seg_len') and packet['seg_len'] > 0))):
# Data transfer: any ACK packet with payload
if not flow['dataTransferStarted']:
flow['dataTransferStarted'] = True
flow['state'] = 'data_transfer'
flow['phases']['dataTransfer'].append({
'packet': packet,
'phase': 'data',
'description': 'Data Transfer'
})
elif fin and not rst:
# FIN packet - graceful close initiation
if not flow['closingStarted']:
flow['closingStarted'] = True
flow['state'] = 'closing'
flow['closeType'] = 'graceful'
flow['phases']['closing'].append({
'packet': packet,
'phase': 'fin',
'description': 'Close Request'
})
elif rst:
# RST packet - abortive close
if flow['state'] == 'establishing':
flow['invalidReason'] = 'rst_during_handshake'
flow['state'] = 'invalid'
flow['closeType'] = 'invalid'
else:
flow['state'] = 'aborted'
flow['closeType'] = 'abortive'
flow['invalidPacket'] = packet
flow['phases']['closing'].append({
'packet': packet,
'phase': 'rst',
'description': 'Connection Aborted'
})
elif ack and not syn and not fin and not rst and flow['establishmentComplete']:
# Other ACK packets
if flow['closingStarted']:
flow['phases']['closing'].append({
'packet': packet,
'phase': 'ack_close',
'description': 'Close Acknowledgment'
})
else:
if not flow['dataTransferStarted']:
flow['dataTransferStarted'] = True
flow['state'] = 'data_transfer'
flow['phases']['dataTransfer'].append({
'packet': packet,
'phase': 'ack_data',
'description': 'Data Acknowledgment'
})
# Final flow state validation
if flow['state'] == 'establishing':
# Incomplete handshake
if not flow.get('synPacket'):
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_syn'
flow['closeType'] = 'invalid'
elif not flow.get('synAckPacket'):
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_synack'
flow['closeType'] = 'invalid'
elif not flow['establishmentComplete']:
flow['state'] = 'invalid'
flow['invalidReason'] = 'incomplete_no_ack'
flow['closeType'] = 'invalid'
elif flow['state'] == 'closing':
flow['state'] = 'closed'
# Mark ongoing flows explicitly
if (
flow['state'] not in ('invalid', 'closed', 'aborted')
and not flow.get('closeType')
and (flow.get('establishmentComplete') or flow.get('dataTransferStarted'))
):
flow['state'] = 'ongoing'
flow['ongoing'] = True
flow['closeType'] = 'open'
flows.append(flow)
# Convert aggregates to output format
ip_pairs = list(ip_pair_map.values())
ip_stats_out = {ip: s for ip, s in ip_stats.items()}
return flows, ip_pairs, ip_stats_out, dict(flag_stats)
def write_flow_chunk(flows_to_write, chunk_idx, flows_dir, flows_index):
"""
Write a chunk of flows to disk and update the flows index.
Args:
flows_to_write: List of flow objects to write
chunk_idx: Chunk file number
flows_dir: Directory to write chunk files
flows_index: List to append flow summaries to (modified in place)
"""
chunk_filename = f"chunk_{chunk_idx:05d}.json"
chunk_file = flows_dir / chunk_filename
# Write chunk file
with open(chunk_file, 'w') as f:
json.dump(flows_to_write, f, indent=2)
# Add flows to index
for local_idx, flow in enumerate(flows_to_write):
flow_summary = {
'id': flow['id'],
'key': flow['key'],
'initiator': flow['initiator'],
'responder': flow['responder'],
'initiatorPort': flow['initiatorPort'],
'responderPort': flow['responderPort'],
'state': flow['state'],
'closeType': flow['closeType'],
'startTime': flow['startTime'],
'endTime': flow['endTime'],
'totalPackets': flow['totalPackets'],
'totalBytes': flow['totalBytes'],
'establishmentComplete': flow['establishmentComplete'],
'dataTransferStarted': flow['dataTransferStarted'],
'closingStarted': flow['closingStarted'],
'invalidReason': flow['invalidReason'],
'ongoing': flow.get('ongoing', False),
'establishment_packets': len(flow['phases']['establishment']),
'data_transfer_packets': len(flow['phases']['dataTransfer']),
'closing_packets': len(flow['phases']['closing']),
'chunk_file': chunk_filename,
'chunk_index': local_idx
}
flows_index.append(flow_summary)
return chunk_filename
def generate_time_bins(records, num_bins=100):
"""Generate time-based bins for range queries"""
if not records:
return []
timestamps = [r['timestamp'] for r in records]
min_ts = min(timestamps)
max_ts = max(timestamps)
if min_ts == max_ts:
return [{'bin': 0, 'start': min_ts, 'end': max_ts, 'count': len(records)}]
bin_width = (max_ts - min_ts) / num_bins
bins = []
for i in range(num_bins):
bin_start = min_ts + (i * bin_width)
bin_end = min_ts + ((i + 1) * bin_width)
# Count packets in this bin
count = sum(1 for ts in timestamps if bin_start <= ts < bin_end)
bins.append({
'bin': i,
'start': int(bin_start),
'end': int(bin_end),
'count': count
})
return bins
def process_tcp_data_chunked(data_files, ip_map_file, output_dir, max_records=None,
chunk_size=200, chunk_read_size=500000, flow_timeout_seconds=300,
filter_ips=None, filter_time_start=None, filter_time_end=None,
attack_context=None):
"""
Process TCP data and create chunked output structure (v2.0) - STREAMING VERSION
Memory-optimized: processes CSV in chunks to avoid loading entire file into memory.
Args:
data_files: Input CSV file path(s) - can be a single file or list of files
ip_map_file: IP mapping JSON file path
output_dir: Output directory path
max_records: Maximum records to process (None = all)
chunk_size: Flows per output chunk file (default: 200)
chunk_read_size: CSV rows per read chunk (default: 500000)
flow_timeout_seconds: Seconds of inactivity before flow timeout (default: 300)
filter_ips: Comma-separated list of IP IDs or dotted-quad IPs to filter (None = no filter)
filter_time_start: Filter packets with timestamp >= this value (microseconds since epoch, None = no filter)
filter_time_end: Filter packets with timestamp <= this value (microseconds since epoch, None = no filter)
attack_context: Attack type label for this subset (stored in manifest.json for UI display)
"""
# Normalize data_files to a list
if isinstance(data_files, str):
data_files = [data_files]
# Create output directory structure
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Create subdirectories
flows_dir = output_path / 'flows'
ips_dir = output_path / 'ips'
indices_dir = output_path / 'indices'
flows_dir.mkdir(exist_ok=True)
ips_dir.mkdir(exist_ok=True)
indices_dir.mkdir(exist_ok=True)
print(f"Loading IP mapping from {ip_map_file}...")
ip_map, int_to_ip = load_ip_mapping(ip_map_file)
# Parse filter IPs once at the start
ip_filter_set = None
if filter_ips:
ip_filter_set = set(filter_ips.split(','))
print(f"IP filter: {len(ip_filter_set)} IP(s) specified")
# Initialize filtering statistics
total_packets_before_filter = 0
total_packets_after_filter = 0
# Initialize streaming state
connection_map = {} # Active flows
all_completed_flows = [] # Buffer for completed flows (written when full)
ip_stats = defaultdict(lambda: {
'sent_packets': 0, 'recv_packets': 0,
'sent_bytes': 0, 'recv_bytes': 0,
'first_ts': None, 'last_ts': None
})
flag_stats = defaultdict(int)
ip_pair_map = {}
unique_ips = set()
all_timestamps = []
packets_file = output_path / 'packets.csv'
packets_written = False
chunk_number = 0
total_packets = 0
tcp_packets = 0
flow_counter = 0
# Early termination tracking for time-based filtering
consecutive_empty_chunks = 0
max_timestamp_seen = 0 # Track the highest timestamp we've encountered
can_terminate_early = False # Only allow early termination after passing filter_time_end
# Flow chunk writing state
flow_chunk_counter = 0
flows_index = []
total_flows_written = 0
# Helper function to convert IP columns (used for each chunk)
def _convert_ip_column(df_chunk, col_name):
if col_name not in df_chunk.columns:
return
series = df_chunk[col_name]
if series.dtype == object:
mask_numeric_like = series.str.fullmatch(r'\d+')
if mask_numeric_like is not None and mask_numeric_like.any():
numeric = pd.to_numeric(series.where(mask_numeric_like), errors='coerce')
mapped = []
for v in numeric:
if pd.isna(v):
mapped.append('')
continue
ival = int(v)
mapped.append(int_to_ip.get(ival, str(ival)))
series = series.mask(mask_numeric_like, pd.Series(mapped, index=series.index))
df_chunk[col_name] = series.fillna('').astype(str)
return
if series.dtype.kind in 'fi':
numeric = pd.to_numeric(series, errors='coerce')
out = []
for v in numeric:
if pd.isna(v):
out.append('')
continue
ival = int(v)
out.append(int_to_ip.get(ival, str(ival)))
df_chunk[col_name] = pd.Series(out, index=series.index).fillna('').astype(str)
else:
df_chunk[col_name] = series.astype(str).fillna('')
# Process each file sequentially
for file_idx, data_file in enumerate(data_files, start=1):
print(f"\n[{file_idx}/{len(data_files)}] Processing: {data_file}")
if not Path(data_file).exists():
print(f" Warning: File '{data_file}' not found, skipping...")
continue
# Determine compression
compression = 'gzip' if data_file.endswith('.gz') else None
# Process CSV in chunks
try:
csv_iterator = pd.read_csv(data_file, chunksize=chunk_read_size, compression=compression)
for df_chunk in csv_iterator:
chunk_number += 1
total_packets_before_filter += len(df_chunk)
# Robust timestamp cleaning for this chunk
if 'timestamp' in df_chunk.columns:
df_chunk['timestamp'] = pd.to_numeric(df_chunk['timestamp'], errors='coerce')
before_drop_count = len(df_chunk)
df_chunk = df_chunk[df_chunk['timestamp'].notna() & np.isfinite(df_chunk['timestamp'])]
dropped_count = before_drop_count - len(df_chunk)
if dropped_count > 0 and chunk_number == 1:
print(f"Note: Dropping rows with invalid timestamps (chunk 1: {dropped_count} dropped)")
# Track max timestamp BEFORE filtering (to detect when we've passed the time window)
if filter_time_end is not None and 'timestamp' in df_chunk.columns and len(df_chunk) > 0:
chunk_max_timestamp = df_chunk['timestamp'].max()
if pd.notna(chunk_max_timestamp):
if chunk_max_timestamp > max_timestamp_seen:
max_timestamp_seen = chunk_max_timestamp
# Enable early termination only after we've seen timestamps beyond filter_time_end
if max_timestamp_seen > filter_time_end:
can_terminate_early = True
# Apply time range filter BEFORE IP conversion (for performance)
if filter_time_start is not None:
df_chunk = df_chunk[df_chunk['timestamp'] >= filter_time_start]
if filter_time_end is not None:
df_chunk = df_chunk[df_chunk['timestamp'] <= filter_time_end]