-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpeering_filters
executable file
·558 lines (469 loc) · 21.4 KB
/
peering_filters
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
#!/usr/bin/env python3
"""
KEES
The ColoClue Network Automation Toolchain
(c) 2014-2017 Job Snijders <[email protected]>
(c) 2017-2023 Network committee Coloclue <[email protected]>
"""
from subprocess import PIPE
from subprocess import Popen
from hashlib import sha256
from jinja2 import Environment, FileSystemLoader
from numpy import base_repr
from concurrent.futures import ProcessPoolExecutor, as_completed
import ipaddr
import json
import os
import requests
import sys
import time
import yaml
with open('vars/generic.yml') as genfile:
generic = yaml.safe_load(genfile)
def download(url, headers = {}):
headers['user-agent'] = 'coloclue-kees'
try:
r = requests.get(url, headers=headers)
downloaded_file = r.text
except requests.exceptions.RequestException:
print("Downloading %s failed" % url, file=sys.stderr)
sys.exit(2)
return downloaded_file
def readfile(filename):
try:
with open(filename, 'r') as reader:
filecontent = reader.read()
except:
print("Reading %s failed" % filename, file = sys.stderr)
sys.exit(2)
return filecontent
pdb_auth = {
"Authorization": (
"Api-Key " + os.environ.get('PEERINGDB_API_KEY', generic['pdb_apikey'])
)
}
netixlan = 'https://www.peeringdb.com/api/netixlan'
pdb_data = json.loads(download(netixlan, pdb_auth))
pdb = {}
for connection in pdb_data['data']:
asn = connection['asn']
v4 = connection['ipaddr4']
v6 = connection['ipaddr6']
if asn not in pdb:
pdb[asn] = []
if v4:
pdb[asn].append(v4)
if v6:
pdb[asn].append(v6)
net = 'https://www.peeringdb.com/api/net'
pdb_netdata = json.loads(download(net, pdb_auth))
max_prefixes = {}
for netdata in pdb_netdata['data']:
asn = 'AS' + str(netdata['asn'])
if asn not in max_prefixes:
max_prefixes[asn] = {}
if 'info_prefixes4' in netdata:
maxprefixes_v4 = netdata['info_prefixes4']
if maxprefixes_v4 < 100:
max_prefixes[asn]['v4'] = 100
else:
max_prefixes[asn]['v4'] = int(maxprefixes_v4 * 1.1)
if 'info_prefixes6' in netdata:
maxprefixes_v6 = netdata['info_prefixes6']
if maxprefixes_v6 < 100:
max_prefixes[asn]['v6'] = 100
else:
max_prefixes[asn]['v6'] = int(maxprefixes_v6 * 1.1)
# Defaults
generate_configs = False
generate_prefixsets = False
debugmode = False
do_checks = True
if 'all' in sys.argv:
generate_configs = True
generate_prefixsets = True
if 'prefixsets' in sys.argv:
generate_prefixsets = True
if 'configs' in sys.argv:
generate_configs = True
if '--no-checks' in sys.argv:
do_checks = False
print("Saw '--no-checks': skipping existence checks for prefix sets when generating config.")
if 'debug' in sys.argv:
debugmode = True
# For testing purposes, allow a local file as peering manifest
if "PEERINGS_FILE" in os.environ:
peerings_flat = readfile(os.environ.get('PEERINGS_FILE'))
else:
peerings_flat = download(generic['peerings_url'])
peerings = yaml.safe_load(peerings_flat)
# ip addresses should not be needed to define ourselves
# this could be retrieved from https://www.peeringdb.com/api/ixlan
ixp_map = {}
router_map = {}
for ixp in generic['ixp_map']:
ixp_map[ixp] = {}
ixp_map[ixp]['subnets'] = [ipaddr.IPNetwork(generic['ixp_map'][ixp]['ipv4_range']),
ipaddr.IPNetwork(generic['ixp_map'][ixp]['ipv6_range'])]
# Set a default bgp_local_pref of 100, allow for IXP based override
ixp_map[ixp]['bgp_local_pref'] = 100
if 'bgp_local_pref' in generic['ixp_map'][ixp]:
ixp_map[ixp]['bgp_local_pref'] = generic['ixp_map'][ixp]['bgp_local_pref']
router_map[ixp] = []
for router in generic['ixp_map'][ixp]['present_on']:
router_map[ixp].append(router)
multihop_source_map = {}
vendor_map = {}
for routername in generic['bgp']:
fqdn = generic['bgp'][routername]['fqdn']
multihop_source_map[fqdn] = {}
multihop_source_map[fqdn]['ipv4'] = generic['bgp'][routername]['ipv4']
multihop_source_map[fqdn]['ipv6'] = generic['bgp'][routername]['ipv6']
vendor_map[fqdn] = generic['bgp'][routername]['vendor']
allow_upto = {
4: "24",
6: "48"
}
# store the directory in which the script was started
# this is used to find template files
launchdir = os.getcwd()
# get output dir from environment, configuration or hard-coded default.
try:
outputdir = os.environ['BUILDDIR']
except KeyError:
outputdir = generic['builddir'] if 'builddir' in generic.keys() else '/opt/routefilters'
try:
os.chdir(outputdir)
except IOError:
print("%s does not exist?" % outputdir)
sys.exit(2)
if 'irr_source_host' in generic:
irr_source_host = generic['irr_source_host']
else:
irr_source_host = 'rr.ntt.net'
def render(tpl_path, context):
path, filename = os.path.split(launchdir + '/' + tpl_path)
env = Environment(loader=FileSystemLoader(path or './'))
env.trim_blocks = True
env.lstrip_blocks = True
env.rstrip_blocks = True
return env.get_template(filename).render(context)
def generate_filters(asn, as_set, irr_order, irr_source_host, loose = False):
# Default filter settings
filtername_prefix = 'AUTOFILTER'
filename_prefix = 'prefixset'
max_prefix_length = allow_upto
# Loose filtering settings
if (loose):
filtername_prefix = 'LOOSEFILTER'
filename_prefix = 'looseprefixset'
max_prefix_length = {
4: "32",
6: "128"
}
# inner function for actual bgpq3 execution
def run_bgpq3(filename, v, as_set, vendor, flags, subterm, asn, irr_order, irr_source_host):
stanza_name = "%s_%s_IPv%s%s" % (filtername_prefix, asn, v, subterm)
with open(filename, "w") as bgpq3_result:
if flags:
p = Popen(["bgpq3", "-h", irr_source_host, "-S", irr_order, "-R",
max_prefix_length[v], "-%s" % v, vendor] + flags +
["-l", stanza_name, "-A", asn] + as_set, stdout=bgpq3_result)
else:
p = Popen(["bgpq3", "-h", irr_source_host, "-S", irr_order, "-R",
max_prefix_length[v], "-%s" % v, vendor, "-l", stanza_name,
"-A", asn] + as_set, stdout=bgpq3_result)
if debugmode:
print("DEBUG: bgpq3 args: {}".format(p.args))
now = time.perf_counter() # record current performance counter
p.wait()
bgpq_duration = time.perf_counter() - now
if debugmode:
print("DEBUG: bgpq3 elapsed time: {}".format(bgpq_duration))
return p.returncode
# BIRD IPv4
for v in [4, 6]:
if as_set == "ANY":
continue
filename = '%s.%s.bird.ipv%s' % (asn, filename_prefix, v)
if os.path.exists(filename):
if time.time() - os.path.getmtime(filename) > 3600:
errno = run_bgpq3(filename, v, as_set, '-b', None, "", asn, irr_order, irr_source_host)
if errno != 0:
print("ERROR: bgpq3 returned non-zero for existing filename {}: {}".format(filename, errno))
print("bird ipv%s refreshed: %s" % (v, filename))
else:
print("bird ipv%s cached: %s" % (v, filename))
else:
errno = run_bgpq3(filename, v, as_set, '-b', None, "", asn, irr_order, irr_source_host)
if errno != 0:
print("ERROR: bgpq3 returned non-zero for existing filename {}: {}".format(filename, errno))
print("bird ipv%s created: %s" % (v, filename))
seen_router_policy = []
seen_bird_peers = {}
def config_snippet(asn, peer, description, ixp, router, no_filter,
export_full_table, limits, gtsm, peer_type,
multihop, disable_multihop_source_map, multihop_source_map, generic,
admin_down_state, block_importexport, bgp_local_pref, graceful_shutdown,
blackhole_accept, blackhole_community):
if peer_type not in ['upstream', 'peer', 'downstream']:
print("ERROR: invalid peertype: %s for %s" % (peer_type, asn))
sys.exit(2)
global seen_router_policy
vendor = vendor_map[router]
v = ipaddr.IPAddress(peer).version
policy_name = "AUTOFILTER:%s:IPv%s" % (asn, v)
if vendor == "bird":
global seen_bird_peers
if asn not in seen_bird_peers:
seen_bird_peers[asn] = 0
else:
seen_bird_peers[asn] = seen_bird_peers[asn] + 1
if no_filter:
filter_name = "ebgp_unfiltered_peering_import"
else:
filter_name = "peer_in_%s_ipv%s" % (asn, v)
password = None
if asn in generic['bgp_passwords']:
password = generic['bgp_passwords'][asn]
ixp_community = None
if 'ixp_community' in generic['ixp_map'][ixp]:
ixp_community = generic['ixp_map'][ixp]['ixp_community']
limit = limits[v]
neighbor_name = base_repr(int(sha256(str(peer).encode('utf-8')).hexdigest(), 16), 36)[:6]
peer_info = {'asn': asn.replace('AS', ''), 'afi': v,
'prefix_set': policy_name.replace(':', '_'),
'neigh_ip': peer,
'neigh_name': 'peer_%s_%s_%s' % (asn, ixp.replace('-',''), neighbor_name),
'description': description,
'filter_name': filter_name,
'limit': limit,
'gtsm': gtsm,
'multihop': multihop,
'disable_multihop_source_map': disable_multihop_source_map,
'password': password,
'peer_type': peer_type,
'source': multihop_source_map[router]["ipv%s" % v],
'export_full_table': export_full_table,
'ixp': ixp,
'ixp_community': ixp_community,
'rpki': generic['rpki'],
'admin_down_state': admin_down_state,
'block_importexport': block_importexport,
'bgp_local_pref': bgp_local_pref,
'graceful_shutdown': graceful_shutdown,
'blackhole_accept': blackhole_accept,
'blackhole_community': blackhole_community,
'loose_prefix_set': policy_name.replace('AUTOFILTER', 'LOOSEFILTER').replace(':', '_')
}
peer_config_blob = render('templates/peer.j2', peer_info)
f = open('%s.ipv%s.config' % (router, v), "a")
if not (router, asn, v) in seen_router_policy:
seen_router_policy.append((router, asn, v))
filter_config_blob = render('templates/filter.j2', peer_info)
f.write(filter_config_blob)
f.write(peer_config_blob)
f.close()
def ebgp_peer_type(asn):
if 'type' in peerings[asn]:
return peerings[asn]['type']
else:
return 'peer'
def ebgp_setting(setting, default_value, asn, ixp, session_ip):
ip = str(session_ip)
bgp_settings = {}
if 'bgp_settings' in generic:
bgp_settings = generic['bgp_settings']
if asn in bgp_settings:
if (('session' in bgp_settings[asn]) and
(ip in bgp_settings[asn]['session']) and
(setting in bgp_settings[asn]['session'][ip])):
return bgp_settings[asn]['session'][ip][setting]
if (('ixp' in bgp_settings[asn]) and
(ixp in bgp_settings[asn]['ixp']) and
(setting in bgp_settings[asn]['ixp'][ixp])):
return bgp_settings[asn]['ixp'][ixp][setting]
if (('common' in bgp_settings[asn]) and
(setting in bgp_settings[asn]['common'])):
return bgp_settings[asn]['common'][setting]
if setting in ixp_map[ixp]:
return ixp_map[ixp][setting]
# last resort
return default_value
def ebgp_local_pref(asn, ixp, session_ip):
setting = 'bgp_local_pref'
default_value = ebgp_local_pref_default(ebgp_peer_type(asn), 100)
return ebgp_setting(setting, default_value, asn, ixp, session_ip)
def ebgp_local_pref_default(peer_type, default_value = 100):
if peer_type == 'downstream':
return 500
if peer_type == 'upstream':
return 60
return default_value
def process_asn(asn, peerings, generic, generate_prefixsets, irr_source_host, do_checks):
results = []
if generate_prefixsets:
irr_order = (
peerings[asn].get('irr_order') or
generic.get('irr_order') or
"NTTCOM,INTERNAL,RADB,RIPE,ALTDB,BELL,LEVEL3,RGNET,APNIC,JPIRR,ARIN,BBOI,TC,AFRINIC,RPKI,"
"ARIN-WHOIS,REGISTROBR"
)
# Generate standard filters
generate_filters(asn, peerings[asn]['import'].split(), irr_order, irr_source_host)
results.append(f"Generated filters for {asn}")
# Generate loose filters for blackhole communities if applicable
if peerings[asn].get('blackhole_accept'):
generate_filters(asn, peerings[asn]['import'].split(), irr_order, irr_source_host, loose=True)
results.append(f"Generated loose filters for {asn}")
elif (not os.path.isfile(f'{asn}.prefixset.bird.ipv4') and
not os.path.isfile(f'{asn}.prefixset.bird.ipv6') and
do_checks):
results.append(f"Skipped {asn} due to missing files")
return results
for router in vendor_map:
if not generate_configs:
break
if vendor_map[router] == "bird":
try:
os.remove("%s.ipv4.config" % router)
os.remove("%s.ipv6.config" % router)
except OSError:
print("INFO: Config for %s wasn't present, no need to delete" % router)
with ProcessPoolExecutor(max_workers=10) as executor:
futures = [
executor.submit(process_asn, asn, peerings, generic, generate_prefixsets, irr_source_host, do_checks)
for asn in peerings
]
for future in as_completed(futures):
try:
result = future.result()
for res in result:
print(res)
except Exception as e:
print(f"Error processing ASN: {e}")
for asn in peerings:
sessions = []
if 'only_with' in peerings[asn]:
sessions = peerings[asn]['only_with']
elif 'private_peerings' in peerings[asn]:
sessions = peerings[asn]['private_peerings']
elif int(asn[2:]) in pdb:
sessions = pdb[int(asn[2:])]
if 'not_with' in peerings[asn]:
for remove_ip in peerings[asn]['not_with']:
sessions.remove(remove_ip)
else:
continue
for session in sessions:
session_ip = ipaddr.IPAddress(session)
for ixp in ixp_map:
for subnet in ixp_map[ixp]['subnets']:
bgp_local_pref = ebgp_local_pref(asn, ixp, session_ip)
if session_ip in subnet:
print("found peer %s in IXP %s with localpref %d" % (session_ip, ixp, bgp_local_pref))
print("must deploy on %s" % " ".join(router_map[ixp]))
description = peerings[asn]['description']
for router in router_map[ixp]:
routershort = router.split('.')[0]
routershortnodash = routershort.replace('-', '')
if 'only_on' in peerings[asn] and router not in peerings[asn]['only_on']:
continue
if 'not_on' in peerings[asn] and ixp in peerings[asn]['not_on']:
continue
peer_type = ebgp_peer_type(asn)
if peerings[asn]['import'] == "ANY":
no_filter = True
else:
no_filter = False
if peerings[asn]['export'] == "ANY":
export_full_table = True
else:
export_full_table = False
# set max prefix settings (if available)
limits = {}
if 'ipv4_limit' in peerings[asn]:
limits[4] = peerings[asn]['ipv4_limit']
elif asn in max_prefixes and 'v4' in max_prefixes[asn]:
limits[4] = max_prefixes[asn]['v4']
else:
limits[4] = 10000
if 'ipv6_limit' in peerings[asn]:
limits[6] = peerings[asn]['ipv6_limit']
elif asn in max_prefixes and 'v6' in max_prefixes[asn]:
limits[6] = max_prefixes[asn]['v6']
else:
limits[6] = 1000
gtsm = False
if 'gtsm' in peerings[asn]:
if peerings[asn]['gtsm']:
gtsm = True
multihop = False
if 'multihop' in peerings[asn]:
if peerings[asn]['multihop']:
multihop = True
disable_multihop_source_map = False
if 'disable_multihop_source_map' in peerings[asn]:
if peerings[asn]['disable_multihop_source_map']:
disable_multihop_source_map = True
blackhole_accept = False
if 'blackhole_accept' in peerings[asn]:
blackhole_accept = peerings[asn]['blackhole_accept']
blackhole_community = [ '65535:666' ]
if 'blackhole_community' in peerings[asn]:
blackhole_community = peerings[asn]['blackhole_community']
ixprouter = ixp + '-' + routershort
admin_down_state = False
# Is the IXP defined in the bgp_groups settings
if ixp in generic['bgp_groups']:
# If it has an admin_down_state setting
if 'admin_down_state' in generic['bgp_groups'][ixp]:
# Configure it to whatever it is set to in the config
admin_down_state = \
generic['bgp_groups'][ixp]['admin_down_state']
# If a specific router of an IXP connection is configured
if ixprouter in generic['bgp_groups']:
# If it has a admin_down_state setting, and it hasn't been configured above yet
if 'admin_down_state' in \
generic['bgp_groups'][ixprouter] \
and admin_down_state is False:
# Set it to whatever it is set to in the config
admin_down_state = \
generic['bgp_groups'][ixprouter]['admin_down_state']
graceful_shutdown = False
if ixp in generic['bgp_groups']:
if 'graceful_shutdown' in generic['bgp_groups'][ixp]:
graceful_shutdown = \
generic['bgp_groups'][ixp]['graceful_shutdown']
if ixprouter in generic['bgp_groups']:
if 'graceful_shutdown' in \
generic['bgp_groups'][ixprouter] \
and graceful_shutdown is False:
graceful_shutdown = \
generic['bgp_groups'][ixprouter]['graceful_shutdown']
if 'graceful_shutdown' in \
generic['bgp'][routershortnodash] \
and graceful_shutdown is False:
graceful_shutdown = \
generic['bgp'][routershortnodash]['graceful_shutdown']
block_importexport = False
if ixp in generic['bgp_groups'] or ixprouter in generic['bgp_groups']:
if 'block_importexport' in \
generic['bgp_groups'][ixp] \
or 'block_importexport' in generic['bgp_groups'][ixprouter]:
block_importexport = \
generic['bgp_groups'][ixp]['block_importexport']
if ixprouter in generic['bgp_groups']:
if 'block_importexport' \
in generic['bgp_groups'][ixprouter] \
and block_importexport is False:
block_importexport = \
generic['bgp_groups'][ixprouter]['block_importexport']
if not generate_configs:
continue
config_snippet(asn, str(session_ip), description, ixp,
router, no_filter, export_full_table,
limits, gtsm, peer_type, multihop, disable_multihop_source_map,
multihop_source_map, generic,
admin_down_state, block_importexport, bgp_local_pref, graceful_shutdown,
blackhole_accept, blackhole_community)