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/rules.py ADDED
@@ -0,0 +1,522 @@
1
+ """Deterministic diagnosis rules. Rules decide; nothing here guesses.
2
+
3
+ Each rule takes the analysis context and yields Findings that cite packet numbers.
4
+ Repeated occurrences of the same failure are grouped into one Finding.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable, Iterator
10
+ from dataclasses import dataclass, field
11
+
12
+ from capsight.codes import (
13
+ AUTH_FAILURE_CAUSE,
14
+ DIAMETER_EXPERIMENTAL,
15
+ DIAMETER_RESULT,
16
+ EMM_CAUSE,
17
+ EMM_MESSAGES,
18
+ EMM_REJECTS,
19
+ ESM_CAUSE,
20
+ GTPV2_CAUSE,
21
+ lookup,
22
+ )
23
+ from capsight.correlate import Transaction, to_bool, to_int
24
+ from capsight.model import Finding, Packet, Severity
25
+
26
+ MAX_EVIDENCE = 5
27
+ ESM_PDN_CONNECTIVITY_REJECT = 0xD1
28
+
29
+
30
+ @dataclass
31
+ class UserPlane:
32
+ """IP flow counts gathered while streaming, for user-plane rules."""
33
+
34
+ tunneled: dict[tuple[str, str], int] = field(default_factory=dict)
35
+ plain: dict[tuple[str, str], int] = field(default_factory=dict)
36
+ first_seen: dict[tuple[str, str], int] = field(default_factory=dict)
37
+
38
+ def feed(self, packet: Packet) -> None:
39
+ srcs = packet.fields.get("ip.src")
40
+ dsts = packet.fields.get("ip.dst")
41
+ if not srcs or not dsts:
42
+ return
43
+ if packet.has("gtp") and not packet.has("gtpv2"):
44
+ if len(srcs) >= 2 and len(dsts) >= 2:
45
+ flow = (srcs[-1], dsts[-1])
46
+ self.tunneled[flow] = self.tunneled.get(flow, 0) + 1
47
+ self.first_seen.setdefault(flow, packet.number)
48
+ elif not packet.has("gtp"):
49
+ flow = (srcs[0], dsts[0])
50
+ self.plain[flow] = self.plain.get(flow, 0) + 1
51
+
52
+
53
+ @dataclass
54
+ class Context:
55
+ """What rules see. `packets` holds only signalling packets (NAS, S1AP, NGAP, RADIUS);
56
+ Diameter, GTPv2-C and PFCP are in the transaction lists, user plane in `flows`."""
57
+
58
+ packets: list[Packet]
59
+ diameter: list[Transaction]
60
+ gtpv2: list[Transaction]
61
+ capture_end: float
62
+ answer_timeout: float = 5.0
63
+ inferred_imsi: dict[int, str] = field(default_factory=dict)
64
+ pfcp: list[Transaction] = field(default_factory=list)
65
+ flows: UserPlane = field(default_factory=UserPlane)
66
+
67
+ def imsi_of(self, packet: Packet) -> str | None:
68
+ return packet.first("e212.imsi") or self.inferred_imsi.get(packet.number)
69
+
70
+
71
+ @dataclass
72
+ class _Group:
73
+ verdict: str
74
+ why: str
75
+ fix: str
76
+ severity: Severity
77
+ evidence: list[int] = field(default_factory=list)
78
+ imsis: set[str] = field(default_factory=set)
79
+ count: int = 0
80
+ retransmissions: int = 0
81
+ times: list[float] = field(default_factory=list)
82
+ per_imsi: dict[str, int] = field(default_factory=dict)
83
+
84
+
85
+ TOP_SUBSCRIBERS = 50
86
+
87
+ Rule = Callable[[Context], Iterator[Finding]]
88
+ RULES: list[tuple[str, Rule]] = []
89
+
90
+
91
+ def rule(rule_id: str) -> Callable[[Rule], Rule]:
92
+ def register(fn: Rule) -> Rule:
93
+ RULES.append((rule_id, fn))
94
+ return fn
95
+
96
+ return register
97
+
98
+
99
+ def _emit(rule_id: str, groups: dict[object, _Group]) -> Iterator[Finding]:
100
+ for group in groups.values():
101
+ why = group.why
102
+ if group.count > 1:
103
+ why += f" Seen {group.count} times"
104
+ if len(group.imsis) > 1:
105
+ why += f" across {len(group.imsis)} subscribers"
106
+ why += "."
107
+ if group.retransmissions:
108
+ why += (
109
+ f" Plus {group.retransmissions} retransmitted copies, not counted as "
110
+ "separate failures."
111
+ )
112
+ yield Finding(
113
+ rule_id=rule_id,
114
+ severity=group.severity,
115
+ verdict=group.verdict,
116
+ why=why,
117
+ evidence=tuple(group.evidence[:MAX_EVIDENCE]),
118
+ fix=group.fix,
119
+ subscribers=tuple(sorted(group.imsis)),
120
+ count=group.count,
121
+ first_time=min(group.times) if group.times else None,
122
+ last_time=max(group.times) if group.times else None,
123
+ per_minute=_per_minute(group.times),
124
+ by_subscriber=tuple(
125
+ sorted(group.per_imsi.items(), key=lambda kv: (-kv[1], kv[0]))[:TOP_SUBSCRIBERS]
126
+ ),
127
+ )
128
+
129
+
130
+ def _per_minute(times: list[float]) -> tuple[tuple[int, int], ...]:
131
+ buckets: dict[int, int] = {}
132
+ for t in times:
133
+ minute = int(t // 60) * 60
134
+ buckets[minute] = buckets.get(minute, 0) + 1
135
+ return tuple(sorted(buckets.items()))
136
+
137
+
138
+ def _add(group: _Group, packets: list[Packet], imsi: str | None) -> None:
139
+ group.count += 1
140
+ if len(group.evidence) < MAX_EVIDENCE:
141
+ group.evidence.extend(p.number for p in packets)
142
+ if packets:
143
+ group.times.append(packets[-1].time)
144
+ if imsi:
145
+ group.imsis.add(imsi)
146
+ group.per_imsi[imsi] = group.per_imsi.get(imsi, 0) + 1
147
+
148
+
149
+ @rule("diameter.result")
150
+ def diameter_failures(ctx: Context) -> Iterator[Finding]:
151
+ groups: dict[object, _Group] = {}
152
+ for tx in ctx.diameter:
153
+ if tx.answer is None:
154
+ continue
155
+ exp = to_int(tx.answer.first("diameter.Experimental-Result-Code"))
156
+ res = to_int(tx.answer.first("diameter.Result-Code"))
157
+ if exp is not None and exp >= 3000:
158
+ code, kind = lookup(DIAMETER_EXPERIMENTAL, exp), "Experimental-Result-Code"
159
+ value = exp
160
+ elif res is not None and res >= 3000:
161
+ code, kind = lookup(DIAMETER_RESULT, res), "Result-Code"
162
+ value = res
163
+ else:
164
+ continue
165
+ answer_name = tx.name[:-1] + "A" if tx.name.endswith("R") else tx.name
166
+ key = (tx.name, kind, value)
167
+ if key not in groups:
168
+ groups[key] = _Group(
169
+ verdict=f"{tx.name} rejected: {code.name}.",
170
+ why=f"{answer_name} carried {kind} {value} ({code.name}).",
171
+ fix=code.hint,
172
+ severity=Severity.FAILURE,
173
+ )
174
+ _add(groups[key], [p for p in (tx.request, tx.answer) if p], tx.imsi)
175
+ yield from _emit("diameter.result", groups)
176
+
177
+
178
+ ONE_WAY_MIN_REQUESTS = 20
179
+ ONE_WAY_MAX_ANSWER_RATIO = 0.05
180
+
181
+
182
+ def _unanswered(
183
+ ctx: Context,
184
+ txs: list[Transaction],
185
+ rule_id: str,
186
+ fix: str,
187
+ ) -> Iterator[Finding]:
188
+ """Requests with no answer, unless the capture simply does not contain the answers.
189
+
190
+ If a command type has many requests and almost no answers at all, the capture is most
191
+ likely one-directional (filtered on one host, one side of a mirror port). Reporting
192
+ thousands of timeouts would be wrong, so that case becomes a single warning.
193
+ """
194
+ requests: dict[str, int] = {}
195
+ answers: dict[str, int] = {}
196
+ for tx in txs:
197
+ if tx.request is not None:
198
+ requests[tx.name] = requests.get(tx.name, 0) + 1
199
+ if tx.answer is not None:
200
+ answers[tx.name] = answers.get(tx.name, 0) + 1
201
+ one_way = {
202
+ name
203
+ for name, n in requests.items()
204
+ if n >= ONE_WAY_MIN_REQUESTS and answers.get(name, 0) / n <= ONE_WAY_MAX_ANSWER_RATIO
205
+ }
206
+ groups: dict[object, _Group] = {}
207
+ for tx in txs:
208
+ if tx.answer is not None or tx.request is None:
209
+ continue
210
+ if ctx.capture_end - tx.request.time < ctx.answer_timeout:
211
+ continue # capture ended too soon to call it a timeout
212
+ if tx.name in one_way:
213
+ key = ("one_way", tx.name)
214
+ if key not in groups:
215
+ n, a = requests[tx.name], answers.get(tx.name, 0)
216
+ groups[key] = _Group(
217
+ verdict=f"Capture looks one-directional for {tx.name}: answers are missing.",
218
+ why=f"{n} {tx.name} requests but only {a} answers in the whole capture. "
219
+ "That pattern means the answers were not captured (capture filtered on "
220
+ "one host or one direction), not that the peer stopped answering.",
221
+ fix="Capture both directions (both peers' addresses) before concluding "
222
+ "requests timed out.",
223
+ severity=Severity.WARNING,
224
+ )
225
+ _add(groups[key], [tx.request], tx.imsi)
226
+ continue
227
+ if tx.name not in groups:
228
+ groups[tx.name] = _Group(
229
+ verdict=f"{tx.name} never answered.",
230
+ why=f"No answer to {tx.name} within {ctx.answer_timeout:g} s.",
231
+ fix=fix,
232
+ severity=Severity.FAILURE,
233
+ )
234
+ _add(groups[tx.name], [tx.request], tx.imsi)
235
+ yield from _emit(rule_id, groups)
236
+
237
+
238
+ @rule("diameter.unanswered")
239
+ def diameter_unanswered(ctx: Context) -> Iterator[Finding]:
240
+ yield from _unanswered(
241
+ ctx,
242
+ ctx.diameter,
243
+ "diameter.unanswered",
244
+ "The peer or a routing agent dropped the request. Check the Diameter connection "
245
+ "state and routing for the destination realm.",
246
+ )
247
+
248
+
249
+ PDN_TYPES = {1: "IPv4", 2: "IPv6", 3: "IPv4v6", 4: "non-IP", 5: "Ethernet"}
250
+ GTP_USER_AUTH_FAILED = 92
251
+ GTP_PDN_TYPE_NOT_SUPPORTED = 83
252
+ RADIUS_ACCESS_ACCEPT = 2
253
+ RADIUS_LOOKBACK_S = 2.0
254
+
255
+
256
+ def _cause_source(answer: Packet) -> str:
257
+ """GTPv2 CS bit: 1 = the cause came from a node further down the path."""
258
+ return "remote" if to_bool(answer.first("gtpv2.cs")) else "local"
259
+
260
+
261
+ def _radius_accept_before(ctx: Context, answer: Packet) -> Packet | None:
262
+ """Most recent RADIUS Access-Accept within RADIUS_LOOKBACK_S before `answer`."""
263
+ best = None
264
+ for packet in ctx.packets:
265
+ if packet.number >= answer.number:
266
+ break
267
+ if not packet.has("radius") or answer.time - packet.time > RADIUS_LOOKBACK_S:
268
+ continue
269
+ if to_int(packet.first("radius.code")) == RADIUS_ACCESS_ACCEPT:
270
+ best = packet
271
+ return best
272
+
273
+
274
+ @rule("gtpv2.cause")
275
+ def gtpv2_rejects(ctx: Context) -> Iterator[Finding]:
276
+ groups: dict[object, _Group] = {}
277
+ for tx in ctx.gtpv2:
278
+ if tx.answer is None:
279
+ continue
280
+ cause = to_int(tx.answer.first("gtpv2.cause"))
281
+ if cause is None or 16 <= cause <= 63:
282
+ continue
283
+ code = lookup(GTPV2_CAUSE, cause)
284
+ source = _cause_source(tx.answer)
285
+ accept = _radius_accept_before(ctx, tx.answer) if cause == GTP_USER_AUTH_FAILED else None
286
+ key = (tx.name, cause, source, accept is not None)
287
+ if key not in groups:
288
+ apn = tx.request.first("gtpv2.apn") if tx.request else None
289
+ why = f"Response carried cause {cause} ({code.name})"
290
+ why += f" for APN {apn}." if apn else "."
291
+ why += (
292
+ " The cause was raised by a node further down the path, not by the responder."
293
+ if source == "remote"
294
+ else " The responding node raised the cause itself."
295
+ )
296
+ fix = code.hint
297
+ if accept is not None:
298
+ why += (
299
+ f" RADIUS returned Access-Accept (packet #{accept.number}) just before, so "
300
+ "the credentials were accepted."
301
+ )
302
+ fix = (
303
+ "Not a credential problem: RADIUS accepted the user but the gateway still "
304
+ "refused the session. Compare this Access-Accept with one from a working "
305
+ "session on the same gateway; look for a missing or different attribute "
306
+ "(e.g. Framed-IP, Called-Station-Id, a vendor-specific policy)."
307
+ )
308
+ groups[key] = _Group(
309
+ verdict=f"{tx.name} rejected: {code.name}.",
310
+ why=why,
311
+ fix=fix,
312
+ severity=Severity.FAILURE,
313
+ )
314
+ group = groups[key]
315
+ _add(group, [p for p in (tx.request, tx.answer) if p], tx.imsi)
316
+ group.retransmissions += tx.retransmissions
317
+ yield from _emit("gtpv2.cause", groups)
318
+
319
+
320
+ @rule("gtpv2.pdn_type")
321
+ def pdn_type_split(ctx: Context) -> Iterator[Finding]:
322
+ """Same subscriber: one PDN type accepted, another rejected with cause 83."""
323
+ accepted: dict[str, set[int]] = {}
324
+ rejected: dict[str, list[Transaction]] = {}
325
+ for tx in ctx.gtpv2:
326
+ if tx.request is None or tx.answer is None or not tx.imsi:
327
+ continue
328
+ pdn_type = to_int(tx.request.first("gtpv2.pdn_type"))
329
+ cause = to_int(tx.answer.first("gtpv2.cause"))
330
+ if pdn_type is None or cause is None:
331
+ continue
332
+ if 16 <= cause <= 63:
333
+ accepted.setdefault(tx.imsi, set()).add(pdn_type)
334
+ elif cause == GTP_PDN_TYPE_NOT_SUPPORTED:
335
+ rejected.setdefault(tx.imsi, []).append(tx)
336
+ groups: dict[object, _Group] = {}
337
+ for imsi, txs in rejected.items():
338
+ ok_types = accepted.get(imsi, set())
339
+ for tx in txs:
340
+ assert tx.request is not None and tx.answer is not None
341
+ bad = to_int(tx.request.first("gtpv2.pdn_type"))
342
+ if bad in ok_types or not ok_types:
343
+ continue
344
+ ok_names = "/".join(PDN_TYPES.get(t, str(t)) for t in sorted(ok_types))
345
+ bad_name = PDN_TYPES.get(bad, str(bad))
346
+ key = (bad, tuple(sorted(ok_types)))
347
+ if key not in groups:
348
+ groups[key] = _Group(
349
+ verdict=f"{bad_name} sessions rejected while {ok_names} works.",
350
+ why=f"The same subscriber got cause 83 (Preferred PDN Type not supported) "
351
+ f"when requesting {bad_name}, and acceptance when requesting {ok_names}. "
352
+ "The failure follows the PDN type, not the APN or the subscription.",
353
+ fix=f"Either enable {bad_name} for this APN on the gateway, or set the "
354
+ f"device/APN profile to request {ok_names}.",
355
+ severity=Severity.FAILURE,
356
+ )
357
+ _add(groups[key], [tx.request, tx.answer], imsi)
358
+ yield from _emit("gtpv2.pdn_type", groups)
359
+
360
+
361
+ @rule("gtpv2.unanswered")
362
+ def gtpv2_unanswered(ctx: Context) -> Iterator[Finding]:
363
+ yield from _unanswered(
364
+ ctx,
365
+ ctx.gtpv2,
366
+ "gtpv2.unanswered",
367
+ "The peer gateway is unreachable or dropping requests. Check the path (GTP-C on "
368
+ "UDP 2123) and the peer's health.",
369
+ )
370
+
371
+
372
+ @rule("nas.emm.reject")
373
+ def nas_rejects(ctx: Context) -> Iterator[Finding]:
374
+ groups: dict[object, _Group] = {}
375
+ for packet in ctx.packets:
376
+ if not packet.has("nas-eps"):
377
+ continue
378
+ mtype = to_int(packet.first("nas-eps.nas_msg_emm_type"))
379
+ if mtype in EMM_REJECTS:
380
+ cause = to_int(packet.first("nas-eps.emm.cause"))
381
+ if cause is None:
382
+ continue
383
+ code = lookup(EMM_CAUSE, cause)
384
+ name = EMM_MESSAGES[mtype]
385
+ key = (mtype, cause)
386
+ if key not in groups:
387
+ groups[key] = _Group(
388
+ verdict=f"{name}: {code.name}.",
389
+ why=f"The network sent {name} with EMM cause #{cause} ({code.name}).",
390
+ fix=code.hint,
391
+ severity=Severity.FAILURE,
392
+ )
393
+ _add(groups[key], [packet], ctx.imsi_of(packet))
394
+ elif mtype == 0x5C: # Authentication Failure, sent by the UE
395
+ cause = to_int(packet.first("nas-eps.emm.cause"))
396
+ if cause is None:
397
+ continue
398
+ code = lookup(AUTH_FAILURE_CAUSE, cause)
399
+ imsi = ctx.imsi_of(packet)
400
+ recovered = cause == 21 and _auth_recovered(ctx, packet, imsi)
401
+ key = ("auth", cause, recovered)
402
+ if key not in groups:
403
+ if recovered:
404
+ groups[key] = _Group(
405
+ verdict="Sequence-number resync, then authentication succeeded.",
406
+ why=f"The device sent Authentication Failure, cause #{cause} "
407
+ f"({code.name}), and the next Authentication Response succeeded.",
408
+ fix="No action. This is normal on a SIM's first attach to a network "
409
+ "and after the HSS loses SQN state.",
410
+ severity=Severity.INFO,
411
+ )
412
+ else:
413
+ groups[key] = _Group(
414
+ verdict=f"Device rejected network authentication: {code.name}.",
415
+ why=f"The device sent Authentication Failure, cause #{cause} "
416
+ f"({code.name}).",
417
+ fix=code.hint,
418
+ severity=Severity.WARNING if cause == 21 else Severity.FAILURE,
419
+ )
420
+ _add(groups[key], [packet], imsi)
421
+ yield from _emit("nas.emm.reject", groups)
422
+
423
+
424
+ @rule("nas.esm.reject")
425
+ def esm_rejects(ctx: Context) -> Iterator[Finding]:
426
+ groups: dict[object, _Group] = {}
427
+ for packet in ctx.packets:
428
+ if not packet.has("nas-eps"):
429
+ continue
430
+ if to_int(packet.first("nas-eps.nas_msg_esm_type")) != ESM_PDN_CONNECTIVITY_REJECT:
431
+ continue
432
+ cause = to_int(packet.first("nas-eps.esm.cause"))
433
+ if cause is None:
434
+ continue
435
+ code = lookup(ESM_CAUSE, cause)
436
+ imsi = ctx.imsi_of(packet)
437
+ after_attach = _attach_accepted_before(ctx, packet, imsi)
438
+ key = (cause, after_attach)
439
+ if key not in groups:
440
+ if after_attach:
441
+ groups[key] = _Group(
442
+ verdict=f"Extra PDN connection rejected: {code.name}.",
443
+ why=f"The device attached and got its default bearer, then asked for an "
444
+ f"additional PDN connection, which was rejected with ESM cause #{cause} "
445
+ f"({code.name}). Data on the default APN works.",
446
+ fix=code.hint
447
+ or "Check which extra APN the device requests and whether the subscription "
448
+ "includes it.",
449
+ severity=Severity.WARNING,
450
+ )
451
+ else:
452
+ groups[key] = _Group(
453
+ verdict=f"PDN connectivity rejected: {code.name}.",
454
+ why=f"The network sent PDN Connectivity Reject, ESM cause #{cause} "
455
+ f"({code.name}).",
456
+ fix=code.hint,
457
+ severity=Severity.FAILURE,
458
+ )
459
+ _add(groups[key], [packet], imsi)
460
+ yield from _emit("nas.esm.reject", groups)
461
+
462
+
463
+ AUTH_RESPONSE = 0x53
464
+ ATTACH_ACCEPT = 0x42
465
+
466
+ # A more specific finding replaces a generic one that cites only the same packets.
467
+ SUPERSEDES = {"gtpv2.pdn_type": "gtpv2.cause"}
468
+
469
+
470
+ def _drop_superseded(findings: list[Finding]) -> list[Finding]:
471
+ covered: dict[str, set[int]] = {}
472
+ for f in findings:
473
+ if f.rule_id in SUPERSEDES:
474
+ covered.setdefault(SUPERSEDES[f.rule_id], set()).update(f.evidence)
475
+ return [
476
+ f for f in findings if not (f.rule_id in covered and set(f.evidence) <= covered[f.rule_id])
477
+ ]
478
+
479
+
480
+ def _same_ue(ctx: Context, a: Packet, b: Packet, imsi: str | None) -> bool:
481
+ enb_id = a.first("s1ap.ENB_UE_S1AP_ID")
482
+ return (imsi is not None and ctx.imsi_of(b) == imsi) or (
483
+ enb_id is not None and b.first("s1ap.ENB_UE_S1AP_ID") == enb_id
484
+ )
485
+
486
+
487
+ def _attach_accepted_before(ctx: Context, packet: Packet, imsi: str | None) -> bool:
488
+ for other in ctx.packets:
489
+ if other.number >= packet.number:
490
+ return False
491
+ if (
492
+ other.has("nas-eps")
493
+ and to_int(other.first("nas-eps.nas_msg_emm_type")) == ATTACH_ACCEPT
494
+ and _same_ue(ctx, packet, other, imsi)
495
+ ):
496
+ return True
497
+ return False
498
+
499
+
500
+ def _auth_recovered(ctx: Context, failure: Packet, imsi: str | None) -> bool:
501
+ """True if the same UE sends a successful Authentication Response after `failure`."""
502
+ enb_id = failure.first("s1ap.ENB_UE_S1AP_ID")
503
+ for packet in ctx.packets:
504
+ if packet.number <= failure.number or not packet.has("nas-eps"):
505
+ continue
506
+ if to_int(packet.first("nas-eps.nas_msg_emm_type")) != AUTH_RESPONSE:
507
+ continue
508
+ same_ue = (imsi is not None and ctx.imsi_of(packet) == imsi) or (
509
+ enb_id is not None and packet.first("s1ap.ENB_UE_S1AP_ID") == enb_id
510
+ )
511
+ if same_ue:
512
+ return True
513
+ return False
514
+
515
+
516
+ def run_rules(ctx: Context) -> list[Finding]:
517
+ findings: list[Finding] = []
518
+ for _rule_id, fn in RULES:
519
+ findings.extend(fn(ctx))
520
+ findings = _drop_superseded(findings)
521
+ order = {Severity.FAILURE: 0, Severity.WARNING: 1, Severity.INFO: 2}
522
+ return sorted(findings, key=lambda f: (order[f.severity], f.evidence[0] if f.evidence else 0))