capsight 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capsight/__init__.py +3 -0
- capsight/cli.py +171 -0
- capsight/codes.py +257 -0
- capsight/codes_5g.py +258 -0
- capsight/correlate.py +268 -0
- capsight/decode.py +167 -0
- capsight/engine.py +145 -0
- capsight/fields.py +80 -0
- capsight/identity.py +66 -0
- capsight/model.py +50 -0
- capsight/redact.py +79 -0
- capsight/rules.py +522 -0
- capsight/rules_5g.py +322 -0
- capsight/summary.py +116 -0
- capsight/timeline.py +238 -0
- capsight/web.py +116 -0
- capsight-0.2.0.dist-info/METADATA +261 -0
- capsight-0.2.0.dist-info/RECORD +21 -0
- capsight-0.2.0.dist-info/WHEEL +4 -0
- capsight-0.2.0.dist-info/entry_points.txt +3 -0
- capsight-0.2.0.dist-info/licenses/LICENSE +21 -0
capsight/correlate.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Pair requests with answers so rules reason about transactions, not single packets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from capsight.codes import DIAMETER_COMMANDS, GTPV2_MESSAGES, GTPV2_PAIRS
|
|
9
|
+
from capsight.codes_5g import PFCP_MESSAGES, PFCP_PAIRS
|
|
10
|
+
from capsight.model import Packet
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_int(value: str | None) -> int | None:
|
|
14
|
+
if value is None or value == "":
|
|
15
|
+
return None
|
|
16
|
+
try:
|
|
17
|
+
return int(value, 0)
|
|
18
|
+
except ValueError:
|
|
19
|
+
try:
|
|
20
|
+
return int(float(value))
|
|
21
|
+
except ValueError:
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def to_bool(value: str | None) -> bool:
|
|
26
|
+
return str(value).lower() in {"1", "true", "yes"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(slots=True)
|
|
30
|
+
class Transaction:
|
|
31
|
+
protocol: str
|
|
32
|
+
name: str
|
|
33
|
+
request: Packet | None
|
|
34
|
+
answer: Packet | None = None
|
|
35
|
+
imsi: str | None = None
|
|
36
|
+
retransmissions: int = 0
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def first_packet(self) -> Packet:
|
|
40
|
+
packet = self.request or self.answer
|
|
41
|
+
assert packet is not None
|
|
42
|
+
return packet
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# Fields rules read from a transaction's request/answer after pairing. Pairing keys
|
|
46
|
+
# (hop-by-hop ids, sequence numbers, Session-Id, ...) are dropped once used, so a capture
|
|
47
|
+
# with millions of transactions stays small in memory.
|
|
48
|
+
TX_FIELDS = frozenset(
|
|
49
|
+
(
|
|
50
|
+
"diameter.Result-Code",
|
|
51
|
+
"diameter.Experimental-Result-Code",
|
|
52
|
+
"gtpv2.cause",
|
|
53
|
+
"gtpv2.cs",
|
|
54
|
+
"gtpv2.apn",
|
|
55
|
+
"gtpv2.pdn_type",
|
|
56
|
+
"e212.imsi",
|
|
57
|
+
"pfcp.cause",
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def slim(packet: Packet, keep: frozenset[str] = TX_FIELDS) -> Packet:
|
|
63
|
+
return Packet(
|
|
64
|
+
packet.number,
|
|
65
|
+
packet.time,
|
|
66
|
+
packet.protocols,
|
|
67
|
+
{k: v for k, v in packet.fields.items() if k in keep},
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def diameter_name(cmd: int, is_request: bool) -> str:
|
|
72
|
+
names = DIAMETER_COMMANDS.get(cmd)
|
|
73
|
+
if names is None:
|
|
74
|
+
return f"Diameter cmd {cmd} {'request' if is_request else 'answer'}"
|
|
75
|
+
return names[0] if is_request else names[1]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Correlator:
|
|
79
|
+
"""Pairs requests with answers one packet at a time (streaming)."""
|
|
80
|
+
|
|
81
|
+
protocol = ""
|
|
82
|
+
|
|
83
|
+
def __init__(self) -> None:
|
|
84
|
+
self.done: list[Transaction] = []
|
|
85
|
+
|
|
86
|
+
def feed(self, packet: Packet) -> None:
|
|
87
|
+
raise NotImplementedError
|
|
88
|
+
|
|
89
|
+
def _open(self) -> list[Transaction]:
|
|
90
|
+
raise NotImplementedError
|
|
91
|
+
|
|
92
|
+
def finish(self) -> list[Transaction]:
|
|
93
|
+
txs = self.done + self._open()
|
|
94
|
+
return sorted(txs, key=lambda t: t.first_packet.number)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class DiameterCorrelator(Correlator):
|
|
98
|
+
"""Pair Diameter requests and answers by (hop-by-hop id, end-to-end id, command).
|
|
99
|
+
|
|
100
|
+
Frames carrying several Diameter messages are paired on the per-message header fields;
|
|
101
|
+
result codes are only trusted when the frame carries a single message.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
protocol = "diameter"
|
|
105
|
+
|
|
106
|
+
def __init__(self) -> None:
|
|
107
|
+
super().__init__()
|
|
108
|
+
self.open_requests: dict[tuple[int, int, int], Transaction] = {}
|
|
109
|
+
|
|
110
|
+
def _open(self) -> list[Transaction]:
|
|
111
|
+
return list(self.open_requests.values())
|
|
112
|
+
|
|
113
|
+
def feed(self, packet: Packet) -> None:
|
|
114
|
+
if not packet.has("diameter"):
|
|
115
|
+
return
|
|
116
|
+
cmds = packet.fields.get("diameter.cmd.code", [])
|
|
117
|
+
flags = packet.fields.get("diameter.flags.request", [])
|
|
118
|
+
hbhs = packet.fields.get("diameter.hopbyhopid", [])
|
|
119
|
+
e2es = packet.fields.get("diameter.endtoendid", [])
|
|
120
|
+
stored = slim(packet)
|
|
121
|
+
for i, raw_cmd in enumerate(cmds):
|
|
122
|
+
cmd = to_int(raw_cmd)
|
|
123
|
+
hbh = to_int(hbhs[i]) if i < len(hbhs) else None
|
|
124
|
+
e2e = to_int(e2es[i]) if i < len(e2es) else None
|
|
125
|
+
if cmd is None or hbh is None or e2e is None:
|
|
126
|
+
continue
|
|
127
|
+
is_request = to_bool(flags[i]) if i < len(flags) else False
|
|
128
|
+
key = (hbh, e2e, cmd)
|
|
129
|
+
if is_request:
|
|
130
|
+
self.open_requests[key] = Transaction(
|
|
131
|
+
"diameter",
|
|
132
|
+
diameter_name(cmd, True),
|
|
133
|
+
stored,
|
|
134
|
+
imsi=packet.first("diameter.User-Name"),
|
|
135
|
+
)
|
|
136
|
+
else:
|
|
137
|
+
tx = self.open_requests.pop(key, None)
|
|
138
|
+
if tx is None:
|
|
139
|
+
tx = Transaction("diameter", diameter_name(cmd, True), None)
|
|
140
|
+
tx.answer = stored
|
|
141
|
+
self.done.append(tx)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
RETRANSMIT_WINDOW = 10.0 # seconds; GTPv2-C sequence numbers wrap far slower than this
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Gtpv2Correlator(Correlator):
|
|
148
|
+
"""Pair GTPv2-C requests and responses by sequence number and message type.
|
|
149
|
+
|
|
150
|
+
Retransmitted requests and repeated responses (same sequence number) are folded into
|
|
151
|
+
one transaction and counted, so a retransmission storm is not mistaken for many failures.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
protocol = "gtpv2"
|
|
155
|
+
|
|
156
|
+
def __init__(self) -> None:
|
|
157
|
+
super().__init__()
|
|
158
|
+
self.responses = {v: k for k, v in GTPV2_PAIRS.items()}
|
|
159
|
+
self.open_requests: dict[tuple[int, int], Transaction] = {}
|
|
160
|
+
self.answered: dict[tuple[int, int], Transaction] = {}
|
|
161
|
+
|
|
162
|
+
def _open(self) -> list[Transaction]:
|
|
163
|
+
return list(self.open_requests.values())
|
|
164
|
+
|
|
165
|
+
def feed(self, packet: Packet) -> None:
|
|
166
|
+
if not packet.has("gtpv2"):
|
|
167
|
+
return
|
|
168
|
+
mtype = to_int(packet.first("gtpv2.message_type"))
|
|
169
|
+
seq = to_int(packet.first("gtpv2.seq"))
|
|
170
|
+
if mtype is None or seq is None:
|
|
171
|
+
return
|
|
172
|
+
if mtype in GTPV2_PAIRS:
|
|
173
|
+
key = (seq, GTPV2_PAIRS[mtype])
|
|
174
|
+
if key in self.open_requests:
|
|
175
|
+
self.open_requests[key].retransmissions += 1
|
|
176
|
+
return
|
|
177
|
+
previous = self.answered.get(key)
|
|
178
|
+
if (
|
|
179
|
+
previous is not None
|
|
180
|
+
and previous.request is not None
|
|
181
|
+
and packet.time - previous.request.time < RETRANSMIT_WINDOW
|
|
182
|
+
and packet.first("e212.imsi") == previous.imsi
|
|
183
|
+
):
|
|
184
|
+
# retransmitted request after the answer was already sent
|
|
185
|
+
previous.retransmissions += 1
|
|
186
|
+
return
|
|
187
|
+
self.open_requests[key] = Transaction(
|
|
188
|
+
"gtpv2",
|
|
189
|
+
GTPV2_MESSAGES.get(mtype, f"GTPv2 type {mtype}"),
|
|
190
|
+
slim(packet),
|
|
191
|
+
imsi=packet.first("e212.imsi"),
|
|
192
|
+
)
|
|
193
|
+
elif mtype in self.responses:
|
|
194
|
+
key = (seq, mtype)
|
|
195
|
+
tx = self.open_requests.pop(key, None)
|
|
196
|
+
if tx is None:
|
|
197
|
+
previous = self.answered.get(key)
|
|
198
|
+
if (
|
|
199
|
+
previous is not None
|
|
200
|
+
and previous.answer is not None
|
|
201
|
+
and packet.time - previous.answer.time < RETRANSMIT_WINDOW
|
|
202
|
+
):
|
|
203
|
+
# repeated answer to a retransmitted request; already counted there
|
|
204
|
+
return
|
|
205
|
+
req_type = self.responses[mtype]
|
|
206
|
+
tx = Transaction("gtpv2", GTPV2_MESSAGES.get(req_type, str(req_type)), None)
|
|
207
|
+
tx.answer = slim(packet)
|
|
208
|
+
self.answered[key] = tx
|
|
209
|
+
self.done.append(tx)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class PfcpCorrelator(Correlator):
|
|
213
|
+
"""Pair PFCP requests and responses by sequence number and message type.
|
|
214
|
+
|
|
215
|
+
Retransmissions (same sequence number while still open) are counted, not duplicated.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
protocol = "pfcp"
|
|
219
|
+
|
|
220
|
+
def __init__(self) -> None:
|
|
221
|
+
super().__init__()
|
|
222
|
+
self.responses = {v: k for k, v in PFCP_PAIRS.items()}
|
|
223
|
+
self.open_requests: dict[tuple[int, int], Transaction] = {}
|
|
224
|
+
|
|
225
|
+
def _open(self) -> list[Transaction]:
|
|
226
|
+
return list(self.open_requests.values())
|
|
227
|
+
|
|
228
|
+
def feed(self, packet: Packet) -> None:
|
|
229
|
+
if not packet.has("pfcp"):
|
|
230
|
+
return
|
|
231
|
+
mtype = to_int(packet.first("pfcp.msg_type"))
|
|
232
|
+
seq = to_int(packet.first("pfcp.seqno"))
|
|
233
|
+
if mtype is None or seq is None:
|
|
234
|
+
return
|
|
235
|
+
if mtype in PFCP_PAIRS:
|
|
236
|
+
key = (seq, PFCP_PAIRS[mtype])
|
|
237
|
+
if key in self.open_requests:
|
|
238
|
+
self.open_requests[key].retransmissions += 1
|
|
239
|
+
return
|
|
240
|
+
name = PFCP_MESSAGES.get(mtype, f"type {mtype}").removesuffix(" Request")
|
|
241
|
+
self.open_requests[key] = Transaction("pfcp", name, slim(packet))
|
|
242
|
+
elif mtype in self.responses:
|
|
243
|
+
tx = self.open_requests.pop((seq, mtype), None)
|
|
244
|
+
if tx is None:
|
|
245
|
+
req = self.responses[mtype]
|
|
246
|
+
tx = Transaction(
|
|
247
|
+
"pfcp", PFCP_MESSAGES.get(req, str(req)).removesuffix(" Request"), None
|
|
248
|
+
)
|
|
249
|
+
tx.answer = slim(packet)
|
|
250
|
+
self.done.append(tx)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _run(correlator: Correlator, packets: Iterable[Packet]) -> list[Transaction]:
|
|
254
|
+
for packet in packets:
|
|
255
|
+
correlator.feed(packet)
|
|
256
|
+
return correlator.finish()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def correlate_diameter(packets: Iterable[Packet]) -> list[Transaction]:
|
|
260
|
+
return _run(DiameterCorrelator(), packets)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def correlate_gtpv2(packets: Iterable[Packet]) -> list[Transaction]:
|
|
264
|
+
return _run(Gtpv2Correlator(), packets)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def correlate_pfcp(packets: Iterable[Packet]) -> list[Transaction]:
|
|
268
|
+
return _run(PfcpCorrelator(), packets)
|
capsight/decode.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Thin wrapper around tshark. capsight never writes its own dissectors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from capsight.model import Packet
|
|
14
|
+
|
|
15
|
+
BASE_FIELDS = ("frame.number", "frame.time_epoch", "frame.protocols")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TsharkError(RuntimeError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def find_tshark() -> str:
|
|
23
|
+
path = shutil.which("tshark")
|
|
24
|
+
if path is None:
|
|
25
|
+
raise TsharkError("tshark not found on PATH. Install Wireshark 4.x.")
|
|
26
|
+
return path
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@lru_cache(maxsize=4)
|
|
30
|
+
def known_fields(tshark: str) -> frozenset[str]:
|
|
31
|
+
"""Field names this tshark build knows. Unknown -e fields make tshark abort."""
|
|
32
|
+
out = subprocess.run([tshark, "-G", "fields"], capture_output=True, text=True).stdout
|
|
33
|
+
return frozenset(
|
|
34
|
+
parts[2]
|
|
35
|
+
for parts in (line.split("\t") for line in out.splitlines())
|
|
36
|
+
if len(parts) > 2 and parts[0] == "F"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@lru_cache(maxsize=4)
|
|
41
|
+
def known_prefs(tshark: str) -> frozenset[str]:
|
|
42
|
+
out = subprocess.run([tshark, "-G", "defaultprefs"], capture_output=True, text=True).stdout
|
|
43
|
+
names = set()
|
|
44
|
+
for line in out.splitlines():
|
|
45
|
+
line = line.lstrip("#").strip()
|
|
46
|
+
if ":" in line and not line.startswith(" "):
|
|
47
|
+
names.add(line.split(":", 1)[0].strip())
|
|
48
|
+
return frozenset(names)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_command(
|
|
52
|
+
tshark: str,
|
|
53
|
+
capture: Path,
|
|
54
|
+
extra_fields: Sequence[str] = (),
|
|
55
|
+
display_filter: str = "",
|
|
56
|
+
prefs: Mapping[str, str] | None = None,
|
|
57
|
+
) -> list[str]:
|
|
58
|
+
cmd = [tshark, "-r", str(capture), "-n", "-T", "ek"]
|
|
59
|
+
for key, value in (prefs or {}).items():
|
|
60
|
+
cmd += ["-o", f"{key}:{value}"]
|
|
61
|
+
for name in (*BASE_FIELDS, *extra_fields):
|
|
62
|
+
cmd += ["-e", name]
|
|
63
|
+
if display_filter:
|
|
64
|
+
cmd += ["-Y", display_filter]
|
|
65
|
+
return cmd
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# Fields kept for packets outside the core protocols: just enough for user-plane rules.
|
|
69
|
+
NON_CORE_KEEP = ("ip.src", "ip.dst")
|
|
70
|
+
CORE = frozenset(
|
|
71
|
+
("diameter", "gtpv2", "gtp", "radius", "nas-eps", "s1ap", "ngap", "nas-5gs", "pfcp", "sip")
|
|
72
|
+
)
|
|
73
|
+
INTERN_MAX = 40 # values shorter than this repeat a lot (IMSIs, causes, hosts): share them
|
|
74
|
+
|
|
75
|
+
_protocol_cache: dict[str, tuple[str, ...]] = {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _protocols(value: str) -> tuple[str, ...]:
|
|
79
|
+
cached = _protocol_cache.get(value)
|
|
80
|
+
if cached is None:
|
|
81
|
+
cached = tuple(sys.intern(p) for p in value.split(":"))
|
|
82
|
+
_protocol_cache[value] = cached
|
|
83
|
+
return cached
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _values(v: object) -> list[str]:
|
|
87
|
+
items = v if isinstance(v, list) else [v]
|
|
88
|
+
return [sys.intern(x) if isinstance(x, str) and len(x) < INTERN_MAX else x for x in items]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_ek_line(line: str, field_names: Sequence[str] = ()) -> Packet | None:
|
|
92
|
+
"""Parse one line of `tshark -T ek` output. Index lines return None.
|
|
93
|
+
|
|
94
|
+
ek output replaces dots with underscores in field names, which is lossy for fields
|
|
95
|
+
that contain a real underscore (e.g. ``nas_eps.emm.cause``). Passing the requested
|
|
96
|
+
``field_names`` restores the exact names.
|
|
97
|
+
|
|
98
|
+
Packets outside the core protocols keep only their IP addresses, and repeated short
|
|
99
|
+
values are interned, so large captures fit in memory.
|
|
100
|
+
"""
|
|
101
|
+
line = line.strip()
|
|
102
|
+
if not line:
|
|
103
|
+
return None
|
|
104
|
+
doc = json.loads(line)
|
|
105
|
+
layers = doc.get("layers")
|
|
106
|
+
if layers is None:
|
|
107
|
+
return None
|
|
108
|
+
names = _name_map(tuple(field_names))
|
|
109
|
+
fields = {sys.intern(names.get(k, k.replace("_", "."))): v for k, v in layers.items()}
|
|
110
|
+
number = int(_first(fields.pop("frame.number")))
|
|
111
|
+
time = float(_first(fields.pop("frame.time_epoch")))
|
|
112
|
+
protocols = _protocols(_first(fields.pop("frame.protocols", "")))
|
|
113
|
+
if CORE.isdisjoint(protocols):
|
|
114
|
+
fields = {k: fields[k] for k in NON_CORE_KEEP if k in fields}
|
|
115
|
+
return Packet(
|
|
116
|
+
number=number,
|
|
117
|
+
time=time,
|
|
118
|
+
protocols=protocols,
|
|
119
|
+
fields={k: _values(v) for k, v in fields.items()},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _first(v: object) -> str:
|
|
124
|
+
return v[0] if isinstance(v, list) else v # type: ignore[return-value]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
_name_maps: dict[tuple[str, ...], dict[str, str]] = {}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _name_map(field_names: tuple[str, ...]) -> dict[str, str]:
|
|
131
|
+
cached = _name_maps.get(field_names)
|
|
132
|
+
if cached is None:
|
|
133
|
+
cached = {n.replace(".", "_"): n for n in (*BASE_FIELDS, *field_names)}
|
|
134
|
+
_name_maps[field_names] = cached
|
|
135
|
+
return cached
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def read_packets(
|
|
139
|
+
capture: Path,
|
|
140
|
+
extra_fields: Sequence[str] = (),
|
|
141
|
+
display_filter: str = "",
|
|
142
|
+
prefs: Mapping[str, str] | None = None,
|
|
143
|
+
) -> Iterator[Packet]:
|
|
144
|
+
"""Stream packets from a capture file without loading it all into memory.
|
|
145
|
+
|
|
146
|
+
Fields and preferences this tshark version does not know are skipped instead of failing,
|
|
147
|
+
so capsight works across Wireshark versions.
|
|
148
|
+
"""
|
|
149
|
+
if not capture.is_file():
|
|
150
|
+
raise TsharkError(f"capture not found: {capture}")
|
|
151
|
+
tshark = find_tshark()
|
|
152
|
+
available = known_fields(tshark)
|
|
153
|
+
if available:
|
|
154
|
+
extra_fields = [f for f in extra_fields if f in available]
|
|
155
|
+
if prefs:
|
|
156
|
+
supported = known_prefs(tshark)
|
|
157
|
+
prefs = {k: v for k, v in prefs.items() if k in supported}
|
|
158
|
+
cmd = build_command(tshark, capture, extra_fields, display_filter, prefs)
|
|
159
|
+
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as proc:
|
|
160
|
+
assert proc.stdout is not None
|
|
161
|
+
for line in proc.stdout:
|
|
162
|
+
packet = parse_ek_line(line, extra_fields)
|
|
163
|
+
if packet is not None:
|
|
164
|
+
yield packet
|
|
165
|
+
stderr = proc.stderr.read() if proc.stderr else ""
|
|
166
|
+
if proc.returncode != 0:
|
|
167
|
+
raise TsharkError(stderr.strip() or f"tshark exited with {proc.returncode}")
|
capsight/engine.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Glue: decode a capture, correlate, run rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from capsight import (
|
|
11
|
+
fields,
|
|
12
|
+
rules_5g, # noqa: F401 (registers 5G rules)
|
|
13
|
+
)
|
|
14
|
+
from capsight.correlate import DiameterCorrelator, Gtpv2Correlator, PfcpCorrelator
|
|
15
|
+
from capsight.decode import read_packets
|
|
16
|
+
from capsight.identity import ngap_imsi_map, s1ap_imsi_map
|
|
17
|
+
from capsight.model import Finding, Packet
|
|
18
|
+
from capsight.rules import Context, UserPlane, run_rules
|
|
19
|
+
from capsight.timeline import (
|
|
20
|
+
Step,
|
|
21
|
+
findings_for,
|
|
22
|
+
normalize_imsi,
|
|
23
|
+
subscriber_timeline,
|
|
24
|
+
subscribers_seen,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
CORE_PROTOCOLS = (
|
|
28
|
+
"diameter",
|
|
29
|
+
"gtpv2",
|
|
30
|
+
"radius",
|
|
31
|
+
"nas-eps",
|
|
32
|
+
"s1ap",
|
|
33
|
+
"ngap",
|
|
34
|
+
"nas-5gs",
|
|
35
|
+
"pfcp",
|
|
36
|
+
"gtp",
|
|
37
|
+
"sip",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Report:
|
|
43
|
+
capture: str
|
|
44
|
+
packets: int
|
|
45
|
+
duration_s: float
|
|
46
|
+
core_protocols: dict[str, int]
|
|
47
|
+
transactions: dict[str, int]
|
|
48
|
+
findings: list[Finding] = field(default_factory=list)
|
|
49
|
+
subscriber: str | None = None
|
|
50
|
+
timeline: list[Step] | None = None
|
|
51
|
+
subscribers_seen: list[str] | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# Packets the rules read one by one; everything else is reduced while streaming.
|
|
55
|
+
SIGNALLING = frozenset(("nas-eps", "s1ap", "radius", "ngap", "nas-5gs"))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Collector:
|
|
59
|
+
"""Consumes packets one at a time and keeps only what the rules need.
|
|
60
|
+
|
|
61
|
+
Diameter, GTPv2-C and PFCP become (slimmed) transactions, user-plane packets become
|
|
62
|
+
flow counters, and only signalling packets are kept whole. Memory therefore grows with
|
|
63
|
+
the number of procedures, not with the number of packets.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self.count = 0
|
|
68
|
+
self.start: float | None = None
|
|
69
|
+
self.end = 0.0
|
|
70
|
+
self.protocols: Counter[str] = Counter()
|
|
71
|
+
self.kept: list[Packet] = []
|
|
72
|
+
self.flows = UserPlane()
|
|
73
|
+
self.diameter = DiameterCorrelator()
|
|
74
|
+
self.gtpv2 = Gtpv2Correlator()
|
|
75
|
+
self.pfcp = PfcpCorrelator()
|
|
76
|
+
|
|
77
|
+
def feed(self, packet: Packet) -> None:
|
|
78
|
+
self.count += 1
|
|
79
|
+
if self.start is None:
|
|
80
|
+
self.start = packet.time
|
|
81
|
+
self.end = packet.time
|
|
82
|
+
protos = set(CORE_SET.intersection(packet.protocols))
|
|
83
|
+
if "gtpv2" in protos:
|
|
84
|
+
protos.discard("gtp") # tshark lists GTPv2-C under gtp too; count it once
|
|
85
|
+
for proto in protos:
|
|
86
|
+
self.protocols[proto] += 1
|
|
87
|
+
self.flows.feed(packet)
|
|
88
|
+
self.diameter.feed(packet)
|
|
89
|
+
self.gtpv2.feed(packet)
|
|
90
|
+
self.pfcp.feed(packet)
|
|
91
|
+
if not SIGNALLING.isdisjoint(packet.protocols):
|
|
92
|
+
self.kept.append(packet)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
CORE_SET = frozenset(CORE_PROTOCOLS)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def analyze_packets(
|
|
99
|
+
capture: str,
|
|
100
|
+
packets: Iterable[Packet],
|
|
101
|
+
answer_timeout: float = 5.0,
|
|
102
|
+
imsi: str | None = None,
|
|
103
|
+
) -> Report:
|
|
104
|
+
collector = Collector()
|
|
105
|
+
for packet in packets:
|
|
106
|
+
collector.feed(packet)
|
|
107
|
+
diameter = collector.diameter.finish()
|
|
108
|
+
gtpv2 = collector.gtpv2.finish()
|
|
109
|
+
pfcp = collector.pfcp.finish()
|
|
110
|
+
kept = collector.kept
|
|
111
|
+
start = collector.start or 0.0
|
|
112
|
+
end = collector.end
|
|
113
|
+
counts = collector.protocols
|
|
114
|
+
ctx = Context(
|
|
115
|
+
kept,
|
|
116
|
+
diameter,
|
|
117
|
+
gtpv2,
|
|
118
|
+
capture_end=end,
|
|
119
|
+
answer_timeout=answer_timeout,
|
|
120
|
+
inferred_imsi={**s1ap_imsi_map(kept), **ngap_imsi_map(kept)},
|
|
121
|
+
pfcp=pfcp,
|
|
122
|
+
flows=collector.flows,
|
|
123
|
+
)
|
|
124
|
+
report = Report(
|
|
125
|
+
capture=capture,
|
|
126
|
+
packets=collector.count,
|
|
127
|
+
duration_s=round(end - start, 3),
|
|
128
|
+
core_protocols={p: counts[p] for p in CORE_PROTOCOLS if counts[p]},
|
|
129
|
+
transactions={"diameter": len(diameter), "gtpv2": len(gtpv2), "pfcp": len(pfcp)},
|
|
130
|
+
findings=run_rules(ctx),
|
|
131
|
+
)
|
|
132
|
+
if imsi is not None:
|
|
133
|
+
wanted = normalize_imsi(imsi)
|
|
134
|
+
steps = subscriber_timeline(ctx, wanted)
|
|
135
|
+
report.subscriber = wanted
|
|
136
|
+
report.timeline = steps
|
|
137
|
+
report.findings = findings_for(report.findings, wanted, steps)
|
|
138
|
+
if not steps:
|
|
139
|
+
report.subscribers_seen = subscribers_seen(ctx)
|
|
140
|
+
return report
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def analyze(capture: Path, answer_timeout: float = 5.0, imsi: str | None = None) -> Report:
|
|
144
|
+
packets = read_packets(capture, fields.ALL, prefs=fields.PREFERENCES)
|
|
145
|
+
return analyze_packets(str(capture), packets, answer_timeout, imsi)
|
capsight/fields.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""tshark fields capsight requests. Field names verified against Wireshark 4.x."""
|
|
2
|
+
|
|
3
|
+
DIAMETER = (
|
|
4
|
+
"diameter.flags.request",
|
|
5
|
+
"diameter.cmd.code",
|
|
6
|
+
"diameter.applicationId",
|
|
7
|
+
"diameter.hopbyhopid",
|
|
8
|
+
"diameter.endtoendid",
|
|
9
|
+
"diameter.Session-Id",
|
|
10
|
+
"diameter.User-Name",
|
|
11
|
+
"diameter.Result-Code",
|
|
12
|
+
"diameter.Experimental-Result-Code",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
GTPV2 = (
|
|
16
|
+
"gtpv2.message_type",
|
|
17
|
+
"gtpv2.seq",
|
|
18
|
+
"gtpv2.teid",
|
|
19
|
+
"gtpv2.cause",
|
|
20
|
+
"gtpv2.apn",
|
|
21
|
+
"gtpv2.cs",
|
|
22
|
+
"gtpv2.pdn_type",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
RADIUS = ("radius.code", "radius.id")
|
|
26
|
+
|
|
27
|
+
NAS_EPS = (
|
|
28
|
+
"nas-eps.nas_msg_emm_type",
|
|
29
|
+
"nas-eps.nas_msg_esm_type",
|
|
30
|
+
"nas-eps.emm.cause",
|
|
31
|
+
"nas-eps.esm.cause",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
IDENTITY = ("e212.imsi", "s1ap.ENB_UE_S1AP_ID", "s1ap.MME_UE_S1AP_ID")
|
|
35
|
+
|
|
36
|
+
NGAP = (
|
|
37
|
+
"ngap.procedureCode",
|
|
38
|
+
"ngap.NGAP_PDU",
|
|
39
|
+
"ngap.Cause",
|
|
40
|
+
"ngap.radioNetwork",
|
|
41
|
+
"ngap.transport",
|
|
42
|
+
"ngap.nas",
|
|
43
|
+
"ngap.protocol",
|
|
44
|
+
"ngap.misc",
|
|
45
|
+
"ngap.RAN_UE_NGAP_ID",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
NAS_5GS = (
|
|
49
|
+
"nas-5gs.mm.message_type",
|
|
50
|
+
"nas-5gs.sm.message_type",
|
|
51
|
+
"nas-5gs.mm.5gmm_cause",
|
|
52
|
+
"nas-5gs.sm.5gsm_cause",
|
|
53
|
+
"nas-5gs.cmn.dnn",
|
|
54
|
+
"nas-5gs.mm.suci.scheme_id",
|
|
55
|
+
"nas-5gs.mm.suci.msin",
|
|
56
|
+
"e212.mcc",
|
|
57
|
+
"e212.mnc",
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
PFCP = ("pfcp.msg_type", "pfcp.seqno", "pfcp.cause", "pfcp.seid")
|
|
61
|
+
|
|
62
|
+
USER_PLANE = ("ip.src", "ip.dst", "gtp.teid")
|
|
63
|
+
|
|
64
|
+
ALL = (
|
|
65
|
+
*DIAMETER,
|
|
66
|
+
*GTPV2,
|
|
67
|
+
*RADIUS,
|
|
68
|
+
*NAS_EPS,
|
|
69
|
+
*IDENTITY,
|
|
70
|
+
*NGAP,
|
|
71
|
+
*NAS_5GS,
|
|
72
|
+
*PFCP,
|
|
73
|
+
*USER_PLANE,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# tshark preferences applied when available. Lab cores often run NAS with the null cipher
|
|
77
|
+
# (NEA0); this lets tshark decode the 5GSM payload in those captures.
|
|
78
|
+
PREFERENCES = {"nas-5gs.null_decipher": "TRUE"}
|
|
79
|
+
|
|
80
|
+
DISPLAY_FILTER = "diameter or gtpv2 or nas-eps or s1ap or radius"
|