-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmonitor.py
executable file
·4139 lines (3802 loc) · 171 KB
/
monitor.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
#!/usr/bin/env python
# Copyright 2015 Check Point Software Technologies LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import StringIO
import argparse
import base64
import collections
import contextlib
import datetime
import email.utils
import fcntl
import hashlib
import httplib
import json
import logging
import logging.handlers
import os
import os.path
import random
import re
import signal
import socket
import ssl
import subprocess
import sys
import time
import traceback
import urllib
import urlparse
import aws
import azure
import gcp
TAG = 'managed-virtual-gateway'
CIDRS_REGEX = (r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}'
r'([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'
r'(\/([0-9]|[1-2][0-9]|3[0-2]))$')
pending_delete_gws = collections.OrderedDict()
conf = collections.OrderedDict()
log_buffer = [None]
def log(msg, level=logging.INFO):
logger = conf.get('logger')
if logger:
current_level = log_buffer[0]
if current_level != level:
line = ''.join(log_buffer[1:])
del log_buffer[:]
log_buffer.append(level)
if line:
logger.log(current_level, line)
if '\n' not in msg:
if msg:
log_buffer.append(msg)
return
lines = msg.split('\n')
lines[0] = ''.join(log_buffer[1:]) + lines[0]
if current_level != level and not lines[0]:
lines.pop(0)
del log_buffer[:]
log_buffer.append(level)
last = lines.pop()
if last:
log_buffer.append(last)
for line in lines:
logger.log(level, '%s', line)
else:
sys.stderr.write(msg)
def progress(msg):
if conf.get('logger'):
log('', level=None)
else:
log(msg)
def debug(msg):
if conf.get('debug'):
log(msg, level=logging.DEBUG)
def dump(obj):
debug('%s\n' % json.dumps(obj, indent=2))
# avoid printing sensitive data
@contextlib.contextmanager
def redact(active, log, redact_patterns):
line = []
if active:
stdout = sys.stdout
redact_patterns = [(re.compile(p), r) for p, r in redact_patterns]
def write(buf):
while buf:
end, newline, start = buf.partition('\n')
line.append(end)
if not newline:
return
buf = ''.join(line) + '\n'
for pattern, replacement in redact_patterns:
m = pattern.match(buf)
if m:
buf = buf[:m.start(1)] + replacement + buf[m.end(1):]
log('%s' % buf)
line[:] = []
buf = start
sys.stdout = StringIO.StringIO()
sys.stdout.write = write
yield
if active:
log('%s' % ''.join(line))
sys.stdout = stdout
class Template(object):
EXCLUDED = set(['proto'])
templates = collections.OrderedDict([(None, None)])
def __init__(self, name, **options):
self.name = name
self.proto = options.get('proto')
self.self = self
self.options = {
k: v for k, v in options.items() if k not in self.EXCLUDED}
self.templates[self.name] = self
def __getattr__(self, attr):
if attr in self.options:
return self.options[attr]
proto = Template.templates[self.proto]
if proto:
return getattr(proto, attr)
raise AttributeError()
@staticmethod
def get(name, attr, default=None):
template = Template.templates[name]
return getattr(template, attr, default)
@staticmethod
def get_dict(template):
result = {}
if not isinstance(template, Template):
template = Template.templates[template]
for k in template.options:
result[k] = template.options[k]
if template.proto:
for k, v in Template.get_dict(template.proto).items():
if k not in result:
result[k] = v
return result
@staticmethod
def get_templates():
return Template.templates
class Instance(object):
def __init__(
self, name, ip_address, interfaces, template, load_balancers=None):
self.name = name
self.ip_address = ip_address
self.interfaces = interfaces
self.template = template
self.load_balancers = load_balancers
def __str__(self):
return ' '.join([
self.name, self.ip_address, json.dumps(self.interfaces),
self.template, json.dumps(self.load_balancers)])
class VPNConn(object):
def __init__(self, name, controller, short_name, tag, gateway,
peer, local, remote, asn, pre_shared_key, tgw_id, cidr,
ready):
self.name = name
self.controller = controller
self.short_name = short_name
self.tag = tag
self.gateway = gateway
self.peer = peer
self.local = local
self.remote = remote
self.asn = asn
self.pre_shared_key = pre_shared_key
self.tgw_id = str(tgw_id or '')
self.cidr = cidr
self.ready = ready
def __str__(self):
name = self.name
if self.tag:
name = '%s(%s)' % (name, self.tag)
gw = self.gateway
return ' '.join([name, gw, self.peer, self.local, self.remote,
self.asn, self.cidr, self.tgw_id])
class Controller(object):
SEPARATOR = '--'
def __init__(self, **options):
self.name = options['name']
self.management = options['management']
self.templates = options.get('templates', [])
self.communities = options.get('communities', [])
self.sync = options.get('sync', {'gateway': True, 'lb': True}).copy()
def get_instances(self):
raise Exception('not implemented')
def get_vpn_conns(self, vpn_env=None, test=False):
return []
def filter_instances(self):
instances = []
for i in self.get_instances():
if self.templates and i.template not in self.templates:
continue
i.controller = self
instances.append(i)
return instances
@staticmethod
@contextlib.contextmanager
def Tester(cls, **options):
controller = cls(**options)
yield controller
if controller.sync.get('gateway', False):
instances = controller.filter_instances()
log('\n\nprovisioned gateways:')
log('\n '.join([''] + [str(i) for i in instances] + ['']))
if controller.sync.get('vpn', False):
vpn_conns = controller.get_vpn_conns(test=True)
log('\n\nvpn connection:')
log('\n '.join([''] + [str(v) for v in vpn_conns] + ['']))
@staticmethod
def test(cls, **options):
with Controller.Tester(cls, **options) as controller:
controller # do nothing but keep pyflakes happy
class AWS(Controller):
BASE_CRED_OPTS = ['access-key', 'secret-key', 'cred-file']
OPT_TO_ARG = {
'access-key': 'key', 'secret-key': 'secret', 'cred-file': 'key_file',
'sts-role': 'sts_role', 'sts-external-id': 'sts_ext_id'}
ARG_TO_ENV = {
'key': 'AWS_ACCESS_KEY_ID', 'secret': 'AWS_SECRET_ACCESS_KEY',
'key_file': 'AWS_KEY_FILE', 'sts_role': 'AWS_STS_ROLE',
'sts_ext_id': 'AWS_STS_EXTERNAL_ID', 'sts_session': 'AWS_STS_SESSION'}
CREDENTIAL = '__credential__'
VPC = '__vpc__'
VGW = '__vgw__'
RTB = '__rtb__'
NUM_CIDRS = 65536 // 4
FREE_CIDRS = {
'%s.%s' % (k * 4 // 256, k * 4 % 256) for k in xrange(NUM_CIDRS)} - {
'0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '169.252'}
PORT_REGEX = (r'[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}'
r'|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]')
def __init__(self, **options):
super(AWS, self).__init__(**options)
self.deletion_tolerance = int(options.get('deletion-tolerance', '0'))
self.regions = options['regions']
sts_session = 'autoprovision-%s' % (
datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ'))
kwargs = {a: options.get(o) for o, a in self.OPT_TO_ARG.items()}
kwargs['sts_session'] = sts_session if 'sts-role' in options else None
self.aws = aws.AWS(**kwargs)
self.env_creds = {None: {
e: kwargs[a] for a, e in self.ARG_TO_ENV.items() if kwargs[a]}}
self.sub_creds = {}
if 'sub-creds' in options:
for sub_cred in options['sub-creds']:
val = options['sub-creds'][sub_cred]
if 'sts-role' in val:
if all(k not in val for k in self.BASE_CRED_OPTS):
val.update({k: options[k]
for k in self.BASE_CRED_OPTS
if k in options})
kwargs = {
a: val.get(o) for o, a in self.OPT_TO_ARG.items()}
kwargs['sts_session'] = (
sts_session if 'sts-role' in val else None)
self.sub_creds[sub_cred] = aws.AWS(**kwargs)
self.env_creds = {sub_cred: {
e: kwargs[a]
for a, e in self.ARG_TO_ENV.items() if kwargs[a]}}
self.sync_tgw = False
templates = (self.templates if self.templates else
Template.get_templates())
for template in templates:
if template:
if Template.get_dict(template).get('deployment-type') == 'TGW':
self.sync_tgw = True
break
def request(self, service, *args, **kwargs):
aws_obj = self.aws
sub_cred = kwargs.pop('sub_cred', None)
if sub_cred is not None:
aws_obj = self.sub_creds[sub_cred]
delays = [.5, 1., 2., 5.]
while True:
headers, body = aws_obj.request(service, *args, **kwargs)
if headers.get('_code') == '200':
return headers, body
error = None
code = None
if headers.get('_parsed'):
if 'Errors' in body:
errors = aws.listify(body['Errors'], 'Error')
else:
errors = [body.get('Error')]
error = errors[0] if errors else {}
code = error.get('Code')
if not error or not code:
msg = 'UnparsedError: %s (%s)' % (
headers.get('_reason', '-'), headers.get('_code', '-'))
else:
msg = '%s: %s' % (code, error.get('Message', '-'))
retry = (headers.get('_code', ' ')[0] == '5' or
code and code.lower() == 'throttling')
if not delays or not retry:
if sub_cred is not None:
log('\nrequest failed for sub account: %s' % sub_cred)
raise Exception(msg)
log('\n%s request failed: %s [%s]' % (service, msg, len(delays)))
time.sleep(delays.pop(0))
def retrieve_subnets(self):
subnets = {}
for region in self.regions:
subnets[region] = {}
headers, body = self.request(
'ec2', region, 'GET', '/?Action=DescribeSubnets', '')
for s in aws.listify(body, 'item')['subnetSet']:
subnets[region][s['subnetId']] = s
return subnets
def retrieve_interfaces(self):
interfaces = {}
for region in self.regions:
interfaces[region] = {}
headers, body = self.request(
'ec2', region, 'GET',
'/?Action=DescribeNetworkInterfaces', '')
for i in aws.listify(body, 'item')['networkInterfaceSet']:
interfaces[region][i['networkInterfaceId']] = i
return interfaces
def register_internal_lb(self, lb, by_template):
tags = lb['Tags']
if tags.get('x-chkp-management') != self.management:
return
ignore_ports = tags.get('x-chkp-ignore-ports', [])
if ignore_ports:
ignore_ports = set(ignore_ports.split(':'))
http_ports = tags.get('x-chkp-http-ports', [])
if http_ports:
http_ports = set(http_ports.split(':'))
https_ports = tags.get('x-chkp-https-ports', [])
if https_ports:
https_ports = set(https_ports.split(':'))
ssl_ports = tags.get('x-chkp-ssl-ports', [])
if ssl_ports:
ssl_ports = set(ssl_ports.split(':'))
bad_ports = ', '.join({p[1:] for p in set(
http_ports) | set(https_ports) if p.startswith('@')})
if bad_ports:
raise Exception(
'the "@" annotation is deprecated in x-chkp-http-ports and '
'x-chkp-https-ports, and is used with ports %s, consider using'
' x-chkp-forwarding instead' % bad_ports)
if set(http_ports) & set(ssl_ports):
raise Exception(
'overlapping ports in x-chkp-http-ports and '
'x-chkp-ssl-ports with ports: %s'
% list(http_ports & ssl_ports))
if set(https_ports) & set(ssl_ports):
raise Exception(
'overlapping ports in x-chkp-https-ports and '
'x-chkp-ssl-ports with ports: %s'
% list(https_ports & ssl_ports))
source_cidrs = tags.get('x-chkp-source-cidrs', '') or set()
if source_cidrs:
source_cidrs = set(source_cidrs.split())
bad_cidrs = {s for s in source_cidrs if not re.compile(
CIDRS_REGEX).match(s)}
if '0.0.0.0/0' in source_cidrs:
source_cidrs = set()
if bad_cidrs:
raise Exception(
'malformed CIDRs: %s in tag x-chkp-source-cidrs' %
', '.join(bad_cidrs))
source_object = tags.get('x-chkp-source-object', '') or set()
if source_object:
source_object = {source_object}
forwarding_rules = tags.get('x-chkp-forwarding', '') or set()
if forwarding_rules:
forwarding_rules = set(forwarding_rules.split())
bad_rules = {r for r in forwarding_rules if not re.compile(
r'(TCP|HTTP|HTTPS|SSL)(-(%s)){2}$' % self.PORT_REGEX).match(r)}
if bad_rules:
raise Exception(
'malformed forwarding rules: %s in tag x-chkp-forwarding' %
', '.join(bad_rules))
protocol_ports = []
for pp in [p1 for p1 in lb['Front'] if p1.split('-')[1] not in [
p2.split('-')[2] for p2 in forwarding_rules]] + list(
forwarding_rules):
protocol, port, translated = (pp.split('-') + [None])[:3]
if port in ignore_ports:
continue
if port in ['444', '8082', '8880']:
raise Exception(
'Port %s cannot be used for internal LB listener'
% port)
if port in {'80', '443'} and not translated:
protocol = 'HTTP' if port == '80' else 'HTTPS'
port, translated = (str(int(port) + 9000), port)
if port in http_ports:
protocol = 'HTTP'
if port in https_ports:
protocol = 'HTTPS'
if port in ssl_ports:
protocol = 'SSL'
protocol_ports.append('%s-%s-%s' % (protocol, port,
translated or port))
template = tags.get('x-chkp-template')
by_template.setdefault(template, {})
by_template[template][lb['DNSName']] = (protocol_ports, source_cidrs
| source_object)
def retrieve_all_elbs(self, region, sub_cred=None):
elb_list = self.retrieve_all(
'elasticloadbalancing', region, '/?Action=DescribeLoadBalancers',
'DescribeLoadBalancersResult', 'LoadBalancerDescriptions',
sub_cred=sub_cred)
for elb in elb_list:
headers, body = self.request(
'elasticloadbalancing', region, 'GET',
'/?Action=DescribeTags&LoadBalancerNames.member.1=' +
elb['LoadBalancerName'], '', sub_cred=sub_cred)
elb['Tags'] = self.get_tags(aws.listify(
body['DescribeTagsResult']['TagDescriptions'],
'member')[0].get('Tags'))
protocol_ports = []
for listener in elb['ListenerDescriptions']:
protocol_ports.append('%s-%s' % (
listener['Listener']['Protocol'],
listener['Listener']['LoadBalancerPort']))
elb['Front'] = protocol_ports
v2lb_dict = {
v2lb['DNSName']: v2lb
for v2lb in self.retrieve_all(
'elasticloadbalancing', region,
'/?Version=2015-12-01&Action=DescribeLoadBalancers',
'DescribeLoadBalancersResult', 'LoadBalancers',
sub_cred=sub_cred)}
for v2lb in v2lb_dict.values():
headers, body = self.request(
'elasticloadbalancing', region, 'GET',
'/?' + urllib.urlencode({
'Version': '2015-12-01',
'Action': 'DescribeTags',
'ResourceArns.member.1': v2lb['LoadBalancerArn']}), '',
sub_cred=sub_cred)
v2lb['Tags'] = self.get_tags(aws.listify(
body['DescribeTagsResult']['TagDescriptions'],
'member')[0].get('Tags'))
v2lb['Listeners'] = self.retrieve_all(
'elasticloadbalancing', region,
'/?' + urllib.urlencode({
'Version': '2015-12-01',
'Action': 'DescribeListeners',
'LoadBalancerArn': v2lb['LoadBalancerArn']}),
'DescribeListenersResult', 'Listeners', sub_cred=sub_cred)
protocol_ports = []
for listener in v2lb['Listeners']:
protocol_ports.append('%s-%s' % (
listener['Protocol'], listener['Port']))
v2lb['Front'] = protocol_ports
return elb_list, v2lb_dict
def retrieve_classic_lbs(self, subnets, auto_scaling_groups,
elb_list, by_template, by_instance):
i2lb_names = {}
lb_name2cidrs = {}
for elb in elb_list:
try:
cidrs = [subnets[s]['cidrBlock'] for s in elb['Subnets']]
except Exception:
log('\n%s' % traceback.format_exc())
continue
back_ports = []
for listener in elb['ListenerDescriptions']:
back_ports.append(
'%s' % listener['Listener']['InstancePort'])
self.register_internal_lb(elb, by_template)
lb_name = elb['LoadBalancerName']
for i in elb['Instances']:
i2lb_names.setdefault(i['InstanceId'], set()).add(
elb['LoadBalancerName'])
lb_name2cidrs.setdefault(lb_name, {})
for port in back_ports:
lb_name2cidrs[lb_name][port] = cidrs
for group in auto_scaling_groups:
for i in group['Instances']:
i2lb_names.setdefault(i['InstanceId'], set()).update(
group['LoadBalancerNames'])
for i in i2lb_names:
by_instance.setdefault(i, {})
for lb_name in i2lb_names[i]:
for port in lb_name2cidrs.get(lb_name, {}):
by_instance[i].setdefault(port, []).append(
((lb_name2cidrs[lb_name].get(port, [])), False))
def retrieve_v2_lbs(self, region, subnets, auto_scaling_groups, v2lb_dict,
by_template, by_instance):
i2target_groups = {}
for auto_scale_group in auto_scaling_groups:
for i in auto_scale_group['Instances']:
for target in auto_scale_group['TargetGroupARNs']:
i2target_groups.setdefault(i['InstanceId'], {}).setdefault(
target, set())
target_groups = self.retrieve_all(
'elasticloadbalancing', region,
'/?Version=2015-12-01&Action=DescribeTargetGroups',
'DescribeTargetGroupsResult', 'TargetGroups')
for target_group in target_groups:
if target_group['TargetType'] == 'lambda':
continue
default_port = target_group['Port']
for i in i2target_groups:
if target_group['TargetGroupArn'] in i2target_groups[i]:
i2target_groups[i][target_group['TargetGroupArn']].add(
default_port)
headers, body = self.request(
'elasticloadbalancing', region, 'GET',
'/?' + urllib.urlencode({
'Version': '2015-12-01',
'Action': 'DescribeTargetHealth',
'TargetGroupArn': target_group['TargetGroupArn']}), '')
targets = aws.listify(body['DescribeTargetHealthResult'][
'TargetHealthDescriptions'], 'member')
for target in targets:
i2target_groups.setdefault(
target['Target']['Id'], {}).setdefault(
target_group['TargetGroupArn'], set()).add(
target['Target']['Port'])
dns_name2cidrs = {}
target_group2dns_names = {}
for v2lb in v2lb_dict.values():
dns_name = v2lb['DNSName']
try:
cidrs = [
subnets[az['SubnetId']]['cidrBlock']
for az in v2lb['AvailabilityZones']]
except Exception:
log('\n%s' % traceback.format_exc())
continue
dns_name2cidrs.setdefault(dns_name, []).extend(cidrs)
for listener in v2lb['Listeners']:
rules = self.retrieve_all(
'elasticloadbalancing', region,
'/?' + urllib.urlencode({
'Version': '2015-12-01',
'Action': 'DescribeRules',
'ListenerArn': listener['ListenerArn']}),
'DescribeRulesResult', 'Rules')
for rule in rules:
for action in rule['Actions']:
if 'TargetGroupArn' not in action:
continue
target_group2dns_names.setdefault(
action['TargetGroupArn'], set()).add(dns_name)
self.register_internal_lb(v2lb, by_template)
for i in i2target_groups:
by_instance.setdefault(i, {})
for target_group in i2target_groups[i]:
for port in i2target_groups[i][target_group]:
for dns_name in target_group2dns_names.get(
target_group, []):
by_instance[i].setdefault(port, []).append(
(dns_name2cidrs[dns_name],
v2lb_dict[dns_name]['Type'] == 'network'))
def retrieve_foreign_internal_lbs(self, region, by_template):
for sub_cred in self.sub_creds:
elb_list, v2lb_dict = self.retrieve_all_elbs(
region, sub_cred=sub_cred)
for elb in elb_list:
self.register_internal_lb(elb, by_template)
for v2lb in v2lb_dict.values():
self.register_internal_lb(v2lb, by_template)
def validate_port_overlap(self, by_template):
used_ports = {}
for template in by_template:
used_ports[template] = {}
for dns_name, (protocol_ports, cidrs) in by_template[
template].iteritems():
for port in [protocol_port.split('-')[1]
for protocol_port in protocol_ports]:
used_ports[template].setdefault(port, []).append(dns_name)
exception_msg = []
for port, DNS_name in [(port, used_ports[template][port]) for template
in used_ports for port in used_ports[template]
if 1 < len(used_ports[template][port])]:
exception_msg.append('Multiple listeners on port %s: %s' %
(port, ', '.join(DNS_name)))
if exception_msg:
raise Exception('\n' + '\n'.join(exception_msg))
def retrieve_elbs(self, subnets):
by_template = {}
by_instance = {}
result = {'by-template': by_template, 'by-instance': by_instance}
if not self.sync.get('lb', False):
return result
for region in self.regions:
by_template[region] = {}
by_instance[region] = {}
auto_scaling_groups = self.retrieve_all(
'autoscaling', region, '/?Action=DescribeAutoScalingGroups',
'DescribeAutoScalingGroupsResult', 'AutoScalingGroups')
elb_list, v2lb_dict = self.retrieve_all_elbs(region)
self.retrieve_classic_lbs(
subnets[region], auto_scaling_groups, elb_list,
by_template[region], by_instance[region])
self.retrieve_v2_lbs(
region, subnets[region], auto_scaling_groups, v2lb_dict,
by_template[region], by_instance[region])
self.retrieve_foreign_internal_lbs(region, by_template[region])
self.validate_port_overlap(by_template[region])
return result
def retrieve_all(self, service, region, path, top_set, collect_set,
sub_cred=None):
MEMBER = {'ec2': 'item'}.get(service, 'member')
MARKER = {
'autoscaling': 'NextToken',
'cloudformation': 'NextToken',
'ec2': 'NextToken',
'elasticloadbalancing': 'Marker'}[service]
NEXT_MARKER = {
'autoscaling': 'NextToken',
'cloudformation': 'NextToken',
'ec2': 'nextToken',
'elasticloadbalancing': 'NextMarker'}[service]
objects = []
marker = None
while True:
extra_params = ''
if marker:
extra_params += '&' + urllib.urlencode({MARKER: marker})
headers, body = self.request(
service, region, 'GET', path + extra_params, '',
sub_cred=sub_cred)
obj = aws.listify(body, MEMBER)
top = obj[top_set]
if top and not isinstance(top, list):
marker = top.get(NEXT_MARKER)
top = [top]
else:
marker = obj.get(NEXT_MARKER)
for r in top:
objects += r[collect_set]
if not marker:
break
return objects
def retrieve_instances(self):
instances = {}
for region in self.regions:
instances[region] = self.retrieve_all(
'ec2',
region,
'/?Action=DescribeInstances',
'reservationSet', 'instancesSet')
instances[region] = [
i for i in instances[region]
if self.get_tags(i.get('tagSet')).get(
'x-chkp-management') == self.management]
return instances
def get_tags(self, tag_list):
if not tag_list:
tag_list = []
tags = collections.OrderedDict()
joined = []
for t in tag_list:
k = t.get('key', t.get('Key'))
v = t.get('value', t.get('Value', ''))
if k.startswith('x-chkp-tags'):
joined.append((k[len('x-chkp-tags'):], v))
else:
tags[k] = v
for sep, joined_tags in sorted(joined):
if not sep:
sep = ':'
for part in joined_tags.split(sep):
key, es, value = part.partition('=')
tags.setdefault('x-chkp-' + key, value)
return tags
def get_topology(self, eni, subnets):
tags = self.get_tags(eni.get('tagSet'))
topology = tags.get('x-chkp-topology', '').lower()
anti_spoofing = (tags.get('x-chkp-anti-spoofing', 'true').lower() ==
'true')
if not topology:
if eni.get('association', {}).get('publicIp') or (
eni['attachment']['deviceIndex'] == '0'):
topology = 'external'
else:
topology = 'internal'
interface = {
'name': 'eth' + eni['attachment']['deviceIndex'],
'ipv4-address': eni['privateIpAddress'],
'ipv4-mask-length':
int(subnets[eni['subnetId']][
'cidrBlock'].partition('/')[2]),
'anti-spoofing': anti_spoofing,
'topology': topology
}
return interface
def get_instances(self):
ec2_instances = self.retrieve_instances()
enis = self.retrieve_interfaces()
subnets = self.retrieve_subnets()
elbs = self.retrieve_elbs(subnets)
instances = []
for region in self.regions:
for instance in ec2_instances[region]:
interfaces = []
instance_name = self.SEPARATOR.join(
[self.name, instance['instanceId'], region])
if instance['instanceState']['name'] in {
'shutting-down', 'terminated'}:
continue
tags = self.get_tags(instance.get('tagSet'))
ip_address = tags.get('x-chkp-ip-address', 'public')
if ip_address == 'private':
ip_address = instance['privateIpAddress']
elif ip_address == 'public':
ip_address = instance.get('ipAddress')
if not ip_address:
log('no ip address for %s\n' % instance_name)
continue
for interface in sorted(
instance['networkInterfaceSet'],
key=lambda i: int(i['attachment']['deviceIndex'])):
interfaces.append(self.get_topology(
enis[region][interface['networkInterfaceId']],
subnets[region]))
template = tags['x-chkp-template']
load_balancers = {}
internal_elbs = elbs['by-template'].get(
region, {}).get(template, {})
external_elbs = elbs['by-instance'].get(region, {}).get(
instance['instanceId'], {})
for dns_name in internal_elbs:
protocol_ports, tag_sources = internal_elbs[dns_name]
for protocol_port in protocol_ports:
cidrs_type = external_elbs.get(
protocol_port.split('-')[1], set())
transparent_cidrs = set(sum(
[ct[0] for ct in cidrs_type if ct[1]], []))
non_transparent_cidrs = set(sum(
[ct[0] for ct in cidrs_type if not ct[1]], []))
if tag_sources:
if non_transparent_cidrs:
raise Exception(
'\nexternal non NLB with cidr or object '
'tag on the internal LB %s' % dns_name)
sources = set(tag_sources) | transparent_cidrs
else:
if transparent_cidrs:
sources = set()
else:
sources = non_transparent_cidrs
load_balancers.setdefault(
dns_name, {})[protocol_port] = list(sources)
instances.append(Instance(
instance_name, ip_address, interfaces, template,
load_balancers))
return instances
def retrieve_vpcs(self, vpcs, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET',
'/?Action=DescribeVpcs&Version=2016-11-15', '',
sub_cred=sub_cred)
vpcs.setdefault(region, {})
for v in aws.listify(body, 'item')['vpcSet']:
v[self.CREDENTIAL] = sub_cred
vpcs[region][v['vpcId']] = v
def retrieve_vgws(self, vgws, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET', '/?Action=DescribeVpnGateways', '',
sub_cred=sub_cred)
vgws.setdefault(region, {})
for v in aws.listify(body, 'item')['vpnGatewaySet']:
vgws[region][v['vpnGatewayId']] = v
return vgws
def retrieve_vconns(self, vconns, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET',
'/?Action=DescribeVpnConnections&Version=2016-11-15', '',
sub_cred=sub_cred)
vconns.setdefault(region, {})
for s in aws.listify(body, 'item')['vpnConnectionSet']:
if 'customerGatewayConfiguration' not in s:
continue
vconns[region][s['vpnConnectionId']] = s
s['customerGatewayConfiguration'] = aws.parse_element(
aws.xml.dom.minidom.parseString(
s['customerGatewayConfiguration']))['vpn_connection']
if vconns[region][s['vpnConnectionId']].get(
'transitGatewayId'):
vconns[region][s['vpnConnectionId']]['ready'] = False
def retrieve_cgws(self, cgws, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET', '/?Action=DescribeCustomerGateways', '',
sub_cred=sub_cred)
cgws.setdefault(region, {})
for c in aws.listify(body, 'item')['customerGatewaySet']:
if c['state'] == 'deleted':
continue
c[self.CREDENTIAL] = sub_cred
cgws[region][c['customerGatewayId']] = c
def retrieve_rtbs(self, rtbs, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET', '/?Action=DescribeRouteTables', '',
sub_cred=sub_cred)
rtbs.setdefault(region, {})
for rtb in aws.listify(body, 'item')['routeTableSet']:
rtbs[region][rtb['routeTableId']] = rtb
def retrieve_tgw_route_tables(self, tgw_rtbs, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET',
'/?Action=' +
'DescribeTransitGatewayRouteTables&Version=2016-11-15'
'&Filter.1.Name=state&Filter.1.Value.1=available',
'', sub_cred=sub_cred)
tgw_rtbs.setdefault(region, {})
for a in aws.listify(body, 'item')['transitGatewayRouteTables']:
a[self.CREDENTIAL] = sub_cred
tgw_rtbs[region][a['transitGatewayRouteTableId']] = a
def retrieve_tgw_attachment_propagations(self, region, attach_id,
sub_cred):
propagations = set()
headers, body = self.request(
'ec2', region, 'GET', '/?Action=' +
'GetTransitGatewayAttachmentPropagations' +
'&Version=2016-11-15&TransitGatewayAttachmentId=' +
attach_id, '', sub_cred=sub_cred)
for p in aws.listify(
body, 'item')['transitGatewayAttachmentPropagations']:
if p['state'] != 'enabled':
continue
propagations.add(p['transitGatewayRouteTableId'])
return propagations
def retrieve_tgw_attachments(self, tgw_attachments, sub_cred):
for region in self.regions:
headers, body = self.request(
'ec2', region, 'GET',
'/?Action=' +
'DescribeTransitGatewayAttachments&Version=2016-11-15'
'&Filter.1.Name=state&Filter.1.Value.1=available',
'',
sub_cred=sub_cred)
tgw_attachments.setdefault(region, {})
for a in aws.listify(body, 'item')['transitGatewayAttachments']:
if a['state'] != 'available':
continue
a[self.CREDENTIAL] = sub_cred
tgw_attachments[region][a['transitGatewayAttachmentId']] = a
def retrieve_tgws(self, tgws, sub_cred):
for region in self.regions:
tgws.setdefault(region, {})
headers, body = self.request(
'ec2', region, 'GET',
'/?Version=2016-11-15&Action=DescribeTransitGateways'
'&Filter.1.Name=state&Filter.1.Value.1=available', '',
sub_cred=sub_cred)
for t in aws.listify(body, 'item')['transitGatewaySet']:
t[self.CREDENTIAL] = sub_cred
tgws[region][t['transitGatewayId']] = t
def retrieve_stacks(self, stacks, cred, test=False):
for region in self.regions:
stacks.setdefault('vpc', {}).setdefault(region, {})
stacks.setdefault('tgw', {}).setdefault(region, {})
log('\n\nvpn stacks:\n')
for stack in self.retrieve_all(
'cloudformation', region, '/?Action=DescribeStacks',
'DescribeStacksResult', 'Stacks', sub_cred=cred):
match = re.match(r'stack/vpn-by-tag--(vpc-[0-9a-z]+)/.*$',
stack['StackId'].split(':')[-1])
if not match:
match = re.match(
r'stack/vpn-by-tag--(tgw-[0-9a-z]+)--(.*)/.*$',
stack['StackId'].split(':')[-1])
if not match:
continue
else:
cgw_ip = match.group(2).replace('-', '.')
stacks['tgw'][region][cgw_ip] = stack
else:
vpc_id = match.group(1)
stacks['vpc'][region][vpc_id] = stack
log('\n%s: %s' % (stack['StackName'], stack['StackStatus']))
stack[self.CREDENTIAL] = cred
if '_FAILED' not in stack['StackStatus']:
continue
try:
reason = stack.get('StackStatusReason')
if reason:
log(': %s' % reason)
resources = self.retrieve_all(
'cloudformation', region,
'/?Action=DescribeStackResources&StackName=' +
stack['StackName'],
'DescribeStackResourcesResult', 'StackResources',
sub_cred=cred)
for resource in resources:
status = resource['ResourceStatus']
if '_PROGRESS' in status or '_COMPLETE' in status:
continue
log('\n %s: %s' % (
resource['LogicalResourceId'], status))
reason = resource.get('ResourceStatusReason')
if reason:
log(': %s' % reason)
finally:
if not test:
self.request(
'cloudformation', region, 'GET',
'/?Action=DeleteStack&StackName=' +
stack['StackName'], '', sub_cred=cred)