/
database.py
1749 lines (1620 loc) · 76.2 KB
/
database.py
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
import datetime
import logging
import os
import signal
import time
from xmlrpc.client import ServerProxy
import pytricia
import redis
import ujson as json
from kombu import Connection
from kombu import Consumer
from kombu import Exchange
from kombu import Queue
from kombu import uuid
from kombu.mixins import ConsumerProducerMixin
from utils import BACKEND_SUPERVISOR_URI
from utils import DB_HOST
from utils import DB_NAME
from utils import DB_PASS
from utils import DB_PORT
from utils import DB_USER
from utils import flatten
from utils import get_hash
from utils import get_ip_version
from utils import get_logger
from utils import hijack_log_field_formatter
from utils import HISTORIC
from utils import ModulesState
from utils import MON_SUPERVISOR_URI
from utils import ping_redis
from utils import purge_redis_eph_pers_keys
from utils import RABBITMQ_URI
from utils import REDIS_HOST
from utils import redis_key
from utils import REDIS_PORT
from utils import search_worst_prefix
from utils import signal_loading
from utils import translate_asn_range
from utils import translate_rfc2622
from utils import WITHDRAWN_HIJACK_THRESHOLD
from utils.tool import DB
# import os
log = get_logger()
TABLES = ["bgp_updates", "hijacks", "configs"]
VIEWS = ["view_configs", "view_bgpupdates", "view_hijacks"]
hij_log = logging.getLogger("hijack_logger")
mail_log = logging.getLogger("mail_logger")
try:
hij_log_filter = json.loads(os.getenv("HIJACK_LOG_FILTER", "[]"))
except Exception:
log.exception("exception")
hij_log_filter = []
class HijackLogFilter(logging.Filter):
def filter(self, rec):
if not hij_log_filter:
return True
for filter_entry in hij_log_filter:
for filter_entry_key in filter_entry:
if rec.__dict__[filter_entry_key] == filter_entry[filter_entry_key]:
return True
return False
mail_log.addFilter(HijackLogFilter())
hij_log.addFilter(HijackLogFilter())
class Database:
def __init__(self):
self.worker = None
signal.signal(signal.SIGTERM, self.exit)
signal.signal(signal.SIGINT, self.exit)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
def run(self):
try:
with Connection(RABBITMQ_URI) as connection:
self.worker = self.Worker(connection)
self.worker.run()
except Exception:
log.exception("exception")
finally:
log.info("stopped")
def exit(self, signum, frame):
if self.worker:
self.worker.ro_db.close()
self.worker.wo_db.close()
self.worker.should_stop = True
class Worker(ConsumerProducerMixin):
def __init__(self, connection):
self.connection = connection
self.prefix_tree = None
self.monitored_prefixes = set()
self.configured_prefix_count = 0
self.monitor_peers = 0
self.rules = None
self.timestamp = -1
self.insert_bgp_entries = []
self.handle_bgp_withdrawals = set()
self.handled_bgp_entries = set()
self.outdate_hijacks = set()
self.insert_hijacks_entries = {}
# DB variables
self.ro_db = DB(
application_name="backend-readonly",
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
reconnect=True,
autocommit=True,
readonly=True,
)
self.wo_db = DB(
application_name="backend-write",
user=DB_USER,
password=DB_PASS,
host=DB_HOST,
port=DB_PORT,
database=DB_NAME,
)
try:
self.wo_db.execute("TRUNCATE table process_states")
query = (
"INSERT INTO process_states (name, running) "
"VALUES (%s, %s) ON CONFLICT(name) DO UPDATE SET running = excluded.running"
)
for ctx in {BACKEND_SUPERVISOR_URI, MON_SUPERVISOR_URI}:
if not ctx:
continue
server = ServerProxy(ctx)
processes = [
(x["name"], x["state"] == 20)
for x in server.supervisor.getAllProcessInfo()
if x["name"] != "listener"
]
self.wo_db.execute_batch(query, processes)
except Exception:
log.exception("exception")
try:
query = (
"INSERT INTO intended_process_states (name, running) "
"VALUES (%s, %s) ON CONFLICT(name) DO NOTHING"
)
for ctx in {BACKEND_SUPERVISOR_URI, MON_SUPERVISOR_URI}:
if not ctx:
continue
server = ServerProxy(ctx)
processes = [
(x["group"], False)
for x in server.supervisor.getAllProcessInfo()
if x["group"] in ["monitor", "detection", "mitigation"]
]
self.wo_db.execute_batch(query, processes)
except Exception:
log.exception("exception")
# redis db
self.redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
ping_redis(self.redis)
self.bootstrap_redis()
# EXCHANGES
self.config_exchange = Exchange(
"config",
channel=connection,
type="direct",
durable=False,
delivery_mode=1,
)
self.update_exchange = Exchange(
"bgp-update",
channel=connection,
type="direct",
durable=False,
delivery_mode=1,
)
self.update_exchange.declare()
self.hijack_exchange = Exchange(
"hijack-update",
channel=connection,
type="direct",
durable=False,
delivery_mode=1,
)
self.hijack_exchange.declare()
self.hijack_hashing = Exchange(
"hijack-hashing",
channel=connection,
type="x-consistent-hash",
durable=False,
delivery_mode=1,
)
self.hijack_hashing.declare()
self.handled_exchange = Exchange(
"handled-update", type="direct", durable=False, delivery_mode=1
)
self.db_clock_exchange = Exchange(
"db-clock", type="direct", durable=False, delivery_mode=1
)
self.mitigation_exchange = Exchange(
"mitigation", type="direct", durable=False, delivery_mode=1
)
# QUEUES
self.update_queue = Queue(
"db-bgp-update",
exchange=self.update_exchange,
routing_key="update",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.withdraw_queue = Queue(
"db-withdraw-update",
exchange=self.update_exchange,
routing_key="withdraw",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.hijack_queue = Queue(
"db-hijack-update-{}".format(uuid()),
exchange=self.hijack_hashing,
routing_key="1",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.hijack_ongoing_request_queue = Queue(
"db-hijack-request-ongoing",
exchange=self.hijack_exchange,
routing_key="ongoing-request",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.hijack_outdate_queue = Queue(
"db-hijack-outdate",
exchange=self.hijack_exchange,
routing_key="outdate",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.hijack_resolve_queue = Queue(
"db-hijack-resolve",
exchange=self.hijack_exchange,
routing_key="resolve",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.hijack_ignore_queue = Queue(
"db-hijack-ignored",
exchange=self.hijack_exchange,
routing_key="ignore",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.handled_queue = Queue(
"db-handled-update",
exchange=self.handled_exchange,
routing_key="update",
durable=False,
auto_delete=True,
max_priority=1,
consumer_arguments={"x-priority": 1},
)
self.config_queue = Queue(
"db-config-notify",
exchange=self.config_exchange,
routing_key="notify",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.db_clock_queue = Queue(
"db-clock-{}".format(uuid()),
exchange=self.db_clock_exchange,
routing_key="pulse",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 3},
)
self.mitigate_queue = Queue(
"db-mitigation-start",
exchange=self.mitigation_exchange,
routing_key="mit-start",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.hijack_comment_queue = Queue(
"db-hijack-comment",
durable=False,
auto_delete=True,
max_priority=4,
consumer_arguments={"x-priority": 4},
)
self.hijack_seen_queue = Queue(
"db-hijack-seen",
exchange=self.hijack_exchange,
routing_key="seen",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.hijack_multiple_action_queue = Queue(
"db-hijack-multiple-action",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
self.hijack_delete_queue = Queue(
"db-hijack-delete",
exchange=self.hijack_exchange,
routing_key="delete",
durable=False,
auto_delete=True,
max_priority=2,
consumer_arguments={"x-priority": 2},
)
signal_loading("database", True)
self.config_request_rpc()
signal_loading("database", False)
def get_consumers(self, Consumer, channel):
return [
Consumer(
queues=[self.config_queue],
on_message=self.handle_config_notify,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.update_queue],
on_message=self.handle_bgp_update,
prefetch_count=100,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_queue],
on_message=self.handle_hijack_update,
prefetch_count=100,
accept=["ujson"],
),
Consumer(
queues=[self.withdraw_queue],
on_message=self.handle_withdraw_update,
prefetch_count=100,
accept=["ujson"],
),
Consumer(
queues=[self.db_clock_queue],
on_message=self._scheduler_instruction,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.handled_queue],
on_message=self.handle_handled_bgp_update,
prefetch_count=100,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_resolve_queue],
on_message=self.handle_resolve_hijack,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.mitigate_queue],
on_message=self.handle_mitigation_request,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_ignore_queue],
on_message=self.handle_hijack_ignore_request,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_comment_queue],
on_message=self.handle_hijack_comment,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_seen_queue],
on_message=self.handle_hijack_seen,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_multiple_action_queue],
on_message=self.handle_hijack_multiple_action,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_ongoing_request_queue],
on_message=self.handle_hijack_ongoing_request,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_outdate_queue],
on_message=self.handle_hijack_outdate,
prefetch_count=1,
accept=["ujson"],
),
Consumer(
queues=[self.hijack_delete_queue],
on_message=self.handle_delete_hijack,
prefetch_count=1,
accept=["ujson"],
),
]
def set_modules_to_intended_state(self):
try:
query = "SELECT name, running FROM intended_process_states"
entries = self.ro_db.execute(query)
modules_state = ModulesState()
for entry in entries:
# entry[0] --> module name, entry[1] --> intended state
# start only intended modules (after making sure they are stopped
# to avoid stale entries)
if entry[1]:
log.info("Setting {} to start state.".format(entry[0]))
modules_state.call(entry[0], "stop")
time.sleep(1)
modules_state.call(entry[0], "start")
except Exception:
log.exception("exception")
def config_request_rpc(self):
self.correlation_id = uuid()
callback_queue = Queue(
uuid(),
durable=False,
auto_delete=True,
max_priority=4,
consumer_arguments={"x-priority": 4},
)
self.producer.publish(
"",
exchange="",
routing_key="config-request-queue",
reply_to=callback_queue.name,
correlation_id=self.correlation_id,
retry=True,
declare=[
Queue(
"config-request-queue",
durable=False,
max_priority=4,
consumer_arguments={"x-priority": 4},
),
callback_queue,
],
priority=4,
serializer="ujson",
)
with Consumer(
self.connection,
on_message=self.handle_config_request_reply,
queues=[callback_queue],
accept=["ujson"],
):
while self.rules is None:
self.connection.drain_events()
def handle_bgp_update(self, message):
# log.debug('message: {}\npayload: {}'.format(message, message.payload))
message.ack()
msg_ = message.payload
# prefix, key, origin_as, peer_asn, as_path, service, type, communities,
# timestamp, hijack_key, handled, matched_prefix, orig_path
if not self.redis.getset(msg_["key"], "1"):
best_match = (
self.find_best_prefix_match(msg_["prefix"]),
) # matched_prefix
if not best_match:
return
try:
origin_as = -1
if len(msg_["path"]) >= 1:
origin_as = msg_["path"][-1]
value = (
msg_["prefix"], # prefix
msg_["key"], # key
origin_as, # origin_as
msg_["peer_asn"], # peer_asn
msg_["path"], # as_path
msg_["service"], # service
msg_["type"], # type
json.dumps(
[(k["asn"], k["value"]) for k in msg_["communities"]]
), # communities
datetime.datetime.fromtimestamp(
(msg_["timestamp"])
), # timestamp
[], # hijack_key
False, # handled
best_match,
json.dumps(msg_["orig_path"]), # orig_path
)
# insert all types of BGP updates
self.insert_bgp_entries.append(value)
# register the monitor/peer ASN from whom we learned this BGP update
self.redis.sadd("peer-asns", msg_["peer_asn"])
if self.redis.scard("peer-asns") != self.monitor_peers:
self.monitor_peers = self.redis.scard("peer-asns")
self.wo_db.execute(
"UPDATE stats SET monitor_peers=%s;", (self.monitor_peers,)
)
except Exception:
log.exception("{}".format(msg_))
# reset timer each time we hit the same BGP update
self.redis.expire(msg_["key"], 2 * 60 * 60)
def handle_withdraw_update(self, message):
# log.debug('message: {}\npayload: {}'.format(message, message.payload))
message.ack()
msg_ = message.payload
try:
# update hijacks based on withdrawal messages
value = (
msg_["prefix"], # prefix
msg_["peer_asn"], # peer_asn
datetime.datetime.fromtimestamp((msg_["timestamp"])), # timestamp
msg_["key"], # key
)
self.handle_bgp_withdrawals.add(value)
except Exception:
log.exception("{}".format(msg_))
def handle_hijack_outdate(self, message):
# log.debug('message: {}\npayload: {}'.format(message, message.payload))
message.ack()
try:
raw = message.payload
self.outdate_hijacks.add((raw["persistent_hijack_key"],))
except Exception:
log.exception("{}".format(message))
def handle_hijack_update(self, message):
# log.debug('message: {}\npayload: {}'.format(message, message.payload))
message.ack()
msg_ = message.payload
try:
key = msg_["key"] # persistent hijack key
if key not in self.insert_hijacks_entries:
# log.info('key {} at {}'.format(key, os.getpid()))
self.insert_hijacks_entries[key] = {}
self.insert_hijacks_entries[key]["prefix"] = msg_["prefix"]
self.insert_hijacks_entries[key]["hijack_as"] = msg_["hijack_as"]
self.insert_hijacks_entries[key]["type"] = msg_["type"]
self.insert_hijacks_entries[key]["time_started"] = msg_[
"time_started"
]
self.insert_hijacks_entries[key]["time_last"] = msg_["time_last"]
self.insert_hijacks_entries[key]["peers_seen"] = list(
msg_["peers_seen"]
)
self.insert_hijacks_entries[key]["asns_inf"] = list(
msg_["asns_inf"]
)
self.insert_hijacks_entries[key]["num_peers_seen"] = len(
msg_["peers_seen"]
)
self.insert_hijacks_entries[key]["num_asns_inf"] = len(
msg_["asns_inf"]
)
self.insert_hijacks_entries[key]["monitor_keys"] = set(
msg_["monitor_keys"]
)
self.insert_hijacks_entries[key]["time_detected"] = msg_[
"time_detected"
]
self.insert_hijacks_entries[key]["configured_prefix"] = msg_[
"configured_prefix"
]
self.insert_hijacks_entries[key]["timestamp_of_config"] = msg_[
"timestamp_of_config"
]
self.insert_hijacks_entries[key]["community_annotation"] = msg_[
"community_annotation"
]
self.insert_hijacks_entries[key]["rpki_status"] = msg_[
"rpki_status"
]
else:
self.insert_hijacks_entries[key]["time_started"] = min(
self.insert_hijacks_entries[key]["time_started"],
msg_["time_started"],
)
self.insert_hijacks_entries[key]["time_last"] = max(
self.insert_hijacks_entries[key]["time_last"], msg_["time_last"]
)
self.insert_hijacks_entries[key]["peers_seen"] = list(
msg_["peers_seen"]
)
self.insert_hijacks_entries[key]["asns_inf"] = list(
msg_["asns_inf"]
)
self.insert_hijacks_entries[key]["num_peers_seen"] = len(
msg_["peers_seen"]
)
self.insert_hijacks_entries[key]["num_asns_inf"] = len(
msg_["asns_inf"]
)
self.insert_hijacks_entries[key]["monitor_keys"].update(
msg_["monitor_keys"]
)
self.insert_hijacks_entries[key]["community_annotation"] = msg_[
"community_annotation"
]
self.insert_hijacks_entries[key]["rpki_status"] = msg_[
"rpki_status"
]
except Exception:
log.exception("{}".format(msg_))
def handle_handled_bgp_update(self, message):
# log.debug('message: {}\npayload: {}'.format(message, message.payload))
message.ack()
try:
key_ = (message.payload,)
self.handled_bgp_entries.add(key_)
except Exception:
log.exception("{}".format(message))
def build_prefix_tree(self):
log.info("Starting building database prefix tree...")
self.prefix_tree = {
"v4": pytricia.PyTricia(32),
"v6": pytricia.PyTricia(128),
}
raw_prefix_count = 0
for rule in self.rules:
try:
rule_translated_origin_asn_set = set()
for asn in rule["origin_asns"]:
this_translated_asn_list = flatten(translate_asn_range(asn))
rule_translated_origin_asn_set.update(
set(this_translated_asn_list)
)
rule["origin_asns"] = list(rule_translated_origin_asn_set)
rule_translated_neighbor_set = set()
for asn in rule["neighbors"]:
this_translated_asn_list = flatten(translate_asn_range(asn))
rule_translated_neighbor_set.update(
set(this_translated_asn_list)
)
rule["neighbors"] = list(rule_translated_neighbor_set)
conf_obj = {
"origin_asns": rule["origin_asns"],
"neighbors": rule["neighbors"],
}
for prefix in rule["prefixes"]:
for translated_prefix in translate_rfc2622(prefix):
ip_version = get_ip_version(translated_prefix)
if self.prefix_tree[ip_version].has_key(translated_prefix):
node = self.prefix_tree[ip_version][translated_prefix]
else:
node = {
"prefix": translated_prefix,
"data": {"confs": []},
}
self.prefix_tree[ip_version].insert(
translated_prefix, node
)
node["data"]["confs"].append(conf_obj)
raw_prefix_count += 1
except Exception:
log.exception("Exception")
log.info(
"{} prefixes integrated in database prefix tree in total".format(
raw_prefix_count
)
)
log.info("Finished building database prefix tree.")
# calculate the monitored and configured prefixes
log.info("Calculating configured and monitored prefixes in database...")
self.monitored_prefixes = set()
self.configured_prefix_count = 0
for ip_version in self.prefix_tree:
for prefix in self.prefix_tree[ip_version]:
self.configured_prefix_count += 1
monitored_prefix = search_worst_prefix(
prefix, self.prefix_tree[ip_version]
)
if monitored_prefix:
self.monitored_prefixes.add(monitored_prefix)
try:
self.wo_db.execute(
"UPDATE stats SET monitored_prefixes=%s, configured_prefixes=%s;",
(len(self.monitored_prefixes), self.configured_prefix_count),
)
except Exception:
log.exception("exception")
log.info("Calculated configured and monitored prefixes in database.")
def find_best_prefix_match(self, prefix):
ip_version = get_ip_version(prefix)
if prefix in self.prefix_tree[ip_version]:
return self.prefix_tree[ip_version].get_key(prefix)
return None
def handle_config_notify(self, message):
message.ack()
signal_loading("database", True)
log.info("Reconfiguring database due to conf update...")
log.debug("Message: {}\npayload: {}".format(message, message.payload))
config = message.payload
try:
if config["timestamp"] > self.timestamp:
self.timestamp = config["timestamp"]
self.rules = config.get("rules", [])
self.build_prefix_tree()
if "timestamp" in config:
del config["timestamp"]
raw_config = ""
if "raw_config" in config:
raw_config = config["raw_config"]
del config["raw_config"]
comment = ""
if "comment" in config:
comment = config["comment"]
del config["comment"]
config_hash = get_hash(raw_config)
self._save_config(config_hash, config, raw_config, comment)
except Exception:
log.exception("{}".format(config))
log.info("Database initiated, configured and running.")
signal_loading("database", False)
def handle_config_request_reply(self, message):
message.ack()
signal_loading("database", True)
log.info("Configuring database for the first time...")
log.debug("Message: {}\npayload: {}".format(message, message.payload))
config = message.payload
try:
if self.correlation_id == message.properties["correlation_id"]:
if config["timestamp"] > self.timestamp:
self.timestamp = config["timestamp"]
self.rules = config.get("rules", [])
self.build_prefix_tree()
if "timestamp" in config:
del config["timestamp"]
raw_config = ""
if "raw_config" in config:
raw_config = config["raw_config"]
del config["raw_config"]
comment = ""
if "comment" in config:
comment = config["comment"]
del config["comment"]
config_hash = get_hash(raw_config)
latest_config_in_db_hash = (
self._retrieve_most_recent_config_hash()
)
if config_hash != latest_config_in_db_hash:
self._save_config(config_hash, config, raw_config, comment)
else:
log.debug("database config is up-to-date")
except Exception:
log.exception("{}".format(config))
self.set_modules_to_intended_state()
log.info("Database initiated, configured and running.")
signal_loading("database", False)
def handle_hijack_ongoing_request(self, message):
message.ack()
timestamp = message.payload
# need redis to handle future case of multiple db processes
last_timestamp = self.redis.get("last_handled_timestamp")
if not last_timestamp or timestamp > float(last_timestamp):
self.redis.set("last_handled_timestamp", timestamp)
try:
results = []
query = (
"SELECT b.key, b.prefix, b.origin_as, b.as_path, b.type, b.peer_asn, "
"b.communities, b.timestamp, b.service, b.matched_prefix, h.key, h.hijack_as, h.type "
"FROM hijacks AS h LEFT JOIN bgp_updates AS b ON (h.key = ANY(b.hijack_key)) "
"WHERE h.active = true AND b.handled=true"
)
entries = self.ro_db.execute(query)
for entry in entries:
results.append(
{
"key": entry[0], # key
"prefix": entry[1], # prefix
"origin_as": entry[2], # origin ASN
"path": entry[3], # as_path
"type": entry[4], # type
"peer_asn": entry[5], # peer_asn
"communities": entry[6], # communities
"timestamp": entry[7].timestamp(), # timestamp
"service": entry[8], # service
"matched_prefix": entry[9], # configured prefix
"hij_key": entry[10],
"hijack_as": entry[11],
"hij_type": entry[12],
}
)
if results:
for result_bucket in [
results[i : i + 10] for i in range(0, len(results), 10)
]:
self.producer.publish(
result_bucket,
exchange=self.hijack_exchange,
routing_key="ongoing",
retry=False,
priority=1,
serializer="ujson",
)
except Exception:
log.exception("exception")
def bootstrap_redis(self):
try:
# bootstrap ongoing hijack events
query = (
"SELECT time_started, time_last, peers_seen, "
"asns_inf, key, prefix, hijack_as, type, time_detected, "
"configured_prefix, timestamp_of_config, community_annotation, rpki_status "
"FROM hijacks WHERE active = true"
)
entries = self.ro_db.execute(query)
redis_pipeline = self.redis.pipeline()
for entry in entries:
result = {
"time_started": entry[0].timestamp(),
"time_last": entry[1].timestamp(),
"peers_seen": set(entry[2]),
"asns_inf": set(entry[3]),
"key": entry[4],
"prefix": entry[5],
"hijack_as": entry[6],
"type": entry[7],
"time_detected": entry[8].timestamp(),
"configured_prefix": entry[9],
"timestamp_of_config": entry[10].timestamp(),
"community_annotation": entry[11],
"rpki_status": entry[12],
}
subquery = "SELECT key FROM bgp_updates WHERE %s = ANY(hijack_key);"
subentries = set(self.ro_db.execute(subquery, (entry[4],)))
subentries = set(map(lambda x: x[0], subentries))
log.debug(
"Adding bgpupdate_keys: {} for {} and {}".format(
subentries,
redis_key(entry[5], entry[6], entry[7]),
entry[4],
)
)
result["bgpupdate_keys"] = subentries
redis_hijack_key = redis_key(entry[5], entry[6], entry[7])
redis_pipeline.set(redis_hijack_key, json.dumps(result))
redis_pipeline.sadd("persistent-keys", entry[4])
redis_pipeline.execute()
# bootstrap BGP updates
query = (
"SELECT key, timestamp FROM bgp_updates "
"WHERE timestamp > NOW() - interval '2 hours' "
"ORDER BY timestamp ASC"
)
entries = self.ro_db.execute(query)
redis_pipeline = self.redis.pipeline()
for entry in entries:
expire = max(
int(entry[1].timestamp()) + 2 * 60 * 60 - int(time.time()), 60
)
redis_pipeline.set(entry[0], "1", ex=expire)
redis_pipeline.execute()
# bootstrap (origin, neighbor) AS-links of ongoing hijacks
query = (
"SELECT bgp_updates.prefix, bgp_updates.peer_asn, bgp_updates.as_path, "
"hijacks.prefix, hijacks.hijack_as, hijacks.type FROM "
"hijacks LEFT JOIN bgp_updates ON (hijacks.key = ANY(bgp_updates.hijack_key)) "
"WHERE bgp_updates.type = 'A' "
"AND hijacks.active = true "
"AND bgp_updates.handled = true"
)
entries = self.ro_db.execute(query)
redis_pipeline = self.redis.pipeline()
for entry in entries:
# store the origin, neighbor combination for this hijack BGP update
origin = None
neighbor = None
as_path = entry[2]
if as_path:
origin = as_path[-1]
if len(as_path) > 1:
neighbor = as_path[-2]
redis_hijack_key = redis_key(entry[3], entry[4], entry[5])
redis_pipeline.sadd(
"hij_orig_neighb_{}".format(redis_hijack_key),
"{}_{}".format(origin, neighbor),
)
# store the prefix and peer asn for this hijack BGP update
redis_pipeline.sadd(
"prefix_{}_peer_{}_hijacks".format(entry[0], entry[1]),
redis_hijack_key,
)
redis_pipeline.sadd(
"hijack_{}_prefixes_peers".format(redis_hijack_key),
"{}_{}".format(entry[0], entry[1]),
)
redis_pipeline.execute()
# bootstrap seen monitor peers
query = "SELECT DISTINCT peer_asn FROM bgp_updates"
entries = self.ro_db.execute(query)
redis_pipeline = self.redis.pipeline()
for entry in entries:
redis_pipeline.sadd("peer-asns", int(entry[0]))
redis_pipeline.execute()
self.monitor_peers = self.redis.scard("peer-asns")
self.wo_db.execute(
"UPDATE stats SET monitor_peers=%s;", (self.monitor_peers,)
)
except Exception: