f5auditdns 0.3.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.
f5auditdns/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """F5AuditDNS: read-only BIG-IP DNS / GSLB configuration auditor."""
2
+ __version__ = "0.3.0"
f5auditdns/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
f5auditdns/analyzer.py ADDED
@@ -0,0 +1,343 @@
1
+ """Conservative, auditable correlation of BIG-IP DNS GSLB objects.
2
+
3
+ No finding in this module is an authorization to delete an object. The
4
+ algorithm distinguishes missing evidence from truly empty relationships.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from collections import defaultdict
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from .collector import Snapshot, RECORD_TYPES, object_id
14
+
15
+
16
+ @dataclass
17
+ class Audit:
18
+ summary: list[dict[str, Any]] = field(default_factory=list)
19
+ wideips: list[dict[str, Any]] = field(default_factory=list)
20
+ pools: list[dict[str, Any]] = field(default_factory=list)
21
+ members: list[dict[str, Any]] = field(default_factory=list)
22
+ servers: list[dict[str, Any]] = field(default_factory=list)
23
+ virtuals: list[dict[str, Any]] = field(default_factory=list)
24
+ datacenters: list[dict[str, Any]] = field(default_factory=list)
25
+ chains: list[dict[str, Any]] = field(default_factory=list)
26
+ manual_review: list[dict[str, Any]] = field(default_factory=list)
27
+ auxiliary: list[dict[str, Any]] = field(default_factory=list)
28
+ collection_health: list[dict[str, Any]] = field(default_factory=list)
29
+ candidates: list[dict[str, Any]] = field(default_factory=list)
30
+ ltm_inventory: list[dict[str, Any]] = field(default_factory=list)
31
+
32
+
33
+ def normalize_path(value: Any, partition: str = "Common") -> str:
34
+ """Resolve a simple relative BIG-IP name without conflating partitions."""
35
+ text = str(value or "").strip()
36
+ if not text:
37
+ return ""
38
+ return text if text.startswith("/") else f"/{partition}/{text}"
39
+
40
+
41
+ def ref_name(ref: Any) -> str:
42
+ if isinstance(ref, str):
43
+ return ref
44
+ if isinstance(ref, dict):
45
+ return str(ref.get("fullPath") or ref.get("name") or ref.get("pool") or "")
46
+ return ""
47
+
48
+
49
+ def names_of(value: Any) -> list[str]:
50
+ if isinstance(value, list):
51
+ return [x for x in (ref_name(item) for item in value) if x]
52
+ if isinstance(value, dict):
53
+ if isinstance(value.get("items"), list):
54
+ return names_of(value["items"])
55
+ return [ref_name(value)] if ref_name(value) else []
56
+ if isinstance(value, str) and value.strip():
57
+ return [value.strip()]
58
+ return []
59
+
60
+
61
+ def config_state(obj: dict[str, Any]) -> str:
62
+ """Configuration enable/disable is not the same as service health UP/DOWN."""
63
+ disabled = obj.get("disabled")
64
+ enabled = obj.get("enabled")
65
+ if disabled is True or str(disabled).lower() in ("true", "yes"):
66
+ return "DISABLED"
67
+ if enabled is False or str(enabled).lower() in ("false", "no"):
68
+ return "DISABLED"
69
+ return "ENABLED" if enabled is True or str(enabled).lower() in ("true", "yes") else "UNKNOWN"
70
+
71
+
72
+ def health_state(obj: dict[str, Any]) -> str:
73
+ """Read only actual health fields; never infer health from 'enabled'."""
74
+ status = obj.get("status")
75
+ if isinstance(status, dict):
76
+ for key in ("availabilityState", "status", "state"):
77
+ if status.get(key):
78
+ return str(status[key]).upper()
79
+ for key in ("availabilityState", "availability", "statusAvailability"):
80
+ if obj.get(key):
81
+ return str(obj[key]).upper()
82
+ return "UNKNOWN"
83
+
84
+
85
+ def add_manual(audit: Audit, kind: str, name: str, reason: str, severity: str = "REVIEW") -> None:
86
+ audit.manual_review.append({"Type": kind, "Object": name, "Priority": severity, "Reason": reason})
87
+
88
+
89
+ def _partition(obj: dict[str, Any]) -> str:
90
+ return str(obj.get("partition") or obj.get("tmPartition") or "Common")
91
+
92
+
93
+ def _member_raw_name(member: dict[str, Any]) -> str:
94
+ return str(member.get("fullPath") or member.get("name") or member.get("virtualServer") or "")
95
+
96
+
97
+ def resolve_member(raw: str, server_virtuals: dict[tuple[str, str], str]) -> tuple[str, str, str]:
98
+ """Match /Partition/Server:/Partition/VS only when the match is unique.
99
+
100
+ A pool member can have a nested path. Use exact /server:vs pairs where
101
+ available; do not guess on ambiguous names. Return (server, vs, status).
102
+ """
103
+ raw = str(raw).strip()
104
+ if not raw:
105
+ return ("", "", "UNKNOWN")
106
+ matches = []
107
+ for (server, vs), _ in server_virtuals.items():
108
+ canonical = server + ":" + vs
109
+ short_server = server.rsplit("/", 1)[-1]
110
+ short_vs = vs.rsplit("/", 1)[-1]
111
+ choices = {canonical, f"{server}:{short_vs}", f"{short_server}:{vs}",
112
+ f"{short_server}:{short_vs}"}
113
+ if raw in choices or raw.endswith(canonical):
114
+ matches.append((server, vs))
115
+ matches = list(set(matches))
116
+ if len(matches) == 1:
117
+ return (*matches[0], "MATCHED")
118
+ return ("", "", "AMBIGUOUS" if len(matches) > 1 else "UNRESOLVED")
119
+
120
+
121
+ def analyze(snap: Snapshot, ltm_snapshots=None, max_snapshot_gap_hours: float = 48,
122
+ ltm_scan=None, ltm_coverage_complete: bool = False) -> Audit:
123
+ a = Audit()
124
+ datasets, results = snap.datasets, snap.meta.get("endpoint_results", {})
125
+ core_keys = [f"gtm_{kind}_{rr}" for rr in RECORD_TYPES for kind in ("wideip", "pool")]
126
+ core_keys += ["gtm_datacenter", "gtm_server"]
127
+ missing_core = [k for k in core_keys if results.get(k) != "OK"]
128
+ any_dynamic = bool(datasets.get("gtm_rule")) or bool(datasets.get("gtm_distributed_app"))
129
+ dynamic_coverage_unknown = snap.meta.get("scope") != "all" or any(
130
+ results.get(k) != "OK" for k in ("gtm_rule", "gtm_distributed_app")
131
+ )
132
+
133
+ for key, state in sorted(results.items()):
134
+ a.collection_health.append({"Dataset": key, "Status": state,
135
+ "Endpoint": snap.meta.get("endpoint_paths", {}).get(key, "")})
136
+ if state != "OK":
137
+ add_manual(a, "COLLECTION", key, f"Dataset incomplete: {state}", "DATA GAP")
138
+
139
+ pools_by_key: dict[tuple[str, str], dict[str, Any]] = {}
140
+ wideip_pools: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
141
+ reverse_pool_refs: dict[tuple[str, str], set[str]] = defaultdict(set)
142
+ unresolved_pool_refs: list[tuple[str, str, str]] = []
143
+
144
+ # Index *all* pool types before resolving A/CNAME last-resort references.
145
+ for rr in RECORD_TYPES:
146
+ for obj in datasets.get(f"gtm_pool_{rr}", []):
147
+ pools_by_key[(rr, object_id(obj))] = obj
148
+ for rr in RECORD_TYPES:
149
+ for obj in datasets.get(f"gtm_wideip_{rr}", []):
150
+ wid = object_id(obj)
151
+ part = _partition(obj)
152
+ associations_key = f"wideip_pools::{rr}::{wid}"
153
+ pool_rows = datasets.get(associations_key)
154
+ if pool_rows is None:
155
+ # Some API versions use a direct 'pools' property in the parent.
156
+ inline = obj.get("pools")
157
+ pool_rows = inline if isinstance(inline, list) else None
158
+ refs: list[tuple[str, str]] = []
159
+ if pool_rows is not None:
160
+ for p in pool_rows:
161
+ name = ref_name(p)
162
+ if name:
163
+ refs.append((rr, normalize_path(name, str(p.get("partition") or part) if isinstance(p, dict) else part)))
164
+ extra = datasets.get(f"wideip_pools_cname::{rr}::{wid}", [])
165
+ for p in extra:
166
+ name = ref_name(p)
167
+ if name:
168
+ refs.append(("cname", normalize_path(name, str(p.get("partition") or part) if isinstance(p, dict) else part)))
169
+ elif obj.get("poolsCname"):
170
+ for n in names_of(obj["poolsCname"]):
171
+ refs.append(("cname", normalize_path(n, part)))
172
+ last_resort = str(obj.get("lastResortPool") or "").strip()
173
+ if last_resort and last_resort.lower() not in ("none", "none "):
174
+ target = normalize_path(last_resort, part)
175
+ # Last resort may be an A or CNAME pool; only resolve when unique.
176
+ options = [(ty, target) for ty in (rr, "cname") if (ty, target) in pools_by_key]
177
+ options = list(dict.fromkeys(options))
178
+ if len(options) == 1:
179
+ refs.append(options[0])
180
+ else:
181
+ unresolved_pool_refs.append((rr, wid, f"Last resort pool {target}: not uniquely resolved"))
182
+ refs = list(dict.fromkeys(refs))
183
+ wideip_pools[(rr, wid)] = refs
184
+ for key in refs:
185
+ reverse_pool_refs[key].add(f"{rr.upper()} {wid}")
186
+ a.wideips.append({
187
+ "Type": rr.upper(), "Wide IP": wid, "Config": config_state(obj),
188
+ "Health": health_state(obj), "Pools": ", ".join(f"{t.upper()}:{n}" for t, n in refs),
189
+ "Pool count": len(refs), "Last resort": last_resort,
190
+ "Rules": ", ".join(names_of(obj.get("rules"))),
191
+ "Finding": "REVIEW: pool links unavailable" if pool_rows is None else
192
+ "REVIEW: no pool reference" if not refs else "REFERENCED",
193
+ })
194
+ if pool_rows is None:
195
+ add_manual(a, "WIDE IP", wid, "Pool association is missing/unknown (not assumed empty)", "DATA GAP")
196
+ elif not refs:
197
+ add_manual(a, "WIDE IP", wid, "No GSLB Pool reference found; validate intended behavior")
198
+ if config_state(obj) == "DISABLED":
199
+ add_manual(a, "WIDE IP", wid, "Wide IP is disabled; not automatically unused")
200
+ if obj.get("rules"):
201
+ add_manual(a, "WIDE IP", wid, "iRules may select GSLB pools dynamically")
202
+ for typ, target in refs:
203
+ if (typ, target) not in pools_by_key:
204
+ unresolved_pool_refs.append((rr, wid, f"Referenced Pool {typ.upper()}:{target} not in collected inventory"))
205
+
206
+ for rr, wid, reason in unresolved_pool_refs:
207
+ add_manual(a, "WIDE IP", wid, reason, "DATA GAP")
208
+
209
+ servers: dict[str, dict[str, Any]] = {object_id(s): s for s in datasets.get("gtm_server", [])}
210
+ datacenters: dict[str, dict[str, Any]] = {object_id(d): d for d in datasets.get("gtm_datacenter", [])}
211
+ server_virtuals: dict[tuple[str, str], str] = {}
212
+ virtuals_per_server: dict[str, int | None] = {}
213
+ for server, obj in servers.items():
214
+ vlist = datasets.get(f"server_virtuals::{server}")
215
+ virtuals_per_server[server] = len(vlist) if isinstance(vlist, list) else None
216
+ if vlist is None:
217
+ add_manual(a, "SERVER", server, "Virtual Server subcollection unknown", "DATA GAP")
218
+ continue
219
+ for v in vlist:
220
+ vname = object_id(v)
221
+ server_virtuals[(server, vname)] = str(v.get("destination") or v.get("address") or "")
222
+ a.virtuals.append({"Server": server, "Virtual Server": vname,
223
+ "Destination": str(v.get("destination") or v.get("address") or ""),
224
+ "Port": v.get("port", ""), "Config": config_state(v),
225
+ "Health": health_state(v)})
226
+
227
+ pool_member_counts: dict[tuple[str, str], int | None] = {}
228
+ referenced_servers: set[str] = set()
229
+ member_unresolved = False
230
+ for (rr, path), p in sorted(pools_by_key.items()):
231
+ mkey = f"pool_members::{rr}::{path}"
232
+ members = datasets.get(mkey)
233
+ pool_member_counts[(rr, path)] = len(members) if isinstance(members, list) else None
234
+ for member in members or []:
235
+ raw = _member_raw_name(member)
236
+ server, virtual, resolution = resolve_member(raw, server_virtuals)
237
+ if resolution != "MATCHED":
238
+ member_unresolved = True
239
+ add_manual(a, "POOL MEMBER", raw or path, f"Server/Virtual mapping: {resolution}", "DATA GAP")
240
+ else:
241
+ referenced_servers.add(server)
242
+ a.members.append({"Type": rr.upper(), "Pool": path, "Member": raw,
243
+ "GSLB Server": server, "Virtual Server": virtual,
244
+ "Destination": server_virtuals.get((server, virtual), ""),
245
+ "Mapping": resolution, "Config": config_state(member),
246
+ "Health": health_state(member)})
247
+ refs = sorted(reverse_pool_refs[(rr, path)])
248
+ if members is None:
249
+ finding = "MANUAL REVIEW: members unknown"
250
+ elif not members:
251
+ finding = "MANUAL REVIEW: no members"
252
+ elif not refs:
253
+ finding = "MANUAL REVIEW: no direct Wide IP reference"
254
+ else:
255
+ finding = "REFERENCED"
256
+ if not refs:
257
+ add_manual(a, "POOL", path, "No direct Wide IP/last-resort reference. iRules and other dependencies may exist.")
258
+ if members is None:
259
+ add_manual(a, "POOL", path, "Pool Member subcollection unavailable", "DATA GAP")
260
+ elif not members:
261
+ add_manual(a, "POOL", path, "Pool has zero members; check fallback/maintenance design")
262
+ a.pools.append({"Type": rr.upper(), "Pool": path, "Config": config_state(p),
263
+ "Health": health_state(p), "Member count": pool_member_counts[(rr, path)],
264
+ "Referenced by": ", ".join(refs), "Monitor": str(p.get("monitor") or ""),
265
+ "Method": str(p.get("loadBalancingMode") or ""), "Finding": finding})
266
+
267
+ server_to_dc: dict[str, list[str]] = defaultdict(list)
268
+ for sid, s in sorted(servers.items()):
269
+ dc = normalize_path(s.get("datacenter"), _partition(s))
270
+ if dc:
271
+ server_to_dc[dc].append(sid)
272
+ count = virtuals_per_server[sid]
273
+ finding = "REFERENCED" if sid in referenced_servers else "MANUAL REVIEW: no mapped member"
274
+ a.servers.append({"Server": sid, "Data Center": dc, "Product": s.get("product", ""),
275
+ "Virtual Server count": count, "Config": config_state(s),
276
+ "Health": health_state(s), "Referenced by member": sid in referenced_servers,
277
+ "Finding": finding})
278
+ if count == 0:
279
+ add_manual(a, "SERVER", sid, "No GSLB Virtual Servers; validate discovery and intended role")
280
+ if dc and dc not in datacenters:
281
+ add_manual(a, "SERVER", sid, f"Data Center {dc} unavailable in inventory", "DATA GAP")
282
+ if sid not in referenced_servers and not member_unresolved:
283
+ add_manual(a, "SERVER", sid, "No mapped GSLB Pool Member; could be backup/prober/discovery")
284
+ for dcid, dc in sorted(datacenters.items()):
285
+ associated = server_to_dc.get(dcid, [])
286
+ a.datacenters.append({"Data Center": dcid, "Server count": len(associated),
287
+ "Servers": ", ".join(associated), "Config": config_state(dc),
288
+ "Health": health_state(dc),
289
+ "Finding": "MANUAL REVIEW: no servers" if not associated else "REFERENCED"})
290
+ if not associated:
291
+ add_manual(a, "DATA CENTER", dcid, "No GSLB Server references; may still have topology/prober role")
292
+
293
+ member_by_pool = defaultdict(list)
294
+ for member in a.members:
295
+ member_by_pool[(member["Type"].lower(), member["Pool"])].append(member)
296
+ for w in a.wideips:
297
+ pairs = wideip_pools.get((w["Type"].lower(), w["Wide IP"]), [])
298
+ if not pairs:
299
+ a.chains.append({"Type": w["Type"], "Wide IP": w["Wide IP"], "Pool": "",
300
+ "Member": "", "Server": "", "Virtual Server": "", "Destination": "", "Note": "NO RESOLVED POOLS"})
301
+ for ptype, pname in pairs:
302
+ linked = member_by_pool.get((ptype, pname), [])
303
+ if not linked:
304
+ a.chains.append({"Type": w["Type"], "Wide IP": w["Wide IP"],
305
+ "Pool": pname, "Member": "", "Server": "", "Virtual Server": "",
306
+ "Destination": "", "Note": "NO MEMBERS OR UNAVAILABLE DATA"})
307
+ for m in linked:
308
+ a.chains.append({"Type": w["Type"], "Wide IP": w["Wide IP"],
309
+ "Pool": pname, "Member": m["Member"],
310
+ "Server": m["GSLB Server"], "Virtual Server": m["Virtual Server"],
311
+ "Destination": m["Destination"], "Note": m["Mapping"]})
312
+
313
+ for key, values in sorted(datasets.items()):
314
+ if key.startswith(("gtm_monitor_", "gtm_listener", "gtm_rule", "gtm_topology",
315
+ "gtm_region", "gtm_prober_pool", "gtm_distributed_app")):
316
+ for item in values if isinstance(values, list) else []:
317
+ a.auxiliary.append({"Dataset": key, "Object": object_id(item),
318
+ "Config": config_state(item), "Description": str(item.get("description") or "")})
319
+ a.summary = [
320
+ {"Metric": "Host", "Value": snap.meta.get("host", "")},
321
+ {"Metric": "Collection timestamp UTC", "Value": snap.meta.get("collected_at", "")},
322
+ {"Metric": "Scope", "Value": snap.meta.get("scope", "")},
323
+ {"Metric": "Wide IPs", "Value": len(a.wideips)},
324
+ {"Metric": "GSLB Pools", "Value": len(a.pools)},
325
+ {"Metric": "GSLB Pool Members", "Value": len(a.members)},
326
+ {"Metric": "GSLB Servers", "Value": len(a.servers)},
327
+ {"Metric": "GSLB Virtual Servers", "Value": len(a.virtuals)},
328
+ {"Metric": "Data Centers", "Value": len(a.datacenters)},
329
+ {"Metric": "Manual review entries", "Value": len(a.manual_review)},
330
+ {"Metric": "Failed or unknown datasets", "Value": sum(v != "OK" for v in results.values())},
331
+ {"Metric": "Complete core catalog", "Value": "YES" if not missing_core else "NO"},
332
+ {"Metric": "Can independently establish lack of use", "Value": "NO - requires historical and operational validation"},
333
+ {"Metric": "Deletion actions", "Value": "NEVER GENERATED"},
334
+ ]
335
+ if missing_core:
336
+ add_manual(a, "GLOBAL", "COLLECTION", "Core inventory incomplete; no unused classification is safe", "DATA GAP")
337
+ if any_dynamic or dynamic_coverage_unknown:
338
+ add_manual(a, "GLOBAL", "DYNAMIC REFERENCES",
339
+ "iRules/distributed apps present or not collected; direct object references may be incomplete")
340
+ from .cleanup import enrich_cleanup
341
+ enrich_cleanup(a, snap, ltm_snapshots, max_snapshot_gap_hours,
342
+ ltm_scan=ltm_scan, ltm_coverage_complete=ltm_coverage_complete)
343
+ return a