-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrir_client.py
More file actions
1786 lines (1554 loc) · 80.3 KB
/
Copy pathrir_client.py
File metadata and controls
1786 lines (1554 loc) · 80.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
rir_client.py — PeerGlass async HTTP clients for all external APIs.
Phase 1: RDAP queries to all 5 RIRs (parallel engine)
Phase 2: RPKI/ROA validation (Cloudflare), BGP status (RIPE Stat),
Organization search (RDAP search endpoints)
Protocol note: all live registry queries use RDAP (RFC 7480-7484),
the IANA-mandated JSON successor to legacy WHOIS. The string
"historical-whois" below refers to the RIPE Stat upstream API
endpoint name — it is not our protocol choice.
The parallel engine is the core of this server:
asyncio.gather() fires all 5 RIR queries simultaneously.
Like asking 5 librarians the same question at once instead of
waiting for each one to finish before approaching the next.
"""
from __future__ import annotations
import asyncio
import ipaddress
import time
from typing import Any, Optional
import httpx
from models import RIRName, RIRQueryResult, RPKIResult, RPKIValidity, BGPStatusResult, BGPPrefix, OrgResource, \
HistoricalEvent, PrefixHistoryResult, TransferEvent, TransferDetectResult, \
RIRDelegationStats, GlobalIPv4Stats, IPv4DelegatedBlock, RelatedPrefix, PrefixOverviewResult, \
IXPRecord, PeeringInfoResult, IXPLookupResult, NetworkHealthResult, \
ChangeMonitorResult, FieldDelta
# ──────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────
RDAP_ENDPOINTS: dict[RIRName, str] = {
RIRName.AFRINIC: "https://rdap.afrinic.net/rdap",
RIRName.APNIC: "https://rdap.apnic.net",
RIRName.ARIN: "https://rdap.arin.net/registry",
RIRName.LACNIC: "https://rdap.lacnic.net/rdap",
RIRName.RIPE: "https://rdap.db.ripe.net",
}
# RDAP search endpoints (not all RIRs support entity search)
RDAP_SEARCH_ENDPOINTS: dict[RIRName, Optional[str]] = {
RIRName.AFRINIC: "https://rdap.afrinic.net/rdap",
RIRName.APNIC: "https://rdap.apnic.net",
RIRName.ARIN: "https://rdap.arin.net/registry",
RIRName.LACNIC: None, # LACNIC does not support RDAP entity search
RIRName.RIPE: "https://rdap.db.ripe.net",
}
# IANA Bootstrap — tells us which RIR is authoritative for each IP/ASN range
IANA_BOOTSTRAP_IPv4 = "https://data.iana.org/rdap/ipv4.json"
IANA_BOOTSTRAP_IPv6 = "https://data.iana.org/rdap/ipv6.json"
IANA_BOOTSTRAP_ASN = "https://data.iana.org/rdap/asn.json"
# Phase 2 — external API endpoints
CLOUDFLARE_RPKI_URL = "https://rpki.cloudflare.com/api/v1/validity"
RIPE_STAT_RPKI_URL = "https://stat.ripe.net/data/rpki-validation/data.json"
RIPE_STAT_BGP_URL = "https://stat.ripe.net/data/bgp-state/data.json"
RIPE_STAT_PREFIXES_URL = "https://stat.ripe.net/data/announced-prefixes/data.json"
RIPE_STAT_ROUTING_URL = "https://stat.ripe.net/data/routing-status/data.json"
# Phase 3 — historical intelligence endpoints
RIPE_STAT_HIST_WHOIS_URL = "https://stat.ripe.net/data/historical-whois/data.json"
RIPE_STAT_ALLOC_HIST_URL = "https://stat.ripe.net/data/allocation-history/data.json"
RIPE_STAT_PREFIX_OVERVIEW = "https://stat.ripe.net/data/prefix-overview/data.json"
RIPE_STAT_LESS_SPECIFICS = "https://stat.ripe.net/data/less-specifics/data.json"
RIPE_STAT_MORE_SPECIFICS = "https://stat.ripe.net/data/more-specifics/data.json"
# NRO Extended Delegation Stats — published daily by each RIR
# Format: rir|CC|type|start|value|date|status[|opaque-id[|extensions]]
NRO_DELEGATION_STATS: dict[str, str] = {
"AFRINIC": "https://ftp.afrinic.net/stats/afrinic/delegated-afrinic-extended-latest",
"APNIC": "https://ftp.apnic.net/stats/apnic/delegated-apnic-extended-latest",
"ARIN": "https://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest",
"LACNIC": "https://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-extended-latest",
"RIPE": "https://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest",
}
RIR_REGIONS: dict[str, str] = {
"AFRINIC": "Africa",
"APNIC": "Asia-Pacific",
"ARIN": "North America",
"LACNIC": "Latin America & Caribbean",
"RIPE": "Europe / Middle East / Central Asia",
}
# Phase 4 — PeeringDB + RIPE Stat neighbours
PEERINGDB_NET_URL = "https://www.peeringdb.com/api/net"
PEERINGDB_IXP_URL = "https://www.peeringdb.com/api/ix"
PEERINGDB_NETIXLAN_URL = "https://www.peeringdb.com/api/netixlan"
RIPE_STAT_NEIGHBOURS_URL = "https://stat.ripe.net/data/asn-neighbours/data.json"
DEFAULT_TIMEOUT = 15.0
DEFAULT_HEADERS = {
"Accept": "application/rdap+json, application/json",
"User-Agent": "peerglass/1.0.0 (PeerGlass RDAP+BGP+RPKI client; educational/research use)",
}
# Bootstrap data is semi-static — cache in-process for the server lifetime
_BOOTSTRAP_CACHE: dict[str, Any] = {}
# ──────────────────────────────────────────────────────────────
# Bootstrap / routing helpers
# ──────────────────────────────────────────────────────────────
async def _load_bootstrap(url: str, client: httpx.AsyncClient) -> dict:
if url in _BOOTSTRAP_CACHE:
return _BOOTSTRAP_CACHE[url]
try:
resp = await client.get(url, timeout=10.0, headers=DEFAULT_HEADERS)
resp.raise_for_status()
data = resp.json()
_BOOTSTRAP_CACHE[url] = data
return data
except Exception:
return {}
def _ip4_to_int(ip: str) -> int:
parts = ip.split(".")
result = 0
for part in parts:
result = (result << 8) + int(part)
return result
def _cidr_contains_ip4(cidr: str, ip_int: int) -> bool:
try:
network, bits = cidr.split("/")
net_int = _ip4_to_int(network)
mask = (0xFFFFFFFF << (32 - int(bits))) & 0xFFFFFFFF
return (ip_int & mask) == (net_int & mask)
except Exception:
return False
async def _find_authoritative_base_url(
query: str,
query_type: str, # "ip" | "asn"
client: httpx.AsyncClient,
) -> Optional[str]:
"""
Use IANA RDAP Bootstrap to find which RIR is authoritative for a given
IP address or ASN. Returns the RDAP base URL of that RIR, or None.
"""
if query_type == "ip":
is_v6 = ":" in query
url = IANA_BOOTSTRAP_IPv6 if is_v6 else IANA_BOOTSTRAP_IPv4
bootstrap = await _load_bootstrap(url, client)
if not is_v6:
try:
ip_int = _ip4_to_int(query.split("/")[0])
for service in bootstrap.get("services", []):
cidrs, urls = service[0], service[1]
for cidr in cidrs:
if _cidr_contains_ip4(cidr, ip_int):
return urls[0] if urls else None
except Exception:
pass
elif query_type == "asn":
bootstrap = await _load_bootstrap(IANA_BOOTSTRAP_ASN, client)
try:
asn_num = int(query.upper().lstrip("AS"))
for service in bootstrap.get("services", []):
ranges, urls = service[0], service[1]
for r in ranges:
parts = r.split("-")
lo = int(parts[0])
hi = int(parts[1]) if len(parts) == 2 else lo
if lo <= asn_num <= hi:
return urls[0] if urls else None
except Exception:
pass
return None
# ──────────────────────────────────────────────────────────────
# Core single-RIR query
# ──────────────────────────────────────────────────────────────
async def _query_one_rir(
client: httpx.AsyncClient,
rir: RIRName,
base_url: str,
path: str,
) -> RIRQueryResult:
"""Query one RIR's RDAP endpoint and return a structured result."""
url = f"{base_url}/{path}"
queried_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
try:
resp = await client.get(url, timeout=DEFAULT_TIMEOUT, headers=DEFAULT_HEADERS, follow_redirects=True)
if resp.status_code == 200:
return RIRQueryResult(rir=rir, status="ok", queried_at=queried_at, data=resp.json())
if resp.status_code == 404:
return RIRQueryResult(rir=rir, status="not_found", queried_at=queried_at,
error=f"Resource not found in {rir.value} registry")
if resp.status_code == 429:
return RIRQueryResult(rir=rir, status="rate_limited", queried_at=queried_at,
error=f"Rate limited by {rir.value}. Try again in a few minutes.")
return RIRQueryResult(rir=rir, status="error", queried_at=queried_at,
error=f"HTTP {resp.status_code} from {rir.value}")
except httpx.TimeoutException:
return RIRQueryResult(rir=rir, status="error", queried_at=queried_at,
error=f"{rir.value} timed out after {DEFAULT_TIMEOUT}s")
except httpx.ConnectError:
return RIRQueryResult(rir=rir, status="error", queried_at=queried_at,
error=f"Cannot connect to {rir.value} RDAP server")
except Exception as exc:
return RIRQueryResult(rir=rir, status="error", queried_at=queried_at,
error=f"{rir.value}: {type(exc).__name__}: {exc}")
# ──────────────────────────────────────────────────────────────
# Phase 1 — Parallel multi-RIR queries
# ──────────────────────────────────────────────────────────────
async def query_ip_all_rirs(ip: str) -> list[RIRQueryResult]:
"""Fire RDAP /ip/{ip} at all 5 RIRs simultaneously."""
async with httpx.AsyncClient() as client:
tasks = [
_query_one_rir(client, rir, endpoint, f"ip/{ip}")
for rir, endpoint in RDAP_ENDPOINTS.items()
]
return list(await asyncio.gather(*tasks))
async def query_asn_all_rirs(asn: str) -> list[RIRQueryResult]:
"""Fire RDAP /autnum/{asn} at all 5 RIRs simultaneously."""
asn_num = asn.upper().lstrip("AS")
async with httpx.AsyncClient() as client:
tasks = [
_query_one_rir(client, rir, endpoint, f"autnum/{asn_num}")
for rir, endpoint in RDAP_ENDPOINTS.items()
]
return list(await asyncio.gather(*tasks))
async def query_authoritative_rir(query: str, query_type: str) -> Optional[RIRQueryResult]:
"""
Find and query ONLY the authoritative RIR using IANA bootstrap.
More efficient than querying all 5 — used for abuse contact lookups.
Falls back to querying all 5 if bootstrap fails.
"""
async with httpx.AsyncClient() as client:
base_url = await _find_authoritative_base_url(query, query_type, client)
if base_url:
matched_rir: Optional[RIRName] = None
for rir, endpoint in RDAP_ENDPOINTS.items():
if base_url.rstrip("/").startswith(endpoint.rstrip("/")):
matched_rir = rir
break
if matched_rir:
path = f"{query_type}/{query}"
return await _query_one_rir(client, matched_rir, base_url, path)
# Fallback: query all, return first successful
path = f"{query_type}/{query.upper().lstrip('AS') if query_type == 'asn' else query}"
all_results = await query_ip_all_rirs(query) if query_type == "ip" else await query_asn_all_rirs(query)
for result in all_results:
if result.status == "ok":
return result
return None
async def get_rir_server_status() -> dict[RIRName, dict]:
"""Fetch /help from all 5 RIR RDAP endpoints simultaneously."""
async with httpx.AsyncClient() as client:
tasks = [
_query_one_rir(client, rir, endpoint, "help")
for rir, endpoint in RDAP_ENDPOINTS.items()
]
results = list(await asyncio.gather(*tasks))
return {
r.rir: r.data if r.status == "ok" else {"error": r.error}
for r in results
}
# ──────────────────────────────────────────────────────────────
# Phase 2 — RPKI / ROA Validation
# ──────────────────────────────────────────────────────────────
async def check_rpki(prefix: str, asn: str) -> RPKIResult:
"""
Validate a prefix+ASN pair against RPKI.
Primary source: RIPE Stat rpki-validation endpoint.
Fallback source: Cloudflare RPKI validator (legacy endpoint).
RPKI (Resource Public Key Infrastructure) is a cryptographic system
where each RIR issues Route Origin Authorizations (ROAs) — digital
certificates that say "ASN X is authorized to announce prefix Y".
This check answers: "Is this BGP route cryptographically valid?"
A VALID result means the route has a matching ROA.
An INVALID result means there IS a ROA, but this ASN/prefix doesn't match it.
NOT-FOUND means no ROA exists — the route is unverified (not necessarily bad).
"""
# Parse prefix into network and length
try:
network, length = prefix.split("/")
except ValueError:
return RPKIResult(
prefix=prefix, asn=asn,
validity=RPKIValidity.UNKNOWN,
description="Invalid prefix format. Use CIDR notation e.g. '1.1.1.0/24'",
)
asn_num = asn.upper().lstrip("AS")
validity_map = {
"valid": RPKIValidity.VALID,
"invalid": RPKIValidity.INVALID,
"not-found": RPKIValidity.NOT_FOUND,
"not_found": RPKIValidity.NOT_FOUND,
"notfound": RPKIValidity.NOT_FOUND,
"unknown": RPKIValidity.UNKNOWN,
}
descriptions = {
RPKIValidity.VALID:
"✅ This route has a valid ROA. The ASN is authorized to announce this prefix.",
RPKIValidity.INVALID:
"🚨 RPKI INVALID. A ROA exists but this ASN/prefix combination violates it. "
"This may indicate a BGP route leak or hijack.",
RPKIValidity.NOT_FOUND:
"⚠️ No ROA found for this prefix. The route is unverified but not necessarily malicious. "
"Consider creating a ROA at your RIR.",
RPKIValidity.UNKNOWN:
"❓ RPKI validity could not be determined.",
}
errors: list[str] = []
try:
async with httpx.AsyncClient() as client:
# 1) Primary: RIPE Stat RPKI validation
ripe_resp = await client.get(
RIPE_STAT_RPKI_URL,
params={"resource": f"AS{asn_num}", "prefix": prefix, "sourceapp": "peerglass"},
timeout=10.0,
headers=DEFAULT_HEADERS,
)
if ripe_resp.status_code == 200:
ripe_payload = ripe_resp.json()
if ripe_payload.get("status") == "ok":
ripe_data = ripe_payload.get("data", {})
state = str(ripe_data.get("status", "unknown")).lower()
validity = validity_map.get(state, RPKIValidity.UNKNOWN)
covering_roas = [
{
"asn": str(roa.get("origin", "")).lstrip("AS"),
"prefix": roa.get("prefix"),
"maxLength": roa.get("max_length"),
}
for roa in ripe_data.get("validating_roas", [])
if isinstance(roa, dict)
]
return RPKIResult(
prefix=prefix,
asn=f"AS{asn_num}",
validity=validity,
covering_roas=covering_roas,
source="RIPE Stat RPKI Validation",
description=descriptions.get(validity, ""),
)
errors.append("RIPE Stat RPKI API returned non-ok payload")
else:
errors.append(f"RIPE Stat RPKI API returned HTTP {ripe_resp.status_code}")
# 2) Fallback: Cloudflare endpoint (legacy)
cf_url = f"{CLOUDFLARE_RPKI_URL}/{asn_num}/{network}/{length}"
cf_resp = await client.get(cf_url, timeout=10.0, headers=DEFAULT_HEADERS)
if cf_resp.status_code == 200:
cf_payload = cf_resp.json()
validity_raw = cf_payload.get("result", {}).get("validity", cf_payload.get("validity", {}))
state = str(validity_raw.get("state", cf_payload.get("status", "unknown"))).lower()
validity = validity_map.get(state, RPKIValidity.UNKNOWN)
vrps = validity_raw.get("VRPs", {}) if isinstance(validity_raw, dict) else {}
covering_roas = vrps.get("matched", [])
unmatched_roas = vrps.get("unmatched_as", []) + vrps.get("unmatched_length", [])
return RPKIResult(
prefix=prefix,
asn=f"AS{asn_num}",
validity=validity,
covering_roas=covering_roas + unmatched_roas,
source="Cloudflare RPKI Validator",
description=descriptions.get(validity, ""),
)
errors.append(f"Cloudflare RPKI API returned HTTP {cf_resp.status_code}")
except httpx.TimeoutException:
errors.append("RPKI validators timed out")
except Exception as exc:
errors.append(f"Error querying RPKI: {type(exc).__name__}: {exc}")
return RPKIResult(
prefix=prefix,
asn=f"AS{asn_num}",
validity=RPKIValidity.UNKNOWN,
source="RIPE Stat + Cloudflare fallback",
description="; ".join(errors) if errors else "RPKI validity could not be determined.",
)
# ──────────────────────────────────────────────────────────────
# Phase 2 — BGP Routing Table Status (RIPE Stat)
# ──────────────────────────────────────────────────────────────
async def get_bgp_status(resource: str) -> BGPStatusResult:
"""
Check whether a prefix or ASN is currently visible in the global
BGP routing table using RIPE Stat (which aggregates data from
RIPE RIS route collectors worldwide).
BGP (Border Gateway Protocol) is the routing protocol of the internet.
Think of it as the internet's GPS — it tells traffic how to get from
one network to another. If a prefix isn't in BGP, no traffic reaches it.
If it IS in BGP with the wrong ASN, that could be a hijack.
"""
queried_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
is_asn = resource.upper().startswith("AS") or resource.isdigit()
resource_type = "asn" if is_asn else "prefix"
url = RIPE_STAT_ROUTING_URL if not is_asn else RIPE_STAT_PREFIXES_URL
params = {"resource": resource, "sourceapp": "peerglass"}
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url, params=params, timeout=15.0, headers=DEFAULT_HEADERS)
if resp.status_code != 200:
return BGPStatusResult(
resource=resource, resource_type=resource_type,
is_announced=False, queried_at=queried_at,
announced_prefixes=[],
)
data = resp.json().get("data", {})
if is_asn:
# RIPE Stat announced-prefixes endpoint
prefixes_raw = data.get("prefixes", [])
prefixes = [
BGPPrefix(
prefix = p.get("prefix", ""),
peers_seeing = p.get("timelines", [{}])[-1].get("endtime") and len(p.get("timelines", [])),
first_seen = p.get("timelines", [{}])[0].get("starttime") if p.get("timelines") else None,
last_seen = p.get("timelines", [{}])[-1].get("endtime") if p.get("timelines") else None,
)
for p in prefixes_raw
]
return BGPStatusResult(
resource = resource,
resource_type = resource_type,
is_announced = len(prefixes) > 0,
announced_prefixes = prefixes,
queried_at = queried_at,
)
else:
# RIPE Stat routing-status endpoint (prefix)
visibility = data.get("visibility", {})
if isinstance(visibility, dict) and (
"full_table_peer_count" in visibility or "seeing_prefix_peer_count" in visibility
):
# Older schema
full_table_peers = visibility.get("full_table_peer_count", 0)
seeing_peers = visibility.get("seeing_prefix_peer_count", 0)
else:
# Newer schema groups visibility by address family (v4/v6)
vis_v4 = visibility.get("v4", {}) if isinstance(visibility, dict) else {}
vis_v6 = visibility.get("v6", {}) if isinstance(visibility, dict) else {}
seeing_peers = max(
int(vis_v4.get("ris_peers_seeing", 0) or 0),
int(vis_v6.get("ris_peers_seeing", 0) or 0),
)
full_table_peers = max(
int(vis_v4.get("total_ris_peers", 0) or 0),
int(vis_v6.get("total_ris_peers", 0) or 0),
)
vis_pct = round((seeing_peers / full_table_peers) * 100, 1) if full_table_peers else None
origin_asns: list[str] = []
origins_raw = data.get("origins") or data.get("by_origin") or []
for origin_entry in origins_raw:
if isinstance(origin_entry, dict):
origin_value = origin_entry.get("origin")
else:
origin_value = origin_entry
if origin_value in (None, ""):
continue
origin = str(origin_value)
origin = origin if origin.upper().startswith("AS") else f"AS{origin}"
if origin not in origin_asns:
origin_asns.append(origin)
# Fallback: bgp-state now returns 'bgp_state' instead of 'routes'
announced_from_bgp_state = False
if seeing_peers == 0 and not origin_asns:
bgp_resp = await client.get(RIPE_STAT_BGP_URL, params=params, timeout=15.0, headers=DEFAULT_HEADERS)
if bgp_resp.status_code == 200:
bgp_data = bgp_resp.json().get("data", {})
entries = bgp_data.get("bgp_state") or bgp_data.get("routes") or []
for entry in entries:
if not isinstance(entry, dict):
continue
path = entry.get("path")
origin_value = path[-1] if isinstance(path, list) and path else entry.get("origin")
if origin_value in (None, ""):
continue
origin = str(origin_value)
origin = origin if origin.upper().startswith("AS") else f"AS{origin}"
if origin not in origin_asns:
origin_asns.append(origin)
announced_from_bgp_state = len(entries) > 0
return BGPStatusResult(
resource = resource,
resource_type = resource_type,
is_announced = (seeing_peers > 0) or bool(origin_asns) or announced_from_bgp_state,
announcing_asns = origin_asns,
visibility_percent = vis_pct,
queried_at = queried_at,
)
except httpx.TimeoutException:
return BGPStatusResult(
resource=resource, resource_type=resource_type,
is_announced=False, queried_at=queried_at,
)
except Exception as exc:
return BGPStatusResult(
resource=resource, resource_type=resource_type,
is_announced=False, queried_at=queried_at,
)
async def get_announced_prefixes(asn: str, min_peers: int = 5) -> BGPStatusResult:
"""
Fetch all IP prefixes currently being announced by an ASN in BGP.
Uses RIPE Stat's announced-prefixes endpoint.
"""
normalized_asn = f"AS{asn.upper().lstrip('AS')}"
queried_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
params = {"resource": normalized_asn, "min_peers_seeing": min_peers, "sourceapp": "peerglass"}
try:
async with httpx.AsyncClient() as client:
resp = await client.get(
RIPE_STAT_PREFIXES_URL, params=params, timeout=20.0, headers=DEFAULT_HEADERS
)
if resp.status_code != 200:
return BGPStatusResult(
resource=normalized_asn, resource_type="asn",
is_announced=False, queried_at=queried_at,
)
data = resp.json().get("data", {})
prefixes_raw = data.get("prefixes", [])
prefixes = [
BGPPrefix(
prefix = p.get("prefix", ""),
peers_seeing = len(p.get("timelines", [])),
first_seen = p.get("timelines", [{}])[0].get("starttime") if p.get("timelines") else None,
last_seen = p.get("timelines", [{}])[-1].get("endtime") if p.get("timelines") else None,
)
for p in prefixes_raw
]
return BGPStatusResult(
resource = normalized_asn,
resource_type = "asn",
is_announced = len(prefixes) > 0,
announced_prefixes = prefixes,
queried_at = queried_at,
)
except Exception:
return BGPStatusResult(
resource=normalized_asn, resource_type="asn",
is_announced=False, queried_at=queried_at,
)
# ──────────────────────────────────────────────────────────────
# Phase 2 — Organization Resource Audit
# ──────────────────────────────────────────────────────────────
async def _search_org_in_rir(
client: httpx.AsyncClient,
rir: RIRName,
base_url: str,
org_name: str,
) -> tuple[RIRName, list[OrgResource], Optional[str]]:
"""Search for an organization's resources in a single RIR."""
resources: list[OrgResource] = []
try:
# RDAP entity search by name
search_url = f"{base_url}/entities?fn={org_name}&role=registrant"
resp = await client.get(search_url, timeout=15.0, headers=DEFAULT_HEADERS, follow_redirects=True)
if resp.status_code in (200, 206):
data = resp.json()
for entity in data.get("entitySearchResults", []):
handle = entity.get("handle", "")
vcard = entity.get("vcardArray", [None, []])[1]
fn = None
for entry in vcard:
if isinstance(entry, list) and entry[0] == "fn":
fn = entry[3]
break
# For each entity, try to get their IP and ASN resources
for link in entity.get("links", []):
if link.get("rel") == "self" and link.get("href"):
resources.append(OrgResource(
rir = rir.value,
resource_type = "entity",
handle = handle,
name = fn,
))
break
elif resp.status_code == 404:
pass # Not found in this RIR — expected
else:
return rir, resources, f"HTTP {resp.status_code} from {rir.value} entity search"
except httpx.TimeoutException:
return rir, resources, f"{rir.value} entity search timed out"
except Exception as exc:
return rir, resources, f"{rir.value}: {type(exc).__name__}: {exc}"
return rir, resources, None
async def search_org_all_rirs(org_name: str) -> tuple[list[OrgResource], list[str]]:
"""
Search for an organization across all 5 RIRs that support entity search.
LACNIC does not support RDAP entity search and is skipped.
Returns (resources, errors).
"""
all_resources: list[OrgResource] = []
all_errors: list[str] = []
searchable = {
rir: url for rir, url in RDAP_SEARCH_ENDPOINTS.items() if url is not None
}
async with httpx.AsyncClient() as client:
tasks = [
_search_org_in_rir(client, rir, base_url, org_name)
for rir, base_url in searchable.items()
]
results = await asyncio.gather(*tasks, return_exceptions=False)
for rir, resources, error in results:
all_resources.extend(resources)
if error:
all_errors.append(error)
if not searchable.get(RIRName.LACNIC):
all_errors.append("LACNIC: Entity search not supported via RDAP. Query LACNIC directly at https://query.milacnic.lacnic.net/home")
return all_resources, all_errors
# ──────────────────────────────────────────────────────────────
# Phase 3 — Historical Allocation Tracking
# ──────────────────────────────────────────────────────────────
def _is_asn_resource(resource: str) -> bool:
"""Return True if resource looks like an ASN (AS12345 or bare integer)."""
cleaned = resource.strip().upper()
if cleaned.startswith("AS"):
return cleaned[2:].isdigit()
return cleaned.isdigit()
def _normalize_resource(resource: str) -> tuple[str, str]:
"""Return (normalized_resource, resource_type) where type is 'asn' or 'prefix'."""
if _is_asn_resource(resource):
num = resource.strip().upper().lstrip("AS")
return f"AS{num}", "asn"
return resource.strip(), "prefix"
async def get_prefix_history(resource: str) -> PrefixHistoryResult:
"""
Fetch full registration history for a prefix or ASN from RIPE Stat.
Uses two complementary RIPE Stat endpoints:
historical-whois → object attribute changes over time (org, status, dates)
allocation-history → raw allocation/assignment event log
Think of this like a property deed history — every time the "land"
(IP block) changed hands or was subdivided, there is a record.
"""
normalized, rtype = _normalize_resource(resource)
events: list[HistoricalEvent] = []
errors: list[str] = []
current_holder: Optional[str] = None
current_rir: Optional[str] = None
registration_date: Optional[str] = None
sources: list[str] = []
params = {"resource": normalized, "sourceapp": "peerglass"}
async with httpx.AsyncClient() as client:
# ── 1. historical-whois: object attribute changes ──────────────
try:
resp = await client.get(
RIPE_STAT_HIST_WHOIS_URL, params=params, timeout=20.0, headers=DEFAULT_HEADERS
)
if resp.status_code == 200:
sources.append("RIPE Stat historical-whois")
data = resp.json().get("data", {})
objects = data.get("objects", [])
for obj in objects:
# Each object has a list of "versions" representing changes
versions = obj.get("versions", [])
obj_type = obj.get("type", "")
for i, version in enumerate(versions):
attrs = {a["key"]: a["value"] for a in version.get("attributes", []) if "key" in a and "value" in a}
version_date = version.get("from_time", "")[:10]
# Detect first registration
if i == 0 and not registration_date and version_date:
registration_date = version_date
events.append(HistoricalEvent(
event_date = version_date,
event_type = "created",
attribute = "object",
new_value = attrs.get("descr") or attrs.get("netname") or obj_type,
source = "RIPE Stat historical-whois",
))
# Detect org / holder changes between consecutive versions
if i > 0:
prev_attrs = {a["key"]: a["value"] for a in versions[i-1].get("attributes", []) if "key" in a and "value" in a}
for field in ("org", "mnt-by", "descr", "netname", "status"):
old_val = prev_attrs.get(field)
new_val = attrs.get(field)
if old_val and new_val and old_val != new_val:
events.append(HistoricalEvent(
event_date = version_date,
event_type = "transferred" if field in ("org", "mnt-by") else "updated",
attribute = field,
old_value = old_val,
new_value = new_val,
source = "RIPE Stat historical-whois",
))
# Track latest holder from most recent version
if i == len(versions) - 1:
current_holder = attrs.get("org") or attrs.get("descr") or attrs.get("netname")
else:
errors.append(f"historical-whois: HTTP {resp.status_code}")
except httpx.TimeoutException:
errors.append("historical-whois: request timed out")
except Exception as exc:
errors.append(f"historical-whois: {type(exc).__name__}: {exc}")
# ── 2. allocation-history: allocation/assignment events ─────────
try:
resp2 = await client.get(
RIPE_STAT_ALLOC_HIST_URL, params=params, timeout=20.0, headers=DEFAULT_HEADERS
)
if resp2.status_code == 200:
sources.append("RIPE Stat allocation-history")
data2 = resp2.json().get("data", {})
for record in data2.get("resources", []):
alloc_date = str(record.get("timelines", [{}])[0].get("starttime", ""))[:10] \
if record.get("timelines") else None
status_val = record.get("status", "")
rir_val = record.get("rir", "")
if rir_val and not current_rir:
current_rir = rir_val.upper()
if alloc_date and status_val:
events.append(HistoricalEvent(
event_date = alloc_date,
event_type = "allocation",
attribute = "status",
new_value = f"{status_val} (via {rir_val or 'unknown RIR'})",
source = "RIPE Stat allocation-history",
))
else:
errors.append(f"allocation-history: HTTP {resp2.status_code}")
except httpx.TimeoutException:
errors.append("allocation-history: request timed out")
except Exception as exc:
errors.append(f"allocation-history: {type(exc).__name__}: {exc}")
# Sort events by date, oldest first
events.sort(key=lambda e: e.event_date or "")
return PrefixHistoryResult(
resource = normalized,
resource_type = rtype,
current_holder = current_holder,
current_rir = current_rir,
registration_date = registration_date,
total_events = len(events),
events = events,
sources = sources,
errors = errors,
)
# ──────────────────────────────────────────────────────────────
# Phase 3 — Transfer Detection
# ──────────────────────────────────────────────────────────────
async def detect_transfers(resource: str) -> TransferDetectResult:
"""
Detect cross-org and cross-RIR transfers for a prefix or ASN.
Strategy:
1. Fetch full history via historical-whois
2. Look for org / mnt-by changes (= ownership transfer)
3. Look for rir-source changes (= cross-RIR transfer)
4. Enrich with current holder from RDAP
A transfer looks like: org changed from "GOOGLE-1" to "META-1" on date X.
A cross-RIR transfer is rarer — it means the block physically moved
between registries (e.g. ARIN → RIPE after an acquisition).
"""
normalized, rtype = _normalize_resource(resource)
transfers: list[TransferEvent] = []
errors: list[str] = []
sources: list[str] = []
current_holder: Optional[str] = None
current_rir: Optional[str] = None
first_registered: Optional[str] = None
notes: list[str] = []
params = {"resource": normalized, "sourceapp": "peerglass"}
async with httpx.AsyncClient() as client:
try:
resp = await client.get(
RIPE_STAT_HIST_WHOIS_URL, params=params, timeout=20.0, headers=DEFAULT_HEADERS
)
if resp.status_code == 200:
sources.append("RIPE Stat historical-whois")
data = resp.json().get("data", {})
for obj in data.get("objects", []):
versions = obj.get("versions", [])
if not versions:
continue
# Capture first registration date
t0 = versions[0].get("from_time", "")[:10]
if t0 and (not first_registered or t0 < first_registered):
first_registered = t0
for i in range(1, len(versions)):
prev = {a["key"]: a["value"] for a in versions[i-1].get("attributes", []) if "key" in a and "value" in a}
curr = {a["key"]: a["value"] for a in versions[i].get("attributes", []) if "key" in a and "value" in a}
vdate = versions[i].get("from_time", "")[:10]
# ── org change → intra-RIR or cross-org transfer ──
for field in ("org", "mnt-by"):
old_v = prev.get(field)
new_v = curr.get(field)
if old_v and new_v and old_v != new_v:
# Heuristic: if org handles differ in the RIR prefix, it's cross-RIR
def _rir_from_handle(h: str) -> Optional[str]:
for rir in ("AFRINIC", "APNIC", "ARIN", "LACNIC", "RIPE"):
if rir in h.upper():
return rir
return None
from_rir = _rir_from_handle(old_v)
to_rir = _rir_from_handle(new_v)
ttype = "inter-rir" if (from_rir and to_rir and from_rir != to_rir) else "org-change"
transfers.append(TransferEvent(
transfer_date = vdate,
transfer_type = ttype,
from_org = old_v,
to_org = new_v,
from_rir = from_rir,
to_rir = to_rir,
evidence = f"{field} changed",
))
# Track current holder from most recent version
if i == len(versions) - 1:
current_holder = curr.get("org") or curr.get("descr") or curr.get("netname")
elif resp.status_code == 404:
notes.append("No historical data found. Resource may be too new or outside RIPE NCC's historical coverage.")
else:
errors.append(f"historical-whois: HTTP {resp.status_code}")
except httpx.TimeoutException:
errors.append("historical-whois: timed out")
except Exception as exc:
errors.append(f"historical-whois: {type(exc).__name__}: {exc}")
# Deduplicate transfers by date + evidence
seen: set[str] = set()
unique_transfers: list[TransferEvent] = []
for t in sorted(transfers, key=lambda x: x.transfer_date or ""):
key = f"{t.transfer_date}|{t.from_org}|{t.to_org}"
if key not in seen:
seen.add(key)
unique_transfers.append(t)
if rtype == "asn":
notes.append(
"Note: RIPE Stat historical-whois has best coverage for RIPE NCC resources. "
"For ARIN resources, cross-RIR transfer records are more limited via this API."
)
if not unique_transfers:
notes.append("No ownership transfers detected in available historical records. "
"This may mean the resource has never changed hands, or its history predates "
"RIPE Stat's coverage window.")
return TransferDetectResult(
resource = normalized,
resource_type = rtype,
transfers_detected= len(unique_transfers),
transfers = unique_transfers,
current_holder = current_holder,
current_rir = current_rir,
first_registered = first_registered,
sources = sources,
notes = notes,
)
# ──────────────────────────────────────────────────────────────
# Phase 3 — IPv4 / IPv6 / ASN Exhaustion Stats
# ──────────────────────────────────────────────────────────────
async def _fetch_rir_delegation_stats(
client: httpx.AsyncClient,
rir: str,
url: str,
include_blocks: bool = False,
status_filter: Optional[str] = None,
country_filter: Optional[str] = None,
) -> tuple[RIRDelegationStats, list[IPv4DelegatedBlock]]:
"""
Fetch and parse the NRO Extended Delegation Stats file for one RIR.
The file is a pipe-delimited text file. Summary lines look like:
arin|*|ipv4|0|7527|summary
arin|*|ipv6|0|18891|summary
arin|*|asn|0|73659|summary
Detail lines look like:
arin|US|ipv4|3.0.0.0|16777216|19941001|allocated
We parse both to build a complete picture.
"""
errors: list[str] = []
ipv4_blocks: list[IPv4DelegatedBlock] = []
stats_date: Optional[str] = None
ipv4_allocated = ipv4_assigned = ipv4_available = ipv4_total = 0
ipv6_allocated = ipv6_total = 0
asn_allocated = asn_total = 0
try:
resp = await client.get(url, timeout=30.0, follow_redirects=True,
headers={"User-Agent": DEFAULT_HEADERS["User-Agent"]})
if resp.status_code != 200:
errors.append(f"HTTP {resp.status_code} from {rir} delegation stats")
return RIRDelegationStats(rir=rir, region=RIR_REGIONS.get(rir, ""), errors=errors), []
for line in resp.text.splitlines():
line = line.strip()
if line.startswith("#") or not line:
continue
parts = line.split("|")
if len(parts) < 6:
continue
# Header line: version|registry|serial|records|startdate|enddate|UTCoffset
if parts[0].isdigit():
if len(parts) >= 5:
stats_date = parts[5][:8] if len(parts) > 5 else None
continue
rir_field = parts[0].upper()
type_field = parts[2].lower() if len(parts) > 2 else ""
value_field = parts[4] if len(parts) > 4 else "0"
status_field= parts[6].lower() if len(parts) > 6 else (parts[5].lower() if len(parts) > 5 else "")
# Summary lines: rir|*|type|0|count|summary
if len(parts) >= 6 and parts[5].lower() == "summary":