Repository navigation
Expand file tree
/
Copy pathcollector.py
More file actions
2203 lines (2017 loc) · 83.7 KB
/
Copy pathcollector.py
File metadata and controls
2203 lines (2017 loc) · 83.7 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
"""FlowSight — NetFlow/sFlow collector + destination-ASN delivery aggregator.
Classic capabilities: multi-router NetFlow v5/v9, IPFIX, sFlow, live IP/ASN
reports, attack alerts, report collection.
AS Traffic: aggregate by destination ASN per interface (ignore source IP),
flush every N minutes, hourly/daily/monthly share reports.
"""
from __future__ import annotations
import argparse
import asyncio
import ipaddress
import json
import socket
import sqlite3
import struct
import sys
import time
import traceback
import urllib.parse
import urllib.request
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
# NetFlow v9 / IPFIX information elements
IE_BYTES, IE_PKTS, IE_PROTO, IE_TOS, IE_TCP_FLAGS = 1, 2, 4, 5, 6
IE_SPORT, IE_SRC4, IE_IN_IF, IE_DPORT, IE_DST4 = 7, 8, 10, 11, 12
IE_OUT_IF, IE_SRC_AS, IE_DST_AS, IE_SRC6, IE_DST6 = 14, 16, 17, 27, 28
IE_SAMPLE = 34
IE_SAMPLE2 = 52
IE_SAMPLE3 = 305
def _ipv4(data: bytes) -> str:
if len(data) < 4:
return "0.0.0.0"
return str(ipaddress.IPv4Address(data[:4]))
def _ipv6(data: bytes) -> str:
if len(data) < 16:
return "::"
return str(ipaddress.IPv6Address(data[:16]))
def _u(data: bytes) -> int:
return int.from_bytes(data, "big") if data else 0
def _fmt_bytes(value: int | float | None) -> str:
n = float(value or 0)
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or unit == "TB":
return f"{int(n)}B" if unit == "B" else f"{n:.1f}{unit}"
n /= 1024
return f"{n:.1f}TB"
def _fmt_ts(ts: float) -> str:
if not ts:
return "-"
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ")
def _table_lines(headers: list[str], rows: list[list[Any]]) -> list[str]:
cols = list(headers)
data = [[str(c) for c in row] for row in rows]
widths = [len(h) for h in cols]
for row in data:
for i, cell in enumerate(row):
widths[i] = min(max(widths[i], len(cell)), 46)
out = [
" ".join(h.ljust(widths[i]) for i, h in enumerate(cols)),
" ".join("-" * w for w in widths),
]
if not data:
out.append("(no data)")
return out
for row in data:
out.append(" ".join(row[i].ljust(widths[i]) for i in range(len(cols))))
return out
def _print_table(headers: list[str], rows: list[list[Any]]) -> None:
for line in _table_lines(headers, rows):
print(line)
def _scalar(text: str) -> Any:
text = text.strip()
if not text:
return ""
if text[0] in "\"'" and len(text) >= 2 and text[-1] == text[0]:
return text[1:-1]
low = text.lower()
if low in ("true", "yes"):
return True
if low in ("false", "no"):
return False
if low in ("null", "~"):
return None
try:
return int(text)
except ValueError:
return text
def load_yaml(text: str) -> Any:
"""Minimal YAML subset: maps, lists, scalars, comments."""
lines = []
for raw in text.splitlines():
if "#" in raw:
in_q = False
out = []
for ch in raw:
if ch in "\"'":
in_q = not in_q
if ch == "#" and not in_q:
break
out.append(ch)
raw = "".join(out)
if raw.strip():
lines.append(raw.rstrip())
def parse_block(index: int, indent: int) -> tuple[Any, int]:
mapping: dict[str, Any] = {}
sequence: list[Any] = []
kind = None
while index < len(lines):
line = lines[index]
cur = len(line) - len(line.lstrip(" "))
if cur < indent:
break
if cur > indent:
raise ValueError(f"Bad indent: {line}")
stripped = line.strip()
if stripped.startswith("- "):
if kind == "map":
raise ValueError("Mixed map/list")
kind = "list"
rest = stripped[2:]
index += 1
key_part = rest.split(":", 1)[0].strip()
if ":" in rest and key_part.isidentifier():
key, _, val = rest.partition(":")
item: dict[str, Any] = {}
if val.strip():
item[key.strip()] = _scalar(val)
nested, index = parse_block(index, cur + 2)
if isinstance(nested, dict):
item.update(nested)
sequence.append(item)
else:
sequence.append(_scalar(rest))
else:
if kind == "list":
break
kind = "map"
if stripped.endswith(":") and stripped.count(":") == 1:
key = stripped[:-1].strip()
index += 1
if index < len(lines):
nxt = lines[index]
ncur = len(nxt) - len(nxt.lstrip(" "))
if ncur > cur:
nested, index = parse_block(index, ncur)
mapping[key] = nested
continue
mapping[key] = {}
else:
key, _, val = stripped.partition(":")
mapping[key.strip()] = _scalar(val)
index += 1
if kind == "list":
return sequence, index
return mapping, index
value, _ = parse_block(0, 0)
return value
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
@dataclass
class Exporter:
id: str
name: str
address: str
enabled: bool = True
local_networks: list[str] = field(default_factory=list)
local_asns: list[int] = field(default_factory=list)
@dataclass
class Config:
netflow_host: str = "0.0.0.0"
netflow_port: int = 2055
sflow_host: str = "0.0.0.0"
sflow_port: int = 6343
accept_unknown: bool = True
local_networks: list[str] = field(default_factory=list)
local_asns: list[int] = field(default_factory=list)
exporters: list[Exporter] = field(default_factory=list)
ripe_enabled: bool = True
ripe_url: str = "https://stat.ripe.net/data/network-info/data.json"
ripe_cache_path: str = "data/ripe_asn_cache.json"
router_state_path: str = "data/router_state.json"
database_path: str = "data/collector.db"
window_seconds: int = 60
retention_minutes: int = 120
attack_enabled: bool = True
attack_window: int = 10
tcp_syn_pps: int = 50000
tcp_scan_ports: int = 100
udp_flood_pps: int = 80000
cooldown: int = 60
alert_dir: str = "alerts"
reports_dir: str = "reports"
reports_auto_seconds: int = 300
reports_keep: int = 48
reports_window: int = 300
reports_limit: int = 20
# Destination-ASN delivery aggregation (high-volume path)
as_enabled: bool = True
as_iface_field: str = "input" # input|output
as_interfaces: set[int] = field(default_factory=set)
as_flush_seconds: int = 600
as_retention_days: int = 90
def load_config(path: str) -> Config:
raw = load_yaml(Path(path).read_text(encoding="utf-8")) or {}
if not isinstance(raw, dict):
raise ValueError("config root must be a mapping")
listen = raw.get("listen") or {}
agg = raw.get("aggregation") or {}
attack = raw.get("attack") or {}
ripe = raw.get("ripe") or {}
reports = raw.get("reports") or {}
as_traffic = raw.get("as_traffic") or {}
ifaces_raw = as_traffic.get("interfaces") or []
if not isinstance(ifaces_raw, list):
ifaces_raw = []
iface_set: set[int] = set()
for x in ifaces_raw:
try:
iface_set.add(int(x))
except (TypeError, ValueError):
continue
exporters = [
Exporter(
id=str(item["id"]),
name=str(item.get("name") or item["id"]),
address=str(item["address"]),
enabled=bool(item.get("enabled", True)),
local_networks=list(item.get("local_networks") or []),
local_asns=[int(a) for a in (item.get("local_asns") or [])],
)
for item in (raw.get("exporters") or [])
]
return Config(
netflow_host=str(listen.get("netflow_host", "0.0.0.0")),
netflow_port=int(listen.get("netflow_port", 2055)),
sflow_host=str(listen.get("sflow_host", "0.0.0.0")),
sflow_port=int(listen.get("sflow_port", 6343)),
accept_unknown=bool(raw.get("accept_unknown_exporters", True)),
local_networks=list(raw.get("local_networks") or []),
local_asns=[int(a) for a in (raw.get("local_asns") or [])],
exporters=exporters,
ripe_enabled=bool(ripe.get("enabled", True)),
ripe_url=str(ripe.get("url") or "https://stat.ripe.net/data/network-info/data.json"),
ripe_cache_path=str(ripe.get("cache_path") or "data/ripe_asn_cache.json"),
router_state_path=str(raw.get("router_state_path") or "data/router_state.json"),
database_path=str(raw.get("database_path") or "data/collector.db"),
window_seconds=int(agg.get("window_seconds", 60)),
retention_minutes=int(agg.get("retention_minutes", 120)),
attack_enabled=bool(attack.get("enabled", True)),
attack_window=int(attack.get("window_seconds", 10)),
tcp_syn_pps=int(attack.get("tcp_syn_pps", 50000)),
tcp_scan_ports=int(attack.get("tcp_scan_unique_ports", 100)),
udp_flood_pps=int(attack.get("udp_flood_pps", 80000)),
cooldown=int(attack.get("cooldown_seconds", 60)),
alert_dir=str(attack.get("output_dir") or "alerts"),
reports_dir=str(reports.get("dir") or "reports"),
reports_auto_seconds=int(reports.get("auto_save_seconds", 300)),
reports_keep=int(reports.get("keep_files", 48)),
reports_window=int(reports.get("window_seconds", 300)),
reports_limit=int(reports.get("limit", 20)),
as_enabled=bool(as_traffic.get("enabled", True)),
as_iface_field=str(as_traffic.get("iface_field", "input")).lower(),
as_interfaces=iface_set,
as_flush_seconds=int(as_traffic.get("flush_seconds", 600)),
as_retention_days=int(as_traffic.get("retention_days", 90)),
)
# ---------------------------------------------------------------------------
# Flow + routers
# ---------------------------------------------------------------------------
@dataclass
class Flow:
timestamp: float
exporter_ip: str
router_id: str
router_name: str
protocol: int
src_ip: str
dst_ip: str
src_port: int = 0
dst_port: int = 0
bytes: int = 0
packets: int = 0
src_asn: int = 0
dst_asn: int = 0
tcp_flags: int = 0
sampling_rate: int = 1
input_iface: int = 0
output_iface: int = 0
direction: str = "unknown"
source: str = ""
source_id: int = 0
@property
def scaled_bytes(self) -> int:
return self.bytes * max(self.sampling_rate, 1)
@property
def scaled_packets(self) -> int:
return self.packets * max(self.sampling_rate, 1)
@dataclass
class RouterStats:
router_id: str
router_name: str
exporter_ip: str
last_seen: float = 0.0
packets_received: int = 0
flows_received: int = 0
template_count: int = 0
protocols: set[str] = field(default_factory=set)
class Routers:
def __init__(self, cfg: Config) -> None:
self.accept_unknown = cfg.accept_unknown
self.state_path = Path(cfg.router_state_path)
self.by_addr = {e.address: e for e in cfg.exporters}
self.by_id = {e.id: e for e in cfg.exporters}
self.stats: dict[str, RouterStats] = {
e.id: RouterStats(e.id, e.name, e.address) for e in cfg.exporters
}
self.enabled: dict[str, bool] = {e.id: e.enabled for e in cfg.exporters}
self.reload_state()
def reload_state(self) -> None:
if not self.state_path.exists():
return
try:
data = json.loads(self.state_path.read_text(encoding="utf-8"))
except Exception:
return
if isinstance(data, dict):
for key, val in data.items():
self.enabled[str(key)] = bool(val)
def save_state(self) -> None:
self.state_path.parent.mkdir(parents=True, exist_ok=True)
self.state_path.write_text(json.dumps(self.enabled, indent=2), encoding="utf-8")
def find(self, token: str) -> Optional[str]:
if token in self.enabled or token in self.by_id or token in self.stats:
return token
for exp in self.by_id.values():
if exp.address == token or exp.name == token:
return exp.id
for st in self.stats.values():
if st.exporter_ip == token or st.router_name == token:
return st.router_id
return None
def is_enabled(self, rid: str) -> bool:
return self.enabled.get(rid, True)
def set_enabled(self, rid: str, on: bool) -> None:
self.enabled[rid] = on
self.save_state()
def resolve(self, ip: str) -> Optional[tuple[str, str, Optional[Exporter]]]:
known = self.by_addr.get(ip)
if known:
return known.id, known.name, known
if not self.accept_unknown:
return None
rid = f"auto-{ip.replace(':', '-')}"
name = f"Unknown ({ip})"
self.stats.setdefault(rid, RouterStats(rid, name, ip))
self.enabled.setdefault(rid, True)
return rid, name, None
def note(
self,
rid: str,
name: str,
ip: str,
source: str,
flows: int,
templates: Optional[int] = None,
) -> None:
st = self.stats.setdefault(rid, RouterStats(rid, name, ip))
st.last_seen = time.time()
st.packets_received += 1
st.flows_received += flows
if source:
st.protocols.add(source)
if templates is not None:
st.template_count = templates
def classify(flow: Flow, cfg: Config, routers: Routers) -> str:
exporter = routers.by_id.get(flow.router_id)
nets = (exporter.local_networks if exporter and exporter.local_networks else cfg.local_networks)
asns = set(exporter.local_asns if exporter and exporter.local_asns else cfg.local_asns)
networks = []
for item in nets:
try:
networks.append(ipaddress.ip_network(item, strict=False))
except ValueError:
pass
if not networks and not asns:
return "unknown"
def is_local(ip: str, asn: int) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
addr = None
ip_ok = addr is not None and any(addr in n for n in networks)
asn_ok = asn > 0 and asn in asns
return ip_ok or asn_ok
src, dst = is_local(flow.src_ip, flow.src_asn), is_local(flow.dst_ip, flow.dst_asn)
if src and dst:
return "internal"
if not src and dst:
return "in"
if src and not dst:
return "out"
return "transit"
def _public_ip(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return not (
addr.is_private
or addr.is_loopback
or addr.is_link_local
or addr.is_multicast
or addr.is_reserved
or addr.is_unspecified
)
class RipeAsn:
"""IP to ASN via RIPEstat network-info, with prefix cache."""
def __init__(self, cfg: Config) -> None:
self.enabled = cfg.ripe_enabled
self.url = cfg.ripe_url
self.cache_path = Path(cfg.ripe_cache_path)
self.ip_cache: dict[str, int] = {}
self.prefixes: list[tuple[ipaddress._BaseNetwork, int]] = []
self._pending: set[str] = set()
self._queue: Optional[asyncio.Queue[str]] = None
self._dirty = False
self._last_save = 0.0
self._load()
def _load(self) -> None:
if not self.cache_path.exists():
return
try:
raw = json.loads(self.cache_path.read_text(encoding="utf-8"))
except Exception:
return
for prefix, asn in (raw.get("prefixes") or {}).items():
try:
net = ipaddress.ip_network(prefix, strict=False)
self.prefixes.append((net, int(asn)))
except (ValueError, TypeError):
continue
def save(self, force: bool = False) -> None:
if not self._dirty and not force:
return
now = time.time()
if not force and now - self._last_save < 30:
return
self.cache_path.parent.mkdir(parents=True, exist_ok=True)
payload = {"prefixes": {str(net): asn for net, asn in self.prefixes}}
self.cache_path.write_text(json.dumps(payload), encoding="utf-8")
self._dirty = False
self._last_save = now
def lookup_cached(self, ip: str) -> Optional[int]:
if ip in self.ip_cache:
return self.ip_cache[ip]
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return None
for net, asn in self.prefixes:
if addr in net:
self.ip_cache[ip] = asn
return asn
return None
def apply(self, flow: Flow) -> None:
if not self.enabled:
return
for attr, ip in (("src_asn", flow.src_ip), ("dst_asn", flow.dst_ip)):
if getattr(flow, attr) > 0:
continue
cached = self.lookup_cached(ip)
if cached is not None:
setattr(flow, attr, cached)
continue
self.enqueue(ip)
def enqueue(self, ip: str) -> None:
if not self.enabled or not _public_ip(ip):
if not _public_ip(ip):
self.ip_cache[ip] = 0
return
if ip in self.ip_cache or ip in self._pending:
return
self._pending.add(ip)
if self._queue is not None:
try:
self._queue.put_nowait(ip)
except asyncio.QueueFull:
self._pending.discard(ip)
def start(self) -> None:
if not self.enabled:
return
self._queue = asyncio.Queue(maxsize=10000)
asyncio.create_task(self._worker())
asyncio.create_task(self._worker())
async def _worker(self) -> None:
assert self._queue is not None
while True:
ip = await self._queue.get()
try:
await asyncio.to_thread(self._fetch, ip)
except Exception:
self._pending.discard(ip)
finally:
self._queue.task_done()
try:
self.save()
except Exception:
pass
def _fetch(self, ip: str) -> None:
url = f"{self.url}?resource={urllib.parse.quote(ip)}"
req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": "netflow-collector/1.0"})
try:
with urllib.request.urlopen(req, timeout=8) as resp:
body = json.loads(resp.read().decode("utf-8"))
except Exception:
self._pending.discard(ip)
return
data = body.get("data") or {}
asns = data.get("asns") or []
prefix = data.get("prefix")
asn = 0
if asns:
try:
asn = int(str(asns[0]).lstrip("AS"))
except ValueError:
asn = 0
self.ip_cache[ip] = asn
if prefix:
try:
net = ipaddress.ip_network(prefix, strict=False)
key = str(net)
if not any(str(existing) == key for existing, _ in self.prefixes):
self.prefixes.append((net, asn))
self._dirty = True
except ValueError:
pass
self._pending.discard(ip)
# ---------------------------------------------------------------------------
# Parsers
# ---------------------------------------------------------------------------
def parse_v5(data: bytes, exp: str, rid: str, name: str, ts: float) -> list[Flow]:
hdr, rec = "!HHIIIIBBH", "!IIIHHIIIIHHBBBBHHBBH"
hs, rs = struct.calcsize(hdr), struct.calcsize(rec)
if len(data) < hs:
return []
version, count, _, unix, *_rest = struct.unpack_from(hdr, data, 0)
sampling = _rest[-1] & 0x3FFF or 1
if version != 5:
return []
stamp = float(unix) if unix else ts
out: list[Flow] = []
off = hs
for _ in range(count):
if off + rs > len(data):
break
f = struct.unpack_from(rec, data, off)
off += rs
src, dst = f[0], f[1]
out.append(
Flow(
timestamp=stamp,
exporter_ip=exp,
router_id=rid,
router_name=name,
protocol=f[13],
src_ip=str(ipaddress.IPv4Address(src)),
dst_ip=str(ipaddress.IPv4Address(dst)),
src_port=f[9],
dst_port=f[10],
bytes=f[6],
packets=f[5],
src_asn=f[15],
dst_asn=f[16],
tcp_flags=f[12],
sampling_rate=sampling,
input_iface=int(f[3]),
output_iface=int(f[4]),
source="netflow_v5",
)
)
return out
@dataclass
class Tmpl:
fields: list[tuple[int, int, bool]] # type, length, enterprise
def fixed_size(self) -> Optional[int]:
total = 0
for _t, length, _e in self.fields:
if length == 0xFFFF:
return None
total += length
return total
class TemplateParser:
"""Shared NetFlow v9 + IPFIX decoder with per-exporter caches."""
def __init__(self) -> None:
self.templates: dict[tuple[str, int, int], Tmpl] = {}
def count_for(self, exp: str) -> int:
return sum(1 for k in self.templates if k[0] == exp)
def parse_v9(self, data: bytes, exp: str, rid: str, name: str, ts: float) -> list[Flow]:
if len(data) < 20:
return []
version, count, _, unix, _, source_id = struct.unpack_from("!HHIIII", data, 0)
if version != 9:
return []
stamp = float(unix) if unix else ts
return self._walk_sets(data, 20, len(data), exp, source_id, rid, name, stamp, v9=True, limit=count + 64)
def parse_ipfix(self, data: bytes, exp: str, rid: str, name: str, ts: float) -> list[Flow]:
if len(data) < 16:
return []
version, length, export_time, _, domain = struct.unpack_from("!HHIII", data, 0)
if version != 10:
return []
stamp = float(export_time) if export_time else ts
return self._walk_sets(data, 16, min(length, len(data)), exp, domain, rid, name, stamp, v9=False)
def _walk_sets(
self,
data: bytes,
offset: int,
end: int,
exp: str,
sid: int,
rid: str,
name: str,
ts: float,
v9: bool,
limit: int = 10_000,
) -> list[Flow]:
flows: list[Flow] = []
n = 0
while offset + 4 <= end and n < limit:
set_id, set_len = struct.unpack_from("!HH", data, offset)
if set_len < 4 or offset + set_len > end:
break
body = data[offset + 4 : offset + set_len]
tmpl_id = 0 if v9 else 2
opt_id = 1 if v9 else 3
if set_id == tmpl_id:
self._read_template(body, exp, sid, ipfix=not v9)
elif set_id == opt_id:
self._read_options(body, exp, sid, ipfix=not v9)
elif set_id >= 256:
flows.extend(self._read_data(body, set_id, exp, sid, rid, name, ts, not v9))
offset += set_len
n += 1
return flows
def _read_template(self, data: bytes, exp: str, sid: int, ipfix: bool) -> None:
off = 0
while off + 4 <= len(data):
tid, count = struct.unpack_from("!HH", data, off)
off += 4
fields: list[tuple[int, int, bool]] = []
for _ in range(count):
if off + 4 > len(data):
return
raw, length = struct.unpack_from("!HH", data, off)
off += 4
ent = bool(raw & 0x8000) if ipfix else False
ftype = raw & 0x7FFF if ipfix else raw
if ent:
if off + 4 > len(data):
return
off += 4
fields.append((ftype, length, ent))
if tid >= 256:
self.templates[(exp, sid, tid)] = Tmpl(fields)
def _read_options(self, data: bytes, exp: str, sid: int, ipfix: bool) -> None:
off = 0
if ipfix:
while off + 6 <= len(data):
tid, count, _scope = struct.unpack_from("!HHH", data, off)
off += 6
fields: list[tuple[int, int, bool]] = []
for _ in range(count):
if off + 4 > len(data):
return
raw, length = struct.unpack_from("!HH", data, off)
off += 4
ent = bool(raw & 0x8000)
if ent:
if off + 4 > len(data):
return
off += 4
fields.append((raw & 0x7FFF, length, ent))
if tid >= 256:
self.templates[(exp, sid, tid)] = Tmpl(fields)
else:
while off + 6 <= len(data):
tid, scope_len, opt_len = struct.unpack_from("!HHH", data, off)
off += 6
total = (scope_len + opt_len) // 4
fields = []
for _ in range(total):
if off + 4 > len(data):
return
ftype, length = struct.unpack_from("!HH", data, off)
off += 4
fields.append((ftype, length, False))
if tid >= 256:
self.templates[(exp, sid, tid)] = Tmpl(fields)
def _read_data(
self, data: bytes, tid: int, exp: str, sid: int, rid: str, name: str, ts: float, ipfix: bool
) -> list[Flow]:
tmpl = self.templates.get((exp, sid, tid))
if not tmpl:
return []
flows: list[Flow] = []
off = 0
while off < len(data):
values: dict[int, bytes] = {}
cur = off
try:
for ftype, length, ent in tmpl.fields:
if length == 0xFFFF:
if cur >= len(data):
return flows
length = data[cur]
cur += 1
if length == 255:
if cur + 2 > len(data):
return flows
length = struct.unpack_from("!H", data, cur)[0]
cur += 2
if cur + length > len(data):
return flows
if not ent:
values[ftype] = data[cur : cur + length]
cur += length
except Exception:
break
if cur <= off:
break
off = cur
flow = values_to_flow(values, exp, rid, name, ts, sid, "ipfix" if ipfix else "netflow_v9")
if flow:
flows.append(flow)
fixed = tmpl.fixed_size()
if fixed is not None and off + fixed > len(data) and len(data) - off < 4:
break
return flows
def values_to_flow(
values: dict[int, bytes], exp: str, rid: str, name: str, ts: float, sid: int, source: str
) -> Optional[Flow]:
src = _ipv4(values[IE_SRC4]) if IE_SRC4 in values else (_ipv6(values[IE_SRC6]) if IE_SRC6 in values else "0.0.0.0")
dst = _ipv4(values[IE_DST4]) if IE_DST4 in values else (_ipv6(values[IE_DST6]) if IE_DST6 in values else "0.0.0.0")
if src in ("0.0.0.0", "::") and dst in ("0.0.0.0", "::"):
return None
sampling = _u(values.get(IE_SAMPLE, values.get(IE_SAMPLE2, values.get(IE_SAMPLE3, b"")))) or 1
return Flow(
timestamp=ts,
exporter_ip=exp,
router_id=rid,
router_name=name,
protocol=_u(values.get(IE_PROTO, b"")),
src_ip=src,
dst_ip=dst,
src_port=_u(values.get(IE_SPORT, b"")),
dst_port=_u(values.get(IE_DPORT, b"")),
bytes=_u(values.get(IE_BYTES, b"")),
packets=_u(values.get(IE_PKTS, b"")) or 1,
src_asn=_u(values.get(IE_SRC_AS, b"")),
dst_asn=_u(values.get(IE_DST_AS, b"")),
tcp_flags=_u(values.get(IE_TCP_FLAGS, b"")),
sampling_rate=sampling,
input_iface=_u(values.get(IE_IN_IF, b"")),
output_iface=_u(values.get(IE_OUT_IF, b"")),
source=source,
source_id=sid,
)
def _ru32(data: bytes, off: int) -> tuple[int, int]:
if off + 4 > len(data):
raise ValueError("truncated")
return struct.unpack_from("!I", data, off)[0], off + 4
def _parse_ip_hdr(pkt: bytes) -> Optional[tuple[str, str, int, int, int, int, int]]:
if len(pkt) < 20:
return None
ver = pkt[0] >> 4
if ver == 4:
ihl = (pkt[0] & 0x0F) * 4
if len(pkt) < ihl:
return None
proto, total = pkt[9], struct.unpack_from("!H", pkt, 2)[0]
src = f"{pkt[12]}.{pkt[13]}.{pkt[14]}.{pkt[15]}"
dst = f"{pkt[16]}.{pkt[17]}.{pkt[18]}.{pkt[19]}"
l4, sport, dport, flags = pkt[ihl:], 0, 0, 0
if proto == 6 and len(l4) >= 14:
sport, dport = struct.unpack_from("!HH", l4, 0)
flags = l4[13]
elif proto == 17 and len(l4) >= 4:
sport, dport = struct.unpack_from("!HH", l4, 0)
return src, dst, proto, sport, dport, flags, total
if ver == 6 and len(pkt) >= 40:
proto, plen = pkt[6], struct.unpack_from("!H", pkt, 4)[0]
src = str(ipaddress.IPv6Address(pkt[8:24]))
dst = str(ipaddress.IPv6Address(pkt[24:40]))
l4, sport, dport, flags = pkt[40:], 0, 0, 0
if proto == 6 and len(l4) >= 14:
sport, dport = struct.unpack_from("!HH", l4, 0)
flags = l4[13]
elif proto == 17 and len(l4) >= 4:
sport, dport = struct.unpack_from("!HH", l4, 0)
return src, dst, proto, sport, dport, flags, plen + 40
return None
def parse_sflow(data: bytes, exp: str, rid: str, name: str, ts: float) -> list[Flow]:
if len(data) < 28:
return []
try:
version, off = _ru32(data, 0)
if version != 5:
return []
atype, off = _ru32(data, off)
off += 4 if atype == 1 else 16 if atype == 2 else 0
_, off = _ru32(data, off)
_, off = _ru32(data, off)
_, off = _ru32(data, off)
count, off = _ru32(data, off)
except ValueError:
return []
flows: list[Flow] = []
for _ in range(min(count, 512)):
try:
stype, off = _ru32(data, off)
slen, off = _ru32(data, off)
body = data[off : off + slen]
off += slen
if (stype >> 12) != 0:
continue
fmt = stype & 0xFFF
if fmt in (1, 3):
flows.extend(_sflow_sample(body, fmt == 3, exp, rid, name, ts))
except ValueError:
break
return flows
def _sflow_sample(data: bytes, expanded: bool, exp: str, rid: str, name: str, ts: float) -> list[Flow]:
try:
off = 0
_, off = _ru32(data, off)
if expanded:
_, off = _ru32(data, off)
_, off = _ru32(data, off)
else:
_, off = _ru32(data, off)
rate, off = _ru32(data, off)
_, off = _ru32(data, off)
_, off = _ru32(data, off)
if expanded:
_, off = _ru32(data, off)
_, off = _ru32(data, off)
_, off = _ru32(data, off)
_, off = _ru32(data, off)
else:
_, off = _ru32(data, off)
_, off = _ru32(data, off)
nrec, off = _ru32(data, off)
except ValueError:
return []
rate = rate or 1
flows: list[Flow] = []
src_as = dst_as = 0
for _ in range(min(nrec, 64)):
try:
rtype, off = _ru32(data, off)
rlen, off = _ru32(data, off)
body = data[off : off + rlen]
off += rlen
if (rtype >> 12) != 0:
continue
fmt = rtype & 0xFFF
if fmt == 1:
flow = _sflow_raw(body, exp, rid, name, ts, rate, src_as, dst_as)
if flow:
flows.append(flow)
elif fmt == 3 and len(body) >= 32:
length, proto = struct.unpack_from("!II", body, 0)
src = str(ipaddress.IPv4Address(body[8:12]))
dst = str(ipaddress.IPv4Address(body[12:16]))
sport, dport, flags = struct.unpack_from("!III", body, 16)
flows.append(
Flow(ts, exp, rid, name, proto, src, dst, sport, dport, length, 1, src_as, dst_as, flags & 0xFF, rate, source="sflow")
)
elif fmt == 1003:
o = 0
atype, o = _ru32(body, o)
o += 4 if atype == 1 else 16 if atype == 2 else 0
_, o = _ru32(body, o)
src_as, o = _ru32(body, o)
n, o = _ru32(body, o)
if n > 0:
dst_as, o = _ru32(body, o)
except ValueError:
break
if flows and (src_as or dst_as):
if flows[-1].src_asn <= 0:
flows[-1].src_asn = src_as
if flows[-1].dst_asn <= 0:
flows[-1].dst_asn = dst_as
return flows
def _sflow_raw(data: bytes, exp: str, rid: str, name: str, ts: float, rate: int, src_as: int, dst_as: int) -> Optional[Flow]:
try:
proto, off = _ru32(data, 0)
flen, off = _ru32(data, off)
_, off = _ru32(data, off)