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/rules_5g.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""5G SA rules: NGAP, 5G NAS (5GMM/5GSM), PFCP and GTP-U user plane."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
|
|
8
|
+
from capsight.codes import lookup
|
|
9
|
+
from capsight.codes_5g import (
|
|
10
|
+
MM_AUTH_FAILURE,
|
|
11
|
+
MM_AUTH_REJECT,
|
|
12
|
+
MM_AUTH_RESPONSE,
|
|
13
|
+
MM_CAUSE,
|
|
14
|
+
MM_DL_NAS_TRANSPORT,
|
|
15
|
+
MM_MESSAGES,
|
|
16
|
+
MM_REJECTS,
|
|
17
|
+
MM_STATUS,
|
|
18
|
+
NGAP_CAUSE,
|
|
19
|
+
NGAP_CAUSE_GROUPS,
|
|
20
|
+
NGAP_PROCEDURES,
|
|
21
|
+
NGAP_UNSUCCESSFUL_OUTCOME,
|
|
22
|
+
PFCP_CAUSE,
|
|
23
|
+
SM_CAUSE,
|
|
24
|
+
SM_ESTABLISHMENT_REQUEST,
|
|
25
|
+
SM_REJECTS,
|
|
26
|
+
)
|
|
27
|
+
from capsight.correlate import to_int
|
|
28
|
+
from capsight.model import Finding, Packet, Severity
|
|
29
|
+
from capsight.rules import Context, _add, _emit, _Group, _unanswered, rule
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ints(packet: Packet, name: str) -> list[int]:
|
|
33
|
+
return [v for v in (to_int(x) for x in packet.fields.get(name, [])) if v is not None]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _ue_key(packet: Packet) -> str | None:
|
|
37
|
+
ids = packet.fields.get("ngap.RAN_UE_NGAP_ID", [])
|
|
38
|
+
return ids[0] if ids else None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _later(ctx: Context, after: Packet, ue: str | None, predicate) -> Packet | None:
|
|
42
|
+
for packet in ctx.packets:
|
|
43
|
+
if packet.number <= after.number or not packet.has("nas-5gs"):
|
|
44
|
+
continue
|
|
45
|
+
if ue is not None and _ue_key(packet) != ue:
|
|
46
|
+
continue
|
|
47
|
+
if predicate(packet):
|
|
48
|
+
return packet
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _earlier(ctx: Context, before: Packet, ue: str | None, predicate) -> Packet | None:
|
|
53
|
+
found = None
|
|
54
|
+
for packet in ctx.packets:
|
|
55
|
+
if packet.number >= before.number:
|
|
56
|
+
break
|
|
57
|
+
if packet.has("nas-5gs") and (ue is None or _ue_key(packet) == ue) and predicate(packet):
|
|
58
|
+
found = packet
|
|
59
|
+
return found
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@rule("ngap.failure")
|
|
63
|
+
def ngap_failures(ctx: Context) -> Iterator[Finding]:
|
|
64
|
+
groups: dict[object, _Group] = {}
|
|
65
|
+
for packet in ctx.packets:
|
|
66
|
+
if not packet.has("ngap"):
|
|
67
|
+
continue
|
|
68
|
+
if NGAP_UNSUCCESSFUL_OUTCOME not in _ints(packet, "ngap.NGAP_PDU"):
|
|
69
|
+
continue
|
|
70
|
+
proc = (_ints(packet, "ngap.procedureCode") or [-1])[0]
|
|
71
|
+
name = NGAP_PROCEDURES.get(proc, f"NGAP procedure {proc}")
|
|
72
|
+
group_idx = (_ints(packet, "ngap.Cause") or [-1])[0]
|
|
73
|
+
cause_group = (
|
|
74
|
+
NGAP_CAUSE_GROUPS[group_idx] if 0 <= group_idx < len(NGAP_CAUSE_GROUPS) else None
|
|
75
|
+
)
|
|
76
|
+
value = (_ints(packet, f"ngap.{cause_group}") or [None])[0] if cause_group else None
|
|
77
|
+
if cause_group and value is not None:
|
|
78
|
+
code = lookup(NGAP_CAUSE.get(cause_group, {}), value)
|
|
79
|
+
cause_text = f"{cause_group}={code.name}"
|
|
80
|
+
else:
|
|
81
|
+
code, cause_text = None, "no cause decoded"
|
|
82
|
+
key = (proc, cause_text)
|
|
83
|
+
if key not in groups:
|
|
84
|
+
groups[key] = _Group(
|
|
85
|
+
verdict=f"{name} failed: {cause_text}.",
|
|
86
|
+
why=f"The peer answered {name} with an unsuccessful outcome ({cause_text}).",
|
|
87
|
+
fix=(code.hint if code else "")
|
|
88
|
+
or "Compare the gNB and AMF configuration for this procedure.",
|
|
89
|
+
severity=Severity.FAILURE,
|
|
90
|
+
)
|
|
91
|
+
_add(groups[key], [packet], None)
|
|
92
|
+
yield from _emit("ngap.failure", groups)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@rule("nas5g.mm.reject")
|
|
96
|
+
def mm_rejects(ctx: Context) -> Iterator[Finding]:
|
|
97
|
+
groups: dict[object, _Group] = {}
|
|
98
|
+
for packet in ctx.packets:
|
|
99
|
+
if not packet.has("nas-5gs"):
|
|
100
|
+
continue
|
|
101
|
+
types = _ints(packet, "nas-5gs.mm.message_type")
|
|
102
|
+
causes = _ints(packet, "nas-5gs.mm.5gmm_cause")
|
|
103
|
+
imsi = ctx.imsi_of(packet)
|
|
104
|
+
ue = _ue_key(packet)
|
|
105
|
+
for mtype in types:
|
|
106
|
+
if mtype in MM_REJECTS and causes:
|
|
107
|
+
cause = causes[0]
|
|
108
|
+
code = lookup(MM_CAUSE, cause)
|
|
109
|
+
name = MM_MESSAGES[mtype]
|
|
110
|
+
key = ("reject", mtype, cause)
|
|
111
|
+
if key not in groups:
|
|
112
|
+
groups[key] = _Group(
|
|
113
|
+
verdict=f"{name}: {code.name}.",
|
|
114
|
+
why=f"The AMF sent {name} with 5GMM cause #{cause} ({code.name}).",
|
|
115
|
+
fix=code.hint,
|
|
116
|
+
severity=Severity.FAILURE,
|
|
117
|
+
)
|
|
118
|
+
_add(groups[key], [packet], imsi)
|
|
119
|
+
elif mtype == MM_AUTH_FAILURE and causes:
|
|
120
|
+
cause = causes[0]
|
|
121
|
+
code = lookup(MM_CAUSE, cause)
|
|
122
|
+
rejected = _later(
|
|
123
|
+
ctx, packet, ue, lambda p: MM_AUTH_REJECT in _ints(p, "nas-5gs.mm.message_type")
|
|
124
|
+
)
|
|
125
|
+
recovered = cause == 21 and _later(
|
|
126
|
+
ctx,
|
|
127
|
+
packet,
|
|
128
|
+
ue,
|
|
129
|
+
lambda p: MM_AUTH_RESPONSE in _ints(p, "nas-5gs.mm.message_type"),
|
|
130
|
+
)
|
|
131
|
+
key = ("auth", cause, bool(recovered))
|
|
132
|
+
if key not in groups:
|
|
133
|
+
if recovered:
|
|
134
|
+
groups[key] = _Group(
|
|
135
|
+
verdict="Sequence-number resync, then authentication succeeded.",
|
|
136
|
+
why=f"The device sent Authentication Failure, cause #{cause} "
|
|
137
|
+
f"({code.name}), and the next Authentication Response succeeded.",
|
|
138
|
+
fix="No action. This is normal on a SIM's first registration and "
|
|
139
|
+
"after the UDM loses SQN state.",
|
|
140
|
+
severity=Severity.INFO,
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
why = (
|
|
144
|
+
f"The device sent Authentication Failure, cause #{cause} ({code.name})."
|
|
145
|
+
)
|
|
146
|
+
if rejected is not None:
|
|
147
|
+
why += (
|
|
148
|
+
f" The network then sent Authentication Reject "
|
|
149
|
+
f"(packet #{rejected.number})."
|
|
150
|
+
)
|
|
151
|
+
groups[key] = _Group(
|
|
152
|
+
verdict=f"Device rejected network authentication: {code.name}.",
|
|
153
|
+
why=why,
|
|
154
|
+
fix=code.hint,
|
|
155
|
+
severity=Severity.WARNING if cause == 21 else Severity.FAILURE,
|
|
156
|
+
)
|
|
157
|
+
_add(groups[key], [packet], imsi)
|
|
158
|
+
elif mtype in (MM_STATUS, MM_DL_NAS_TRANSPORT) and causes:
|
|
159
|
+
cause = causes[0]
|
|
160
|
+
code = lookup(MM_CAUSE, cause)
|
|
161
|
+
request = _earlier(
|
|
162
|
+
ctx,
|
|
163
|
+
packet,
|
|
164
|
+
ue,
|
|
165
|
+
lambda p: SM_ESTABLISHMENT_REQUEST in _ints(p, "nas-5gs.sm.message_type"),
|
|
166
|
+
)
|
|
167
|
+
dnn = request.first("nas-5gs.cmn.dnn") if request else None
|
|
168
|
+
key = ("not_forwarded", cause, dnn)
|
|
169
|
+
if key not in groups:
|
|
170
|
+
subject = "PDU session request" if request else "NAS message"
|
|
171
|
+
why = f"The AMF answered with {MM_MESSAGES[mtype]}, 5GMM cause #{cause} "
|
|
172
|
+
why += f"({code.name})"
|
|
173
|
+
if request is not None:
|
|
174
|
+
why += " to the PDU Session Establishment Request in packet "
|
|
175
|
+
why += f"#{request.number}"
|
|
176
|
+
if dnn:
|
|
177
|
+
why += f" for DNN {dnn!r}"
|
|
178
|
+
why += ". The request never reached an SMF."
|
|
179
|
+
groups[key] = _Group(
|
|
180
|
+
verdict=f"{subject} refused by the AMF: {code.name}.",
|
|
181
|
+
why=why,
|
|
182
|
+
fix=code.hint,
|
|
183
|
+
severity=Severity.FAILURE,
|
|
184
|
+
)
|
|
185
|
+
group = groups[key]
|
|
186
|
+
evidence = [request, packet] if request else [packet]
|
|
187
|
+
_add(group, evidence, imsi)
|
|
188
|
+
yield from _emit("nas5g.mm.reject", groups)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@rule("nas5g.sm.reject")
|
|
192
|
+
def sm_rejects(ctx: Context) -> Iterator[Finding]:
|
|
193
|
+
groups: dict[object, _Group] = {}
|
|
194
|
+
for packet in ctx.packets:
|
|
195
|
+
if not packet.has("nas-5gs"):
|
|
196
|
+
continue
|
|
197
|
+
causes = _ints(packet, "nas-5gs.sm.5gsm_cause")
|
|
198
|
+
for mtype in _ints(packet, "nas-5gs.sm.message_type"):
|
|
199
|
+
if mtype not in SM_REJECTS or not causes:
|
|
200
|
+
continue
|
|
201
|
+
cause = causes[0]
|
|
202
|
+
code = lookup(SM_CAUSE, cause)
|
|
203
|
+
name = SM_REJECTS[mtype]
|
|
204
|
+
request = _earlier(
|
|
205
|
+
ctx,
|
|
206
|
+
packet,
|
|
207
|
+
_ue_key(packet),
|
|
208
|
+
lambda p: SM_ESTABLISHMENT_REQUEST in _ints(p, "nas-5gs.sm.message_type"),
|
|
209
|
+
)
|
|
210
|
+
dnn = request.first("nas-5gs.cmn.dnn") if request else None
|
|
211
|
+
key = (mtype, cause, dnn)
|
|
212
|
+
if key not in groups:
|
|
213
|
+
why = f"The SMF sent {name}, 5GSM cause #{cause} ({code.name})"
|
|
214
|
+
why += f" for DNN {dnn!r}." if dnn else "."
|
|
215
|
+
groups[key] = _Group(
|
|
216
|
+
verdict=f"{name}: {code.name}.",
|
|
217
|
+
why=why,
|
|
218
|
+
fix=code.hint,
|
|
219
|
+
severity=Severity.FAILURE,
|
|
220
|
+
)
|
|
221
|
+
_add(groups[key], [packet], ctx.imsi_of(packet))
|
|
222
|
+
yield from _emit("nas5g.sm.reject", groups)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@rule("pfcp.cause")
|
|
226
|
+
def pfcp_rejects(ctx: Context) -> Iterator[Finding]:
|
|
227
|
+
groups: dict[object, _Group] = {}
|
|
228
|
+
for tx in ctx.pfcp:
|
|
229
|
+
if tx.answer is None:
|
|
230
|
+
continue
|
|
231
|
+
cause = to_int(tx.answer.first("pfcp.cause"))
|
|
232
|
+
if cause is None or cause < 64:
|
|
233
|
+
continue
|
|
234
|
+
code = lookup(PFCP_CAUSE, cause)
|
|
235
|
+
key = (tx.name, cause)
|
|
236
|
+
if key not in groups:
|
|
237
|
+
groups[key] = _Group(
|
|
238
|
+
verdict=f"PFCP {tx.name} rejected: {code.name}.",
|
|
239
|
+
why=f"The UPF answered PFCP {tx.name} with cause {cause} ({code.name}).",
|
|
240
|
+
fix=code.hint,
|
|
241
|
+
severity=Severity.FAILURE,
|
|
242
|
+
)
|
|
243
|
+
group = groups[key]
|
|
244
|
+
_add(group, [p for p in (tx.request, tx.answer) if p], None)
|
|
245
|
+
group.retransmissions += tx.retransmissions
|
|
246
|
+
yield from _emit("pfcp.cause", groups)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@rule("pfcp.unanswered")
|
|
250
|
+
def pfcp_unanswered(ctx: Context) -> Iterator[Finding]:
|
|
251
|
+
yield from _unanswered(
|
|
252
|
+
ctx,
|
|
253
|
+
ctx.pfcp,
|
|
254
|
+
"pfcp.unanswered",
|
|
255
|
+
"The UPF (or SMF) did not answer. Check that the PFCP association is up, the peer is "
|
|
256
|
+
"reachable on UDP 8805, and its health.",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
ONE_WAY_MIN_PACKETS = 3
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
UE_POOL_RANGES = tuple(
|
|
264
|
+
ipaddress.ip_network(n)
|
|
265
|
+
for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "fc00::/7")
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _private(addr: str) -> bool:
|
|
270
|
+
"""RFC 1918 / CGNAT / ULA: addresses that need NAT to reach the internet."""
|
|
271
|
+
try:
|
|
272
|
+
ip = ipaddress.ip_address(addr)
|
|
273
|
+
except ValueError:
|
|
274
|
+
return False
|
|
275
|
+
return any(ip.version == net.version and ip in net for net in UE_POOL_RANGES)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@rule("gtpu.one_way")
|
|
279
|
+
def gtpu_one_way(ctx: Context) -> Iterator[Finding]:
|
|
280
|
+
"""Uplink user traffic enters the tunnel but nothing ever comes back."""
|
|
281
|
+
tunneled = ctx.flows.tunneled
|
|
282
|
+
plain = ctx.flows.plain
|
|
283
|
+
first_seen = ctx.flows.first_seen
|
|
284
|
+
groups: dict[object, _Group] = {}
|
|
285
|
+
for (src, dst), n in tunneled.items():
|
|
286
|
+
if n < ONE_WAY_MIN_PACKETS or tunneled.get((dst, src)) or plain.get((dst, src)):
|
|
287
|
+
continue
|
|
288
|
+
left_n6 = plain.get((src, dst), 0)
|
|
289
|
+
why = (
|
|
290
|
+
f"{n} GTP-U packets from {src} to {dst} went into the tunnel and none came back "
|
|
291
|
+
"(no reply inside or outside the tunnel)."
|
|
292
|
+
)
|
|
293
|
+
if left_n6:
|
|
294
|
+
why += (
|
|
295
|
+
f" The same packets were seen leaving towards the data network ({left_n6}x) "
|
|
296
|
+
f"still using the device's address {src} as source."
|
|
297
|
+
)
|
|
298
|
+
if _private(src) and not _private(dst):
|
|
299
|
+
fix = (
|
|
300
|
+
f"{src} is a private address, so replies from {dst} cannot route back. "
|
|
301
|
+
"Add NAT/masquerade for the UE address pool on the UPF's N6/SGi side, or "
|
|
302
|
+
"a return route for the pool."
|
|
303
|
+
)
|
|
304
|
+
else:
|
|
305
|
+
fix = "Check the return route from the data network to the UE address pool."
|
|
306
|
+
severity = Severity.FAILURE
|
|
307
|
+
else:
|
|
308
|
+
fix = (
|
|
309
|
+
"Check the UPF's N6/SGi side (routing and NAT for the UE pool). If the capture "
|
|
310
|
+
"only covers one direction, capture both before concluding."
|
|
311
|
+
)
|
|
312
|
+
severity = Severity.WARNING
|
|
313
|
+
key = (src, dst)
|
|
314
|
+
groups[key] = _Group(
|
|
315
|
+
verdict=f"User plane one-way: traffic from {src} to {dst} gets no reply.",
|
|
316
|
+
why=why,
|
|
317
|
+
fix=fix,
|
|
318
|
+
severity=severity,
|
|
319
|
+
evidence=[first_seen[key]],
|
|
320
|
+
count=1,
|
|
321
|
+
)
|
|
322
|
+
yield from _emit("gtpu.one_way", groups)
|
capsight/summary.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Summary mode: the shape of a busy capture in one screen.
|
|
2
|
+
|
|
3
|
+
Top problems by occurrences, the most affected subscribers, and problems over time.
|
|
4
|
+
Built from the findings, so it never says more than the rules found.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
|
|
12
|
+
from capsight.engine import Report
|
|
13
|
+
|
|
14
|
+
TOP_PROBLEMS = 10
|
|
15
|
+
TOP_SUBSCRIBERS = 10
|
|
16
|
+
MAX_ROWS = 24
|
|
17
|
+
BUCKETS = (1, 2, 5, 10, 15, 30, 60, 120, 240, 360, 720, 1440) # minutes
|
|
18
|
+
BAR = 40
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_summary(report: Report) -> dict:
|
|
22
|
+
problems = [f for f in report.findings if f.severity != "info"]
|
|
23
|
+
problems.sort(key=lambda f: (f.severity != "failure", -f.count))
|
|
24
|
+
subscribers: set[str] = set()
|
|
25
|
+
per_sub: Counter[str] = Counter()
|
|
26
|
+
per_sub_problems: dict[str, list[str]] = {}
|
|
27
|
+
minutes: Counter[int] = Counter()
|
|
28
|
+
for finding in problems:
|
|
29
|
+
subscribers.update(finding.subscribers)
|
|
30
|
+
for imsi, n in finding.by_subscriber:
|
|
31
|
+
per_sub[imsi] += n
|
|
32
|
+
per_sub_problems.setdefault(imsi, []).append(finding.verdict)
|
|
33
|
+
for minute, n in finding.per_minute:
|
|
34
|
+
minutes[minute] += n
|
|
35
|
+
bucket = _bucket(minutes)
|
|
36
|
+
timeline: Counter[int] = Counter()
|
|
37
|
+
for minute, n in minutes.items():
|
|
38
|
+
timeline[minute - minute % (bucket * 60)] += n
|
|
39
|
+
return {
|
|
40
|
+
"problems": len(problems),
|
|
41
|
+
"occurrences": sum(f.count for f in problems),
|
|
42
|
+
"subscribers_affected": len(subscribers),
|
|
43
|
+
"top_problems": [
|
|
44
|
+
{
|
|
45
|
+
"severity": str(f.severity),
|
|
46
|
+
"verdict": f.verdict,
|
|
47
|
+
"count": f.count,
|
|
48
|
+
"subscribers": len(f.subscribers),
|
|
49
|
+
"first": _clock(f.first_time),
|
|
50
|
+
"last": _clock(f.last_time),
|
|
51
|
+
"rule_id": f.rule_id,
|
|
52
|
+
}
|
|
53
|
+
for f in problems[:TOP_PROBLEMS]
|
|
54
|
+
],
|
|
55
|
+
"top_subscribers": [
|
|
56
|
+
{"imsi": imsi, "count": n, "problems": per_sub_problems[imsi]}
|
|
57
|
+
for imsi, n in per_sub.most_common(TOP_SUBSCRIBERS)
|
|
58
|
+
],
|
|
59
|
+
"bucket_minutes": bucket,
|
|
60
|
+
"over_time": [(_clock(t, seconds=False), n) for t, n in sorted(timeline.items())],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _bucket(minutes: Counter[int]) -> int:
|
|
65
|
+
if not minutes:
|
|
66
|
+
return 1
|
|
67
|
+
first, last = min(minutes), max(minutes)
|
|
68
|
+
for b in BUCKETS:
|
|
69
|
+
size = b * 60
|
|
70
|
+
rows = (last - last % size - (first - first % size)) // size + 1
|
|
71
|
+
if rows <= MAX_ROWS:
|
|
72
|
+
return b
|
|
73
|
+
return BUCKETS[-1]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _clock(epoch: float | None, seconds: bool = True) -> str | None:
|
|
77
|
+
if epoch is None:
|
|
78
|
+
return None
|
|
79
|
+
fmt = "%Y-%m-%d %H:%M:%S" if seconds else "%Y-%m-%d %H:%M"
|
|
80
|
+
return datetime.fromtimestamp(epoch, UTC).strftime(fmt)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def render_summary(summary: dict) -> list[str]:
|
|
84
|
+
lines = [""]
|
|
85
|
+
if not summary["problems"]:
|
|
86
|
+
lines.append("summary no problems found.")
|
|
87
|
+
return lines
|
|
88
|
+
lines.append(
|
|
89
|
+
f"summary {summary['problems']} problem{'s' if summary['problems'] != 1 else ''}, "
|
|
90
|
+
f"{summary['occurrences']:,} occurrence{'s' if summary['occurrences'] != 1 else ''}, "
|
|
91
|
+
f"{summary['subscribers_affected']:,} "
|
|
92
|
+
f"subscriber{'s' if summary['subscribers_affected'] != 1 else ''} affected"
|
|
93
|
+
)
|
|
94
|
+
lines += ["", "TOP PROBLEMS"]
|
|
95
|
+
for i, p in enumerate(summary["top_problems"], 1):
|
|
96
|
+
when = p["first"][11:] if p["first"] else "?"
|
|
97
|
+
if p["last"] and p["last"] != p["first"]:
|
|
98
|
+
when += f" - {p['last'][11:]}"
|
|
99
|
+
n = p["subscribers"]
|
|
100
|
+
subs = f", {n:,} subscriber{'s' if n != 1 else ''}" if n else ""
|
|
101
|
+
lines.append(f" {i:>2}. {p['severity'].upper():<8} {p['count']:>8,}x {p['verdict']}")
|
|
102
|
+
lines.append(f" {'':<8} {'':>9} {when} UTC{subs}")
|
|
103
|
+
if summary["top_subscribers"]:
|
|
104
|
+
lines += ["", "MOST AFFECTED SUBSCRIBERS"]
|
|
105
|
+
for s in summary["top_subscribers"]:
|
|
106
|
+
first = s["problems"][0]
|
|
107
|
+
more = f" (+{len(s['problems']) - 1} more)" if len(s["problems"]) > 1 else ""
|
|
108
|
+
lines.append(f" {s['imsi']:<16} {s['count']:>8,}x {first}{more}")
|
|
109
|
+
rows = summary["over_time"]
|
|
110
|
+
if len(rows) > 1:
|
|
111
|
+
peak = max(n for _, n in rows)
|
|
112
|
+
lines += ["", f"OVER TIME (UTC, per {summary['bucket_minutes']} min)"]
|
|
113
|
+
for label, n in rows:
|
|
114
|
+
bar = "#" * max(1, round(BAR * n / peak))
|
|
115
|
+
lines.append(f" {label} {bar} {n:,}")
|
|
116
|
+
return lines
|
capsight/timeline.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Per-subscriber view: one subscriber's procedures in order, and where they broke."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from capsight.codes import (
|
|
9
|
+
AUTH_FAILURE_CAUSE,
|
|
10
|
+
DIAMETER_EXPERIMENTAL,
|
|
11
|
+
DIAMETER_RESULT,
|
|
12
|
+
EMM_CAUSE,
|
|
13
|
+
EMM_MESSAGES,
|
|
14
|
+
EMM_REJECTS,
|
|
15
|
+
ESM_CAUSE,
|
|
16
|
+
GTPV2_CAUSE,
|
|
17
|
+
lookup,
|
|
18
|
+
)
|
|
19
|
+
from capsight.codes_5g import MM_CAUSE, MM_MESSAGES, MM_REJECTS, SM_CAUSE, SM_REJECTS
|
|
20
|
+
from capsight.correlate import Transaction, to_int
|
|
21
|
+
from capsight.model import Finding, Packet
|
|
22
|
+
from capsight.rules import Context
|
|
23
|
+
|
|
24
|
+
OK, FAILED, NO_ANSWER, INFO = "ok", "failed", "no answer", "info"
|
|
25
|
+
|
|
26
|
+
ESM_MESSAGES: dict[int, str] = {
|
|
27
|
+
0xC1: "Activate Default EPS Bearer Context Request",
|
|
28
|
+
0xC2: "Activate Default EPS Bearer Context Accept",
|
|
29
|
+
0xC3: "Activate Default EPS Bearer Context Reject",
|
|
30
|
+
0xC5: "Activate Dedicated EPS Bearer Context Request",
|
|
31
|
+
0xCD: "Deactivate EPS Bearer Context Request",
|
|
32
|
+
0xD0: "PDN Connectivity Request",
|
|
33
|
+
0xD1: "PDN Connectivity Reject",
|
|
34
|
+
0xD2: "PDN Disconnect Request",
|
|
35
|
+
0xD9: "ESM Information Request",
|
|
36
|
+
0xDA: "ESM Information Response",
|
|
37
|
+
}
|
|
38
|
+
ESM_REJECTS = {0xC3, 0xD1}
|
|
39
|
+
|
|
40
|
+
SM_MESSAGES: dict[int, str] = {
|
|
41
|
+
0xC1: "PDU Session Establishment Request",
|
|
42
|
+
0xC2: "PDU Session Establishment Accept",
|
|
43
|
+
0xC9: "PDU Session Modification Request",
|
|
44
|
+
0xCC: "PDU Session Modification Command",
|
|
45
|
+
0xD1: "PDU Session Release Request",
|
|
46
|
+
0xD3: "PDU Session Release Command",
|
|
47
|
+
**SM_REJECTS,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
EMM_AUTH_FAILURE = 0x5C
|
|
51
|
+
MM_AUTH_FAILURE = 0x59
|
|
52
|
+
MM_STATUS_LIKE = {0x64, 0x68}
|
|
53
|
+
SYNC_FAILURE = 21 # same value in EMM and 5GMM; the network normally resyncs and retries
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Step:
|
|
58
|
+
"""One procedure (request/answer pair) or one NAS message for the subscriber."""
|
|
59
|
+
|
|
60
|
+
time: float
|
|
61
|
+
packets: tuple[int, ...]
|
|
62
|
+
protocol: str
|
|
63
|
+
name: str
|
|
64
|
+
status: str
|
|
65
|
+
detail: str = ""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def normalize_imsi(value: str) -> str:
|
|
69
|
+
"""Accept 001010000000001, imsi-001010000000001 or 001 01 0000000001."""
|
|
70
|
+
return re.sub(r"\D", "", value.removeprefix("imsi-"))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _diameter_step(tx: Transaction, ctx: Context) -> Step:
|
|
74
|
+
request = tx.request
|
|
75
|
+
first = tx.first_packet
|
|
76
|
+
answer_name = tx.name[:-1] + "A" if tx.name.endswith("R") else "answer"
|
|
77
|
+
packets = tuple(p.number for p in (request, tx.answer) if p)
|
|
78
|
+
if tx.answer is None:
|
|
79
|
+
return Step(first.time, packets, "diameter", tx.name, _missing(ctx, first), "")
|
|
80
|
+
exp = to_int(tx.answer.first("diameter.Experimental-Result-Code"))
|
|
81
|
+
res = to_int(tx.answer.first("diameter.Result-Code"))
|
|
82
|
+
if exp is not None and exp >= 3000:
|
|
83
|
+
code = lookup(DIAMETER_EXPERIMENTAL, exp)
|
|
84
|
+
return Step(
|
|
85
|
+
first.time,
|
|
86
|
+
packets,
|
|
87
|
+
"diameter",
|
|
88
|
+
f"{tx.name} -> {answer_name}",
|
|
89
|
+
FAILED,
|
|
90
|
+
f"{code.name} ({exp})",
|
|
91
|
+
)
|
|
92
|
+
if res is not None and res >= 3000:
|
|
93
|
+
code = lookup(DIAMETER_RESULT, res)
|
|
94
|
+
return Step(
|
|
95
|
+
first.time,
|
|
96
|
+
packets,
|
|
97
|
+
"diameter",
|
|
98
|
+
f"{tx.name} -> {answer_name}",
|
|
99
|
+
FAILED,
|
|
100
|
+
f"{code.name} ({res})",
|
|
101
|
+
)
|
|
102
|
+
value = exp if exp is not None else res
|
|
103
|
+
return Step(
|
|
104
|
+
first.time,
|
|
105
|
+
packets,
|
|
106
|
+
"diameter",
|
|
107
|
+
f"{tx.name} -> {answer_name}",
|
|
108
|
+
OK,
|
|
109
|
+
str(value) if value is not None else "",
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _gtpv2_step(tx: Transaction, ctx: Context) -> Step:
|
|
114
|
+
first = tx.first_packet
|
|
115
|
+
packets = tuple(p.number for p in (tx.request, tx.answer) if p)
|
|
116
|
+
name = tx.name.removesuffix(" Request")
|
|
117
|
+
n = tx.retransmissions
|
|
118
|
+
retx = f", {n} retransmission{'s' if n != 1 else ''}" if n else ""
|
|
119
|
+
apn = tx.request.first("gtpv2.apn") if tx.request else None
|
|
120
|
+
apn_text = f"APN {apn}" if apn else ""
|
|
121
|
+
if tx.answer is None:
|
|
122
|
+
detail = ", ".join(x for x in (apn_text, retx.lstrip(", ")) if x)
|
|
123
|
+
return Step(first.time, packets, "gtpv2", name, _missing(ctx, first), detail)
|
|
124
|
+
cause = to_int(tx.answer.first("gtpv2.cause"))
|
|
125
|
+
if cause is None:
|
|
126
|
+
return Step(first.time, packets, "gtpv2", name, INFO, apn_text)
|
|
127
|
+
code = lookup(GTPV2_CAUSE, cause)
|
|
128
|
+
status = OK if 16 <= cause <= 63 else FAILED
|
|
129
|
+
detail = f"cause {cause} ({code.name})"
|
|
130
|
+
if apn_text:
|
|
131
|
+
detail = f"{apn_text}, {detail}"
|
|
132
|
+
return Step(first.time, packets, "gtpv2", name, status, detail + retx)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _missing(ctx: Context, request: Packet) -> str:
|
|
136
|
+
waited = ctx.capture_end - request.time
|
|
137
|
+
return NO_ANSWER if waited >= ctx.answer_timeout else INFO
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _nas_eps_steps(packet: Packet) -> list[Step]:
|
|
141
|
+
steps = []
|
|
142
|
+
emm = to_int(packet.first("nas-eps.nas_msg_emm_type"))
|
|
143
|
+
if emm is not None:
|
|
144
|
+
name = EMM_MESSAGES.get(emm, f"EMM message 0x{emm:02x}")
|
|
145
|
+
cause = to_int(packet.first("nas-eps.emm.cause"))
|
|
146
|
+
if emm in EMM_REJECTS or emm == 0x54:
|
|
147
|
+
detail = f"EMM cause #{cause} ({lookup(EMM_CAUSE, cause).name})" if cause else ""
|
|
148
|
+
steps.append(Step(packet.time, (packet.number,), "nas", name, FAILED, detail))
|
|
149
|
+
elif emm == EMM_AUTH_FAILURE:
|
|
150
|
+
detail = f"cause #{cause} ({lookup(AUTH_FAILURE_CAUSE, cause).name})" if cause else ""
|
|
151
|
+
status = INFO if cause == SYNC_FAILURE else FAILED
|
|
152
|
+
steps.append(Step(packet.time, (packet.number,), "nas", name, status, detail))
|
|
153
|
+
else:
|
|
154
|
+
steps.append(Step(packet.time, (packet.number,), "nas", name, OK))
|
|
155
|
+
esm = to_int(packet.first("nas-eps.nas_msg_esm_type"))
|
|
156
|
+
if esm is not None:
|
|
157
|
+
name = ESM_MESSAGES.get(esm, f"ESM message 0x{esm:02x}")
|
|
158
|
+
cause = to_int(packet.first("nas-eps.esm.cause"))
|
|
159
|
+
if esm in ESM_REJECTS:
|
|
160
|
+
detail = f"ESM cause #{cause} ({lookup(ESM_CAUSE, cause).name})" if cause else ""
|
|
161
|
+
steps.append(Step(packet.time, (packet.number,), "nas", name, FAILED, detail))
|
|
162
|
+
else:
|
|
163
|
+
steps.append(Step(packet.time, (packet.number,), "nas", name, OK))
|
|
164
|
+
return steps
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _nas_5gs_steps(packet: Packet) -> list[Step]:
|
|
168
|
+
steps = []
|
|
169
|
+
mm_causes = packet.fields.get("nas-5gs.mm.5gmm_cause", [])
|
|
170
|
+
mm_cause = to_int(mm_causes[0]) if mm_causes else None
|
|
171
|
+
for raw in packet.fields.get("nas-5gs.mm.message_type", []):
|
|
172
|
+
mtype = to_int(raw)
|
|
173
|
+
if mtype is None or mtype in (0x67, 0x68) and mm_cause is None:
|
|
174
|
+
continue # NAS transport containers: the 5GSM message inside is listed instead
|
|
175
|
+
name = MM_MESSAGES.get(mtype, f"5GMM message 0x{mtype:02x}")
|
|
176
|
+
failed = (
|
|
177
|
+
mtype in MM_REJECTS
|
|
178
|
+
or mtype in (0x58, MM_AUTH_FAILURE)
|
|
179
|
+
or (mtype in MM_STATUS_LIKE and mm_cause is not None)
|
|
180
|
+
)
|
|
181
|
+
detail = ""
|
|
182
|
+
if failed and mm_cause is not None:
|
|
183
|
+
detail = f"5GMM cause #{mm_cause} ({lookup(MM_CAUSE, mm_cause).name})"
|
|
184
|
+
steps.append(
|
|
185
|
+
Step(packet.time, (packet.number,), "nas-5g", name, FAILED if failed else OK, detail)
|
|
186
|
+
)
|
|
187
|
+
sm_causes = packet.fields.get("nas-5gs.sm.5gsm_cause", [])
|
|
188
|
+
for raw in packet.fields.get("nas-5gs.sm.message_type", []):
|
|
189
|
+
mtype = to_int(raw)
|
|
190
|
+
if mtype is None:
|
|
191
|
+
continue
|
|
192
|
+
name = SM_MESSAGES.get(mtype, f"5GSM message 0x{mtype:02x}")
|
|
193
|
+
dnn = packet.first("nas-5gs.cmn.dnn")
|
|
194
|
+
detail = f"DNN {dnn}" if dnn else ""
|
|
195
|
+
if mtype in SM_REJECTS:
|
|
196
|
+
cause = to_int(sm_causes[0]) if sm_causes else None
|
|
197
|
+
if cause is not None:
|
|
198
|
+
detail = f"5GSM cause #{cause} ({lookup(SM_CAUSE, cause).name})"
|
|
199
|
+
steps.append(Step(packet.time, (packet.number,), "nas-5g", name, FAILED, detail))
|
|
200
|
+
else:
|
|
201
|
+
steps.append(Step(packet.time, (packet.number,), "nas-5g", name, OK, detail))
|
|
202
|
+
return steps
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def subscriber_timeline(ctx: Context, imsi: str) -> list[Step]:
|
|
206
|
+
steps: list[Step] = []
|
|
207
|
+
for tx in ctx.diameter:
|
|
208
|
+
if tx.imsi == imsi:
|
|
209
|
+
steps.append(_diameter_step(tx, ctx))
|
|
210
|
+
for tx in ctx.gtpv2:
|
|
211
|
+
if tx.imsi == imsi:
|
|
212
|
+
steps.append(_gtpv2_step(tx, ctx))
|
|
213
|
+
for packet in ctx.packets:
|
|
214
|
+
if ctx.imsi_of(packet) != imsi:
|
|
215
|
+
continue
|
|
216
|
+
if packet.has("nas-eps"):
|
|
217
|
+
steps.extend(_nas_eps_steps(packet))
|
|
218
|
+
if packet.has("nas-5gs"):
|
|
219
|
+
steps.extend(_nas_5gs_steps(packet))
|
|
220
|
+
return sorted(steps, key=lambda s: (s.packets[0], s.time))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def subscribers_seen(ctx: Context) -> list[str]:
|
|
224
|
+
seen: dict[str, None] = {}
|
|
225
|
+
for tx in (*ctx.diameter, *ctx.gtpv2):
|
|
226
|
+
if tx.imsi:
|
|
227
|
+
seen.setdefault(tx.imsi)
|
|
228
|
+
for packet in ctx.packets:
|
|
229
|
+
imsi = ctx.imsi_of(packet)
|
|
230
|
+
if imsi:
|
|
231
|
+
seen.setdefault(imsi)
|
|
232
|
+
return [i for i in seen if i.isdigit()]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def findings_for(findings: list[Finding], imsi: str, steps: list[Step]) -> list[Finding]:
|
|
236
|
+
"""Findings that name the subscriber, or that cite one of its packets."""
|
|
237
|
+
own = {n for s in steps for n in s.packets}
|
|
238
|
+
return [f for f in findings if imsi in f.subscribers or own & set(f.evidence)]
|