-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathapi.py
More file actions
350 lines (290 loc) · 11.4 KB
/
Copy pathapi.py
File metadata and controls
350 lines (290 loc) · 11.4 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API endpoints for the NLNOG Looking Glass.
This file provides JSON API endpoints for the NLNOG Looking Glass functionality.
"""
import operator
from datetime import datetime, timedelta, timezone
from urllib.parse import unquote
import netaddr
from flask import abort, Blueprint, jsonify, request
from utils import (
get_asn_name,
get_community_descr_from_list,
get_peer_info,
get_ringnodes,
LGException,
openbgpd_command,
read_archive,
read_communities,
resolve,
whois_command,
write_archive,
)
api = Blueprint("api", __name__)
api.communitylist = {}
@api.route("/summary")
def api_bgp_summary():
"""API endpoint for BGP peer summary information."""
(data, totals) = get_peer_info(api.config, names_only=False)
if len(data) == 0:
return (
jsonify({"error": "No data received from the NLNOG Ring API endpoint."}),
500,
)
return jsonify({"peers": data, "totals": totals})
@api.route("/peer/<peer>")
def api_peer_details(peer: str):
"""API endpoint for peer details."""
ret, result = openbgpd_command(api.config["ROUTER"], "peer", {"neighbor": peer})
ringnodes = get_ringnodes()
if not ret:
return jsonify({"error": f"Failed to retrieve information for {peer}."}), 500
remote_as = int(result["neighbors"][0]["remote_as"])
return jsonify(
{
"peer": peer,
"data": result["neighbors"][0],
"ringnodes": ringnodes.get(remote_as, {}),
}
)
@api.route("/prefix")
def api_show_route_for_prefix():
"""API endpoint for prefix lookup."""
warnings = []
prefix = unquote(request.args.get("q", "").strip())
if not prefix:
return jsonify({"error": "No prefix specified."}), 400
args = {}
# Try to see if the argument is a network by typecasting it to IPNetwork
try:
net = netaddr.IPNetwork(prefix)
# Single addresses without a netmask would be a valid IPNetwork too, ignore them
if "/" in prefix:
if request.args.get("match", "exact") != "exact" and (
(netaddr.valid_ipv4(str(net.ip)) and net.prefixlen <= 16)
or (netaddr.valid_ipv6(str(net.ip)) and net.prefixlen <= 48)
):
warnings.append(
"Not showing more specific routes, too many results, showing exact matches only."
)
elif request.args.get("match") == "orlonger":
args["all"] = 1
except netaddr.core.AddrFormatError:
if not netaddr.valid_ipv4(prefix) and not netaddr.valid_ipv6(prefix):
# Test domain resolution
resolved = resolve(prefix)
# Make sure the received answer is either valid IPv4 or IPv6
if resolved and (
netaddr.valid_ipv4(resolved) or netaddr.valid_ipv6(resolved)
):
prefix = resolved
else:
return (
jsonify(
{"error": f"{prefix} is not a valid IPv4 or IPv6 address."}
),
400,
)
args["prefix"] = prefix
result = {"rib": []}
nodelist = []
if request.args.get("all") == "all":
nodelist = ["all"]
else:
nodelist = request.args.getlist("peer")
if not nodelist:
# If no peers specified, use all
nodelist = ["all"]
for peername in nodelist:
if peername != "all":
args["neighbor"] = peername
# Query the OpenBGPD API endpoint
status, peerresult = openbgpd_command(api.config["ROUTER"], "route", args=args)
if not status:
return (
jsonify({"error": "Failed to query the NLNOG Looking Glass backend."}),
500,
)
if "rib" in peerresult:
result["rib"] = result["rib"] + peerresult["rib"]
try:
query_id = write_archive(result, prefix, ",".join(nodelist), api.config)
except LGException:
return jsonify({"error": "Failed to store results."}), 500
routes = {}
ringnodes = get_ringnodes()
create_date = None
if result.get("created", False):
create_date = datetime.utcfromtimestamp(result["created"]).strftime(
"%Y-%m-%d %H:%M:%S UTC"
)
if "rib" in result:
now = datetime.now(timezone.utc)
for route in result.get("rib", []):
delta = timedelta(seconds=int(route.get("last_update_sec", 0)))
timestamp = now - delta
otc = ""
for attribute in route.get("attributes", []):
if attribute["type"] == "OTC":
otc = (attribute["as"], get_asn_name(str(attribute["as"])))
if route["prefix"] not in routes:
routes[route["prefix"]] = []
routes[route["prefix"]].append(
{
"peer": route["neighbor"].get("description", "no description"),
"ip": route["neighbor"]["remote_addr"],
"bgp_id": route["neighbor"]["bgp_id"],
"aspath": [
(r, get_asn_name(r)) for r in route["aspath"].split(" ")
],
"origin": route["origin"],
"source": route["source"],
"communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("communities", [])
],
"extended_communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("extended_communities", [])
],
"large_communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("large_communities", [])
],
"valid": route["valid"],
"ovs": route["ovs"],
"avs": route.get("avs", "unknown"),
"exit_nexthop": route["exit_nexthop"],
"last_update": route["last_update"],
"last_update_at": timestamp.strftime("%Y-%m-%d %H:%M:%S UTC"),
"metric": route["metric"],
"otc": otc,
}
)
# Sort output by peername per prefix
for pfx in routes:
routes[pfx].sort(key=operator.itemgetter("peer"))
return jsonify(
{
"query_id": query_id,
"prefix": prefix,
"routes": routes,
"warnings": warnings,
"collected": create_date,
}
)
@api.route("/prefix/saved/<query_id>")
def api_show_saved_route(query_id):
"""API endpoint for retrieving saved prefix lookup results."""
try:
(result, prefix, nodelist) = read_archive(query_id, api.config)
except LGException as err:
return jsonify({"error": str(err)}), 400
routes = {}
ringnodes = get_ringnodes()
create_date = None
if result.get("created", False):
create_date = datetime.utcfromtimestamp(result["created"]).strftime(
"%Y-%m-%d %H:%M:%S UTC"
)
if "rib" in result:
now = datetime.now(timezone.utc)
for route in result.get("rib", []):
delta = timedelta(seconds=int(route.get("last_update_sec", 0)))
timestamp = now - delta
otc = ""
for attribute in route.get("attributes", []):
if attribute["type"] == "OTC":
otc = (attribute["as"], get_asn_name(str(attribute["as"])))
if route["prefix"] not in routes:
routes[route["prefix"]] = []
routes[route["prefix"]].append(
{
"peer": route["neighbor"].get("description", "no description"),
"ip": route["neighbor"]["remote_addr"],
"bgp_id": route["neighbor"]["bgp_id"],
"aspath": [
(r, get_asn_name(r)) for r in route["aspath"].split(" ")
],
"origin": route["origin"],
"source": route["source"],
"communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("communities", [])
],
"extended_communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("extended_communities", [])
],
"large_communities": [
(c, get_community_descr_from_list(c.strip(), api.communitylist))
for c in route.get("large_communities", [])
],
"valid": route["valid"],
"ovs": route["ovs"],
"avs": route.get("avs", "unknown"),
"exit_nexthop": route["exit_nexthop"],
"last_update": route["last_update"],
"last_update_at": timestamp.strftime("%Y-%m-%d %H:%M:%S UTC"),
"metric": route["metric"],
"otc": otc,
}
)
# Sort output by peername per prefix
for pfx in routes:
routes[pfx].sort(key=operator.itemgetter("peer"))
return jsonify(
{
"query_id": query_id,
"prefix": prefix,
"peers": nodelist,
"routes": routes,
"collected": create_date,
}
)
@api.route("/communities")
def api_communitylist():
"""API endpoint for community list."""
communities = []
for community in sorted([int(c) for c in read_communities(api.config)]):
communities.append({"asn": community, "name": get_asn_name(str(community))})
return jsonify({"communities": communities})
@api.route("/communities/<asn>")
def api_communitylist_specific(asn):
"""API endpoint for community details for a specific ASN."""
asn = unquote(asn.strip())
communitylist = read_communities(api.config)
if asn not in communitylist:
return jsonify({"error": f"ASN {asn} not found in community list."}), 404
asname = get_asn_name(asn)
return jsonify(
{"asn": asn, "name": asname, "communities": communitylist[asn]["raw"]}
)
@api.route("/statistics")
def api_stats():
"""API endpoint for statistics."""
result, stats = openbgpd_command(api.config["ROUTER"], "memory")
if not result:
return (
jsonify({"error": "Failed to retrieve Looking glass server statistics."}),
500,
)
return jsonify({"statistics": stats})
@api.route("/whois")
def api_whois():
"""API endpoint for whois requests."""
query = unquote(request.args.get("q", "").strip())
if not query:
return jsonify({"error": "No query specified."}), 400
try:
asnum = int(query)
query = f"as{asnum}"
except ValueError:
try:
netaddr.IPNetwork(query)
except netaddr.core.AddrFormatError:
return jsonify({"error": f"Invalid query: {query}"}), 400
output = whois_command(query, api.config)
return jsonify({"query": query, "output": output})